Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, July 30, 2010

Useful Extension Method: SplitNoEmpty

I ran into a situation where there were some extra spaces in some splits I was doing. I was unaware there was an option StringSplitOptions.RemoveEmptyEntries, which would fix my problem. But to cut down on text in the code since I have splits all over the place, I created the following extension class.
public static class StringSplitExtension
{
public static string[] SplitNoEmpty(this string val, string delim)
{
return val.Split ( delim.ToCharArray (), StringSplitOptions.RemoveEmptyEntries );
}
}

So now, I just change my splits from-

mystring.split(' ');
to-
mystring.SplitNoEmpty(" ");




Wednesday, February 24, 2010

Monday, June 15, 2009

My HelloWorld LINQ Example

I know it is sad, but up until today I hadn't ever written a single LINQ query. So, for future prosterity, here is my hello world example.

 string[] s = { "test", "hello world", "mamma", "zack", "aaa","xxx" };
// LINQ
var subset = from z in s where z != "hello world"
orderby z descending select z;
int i = 0;
foreach (var l in subset)
{
Response.Write(
"Item " + i.ToString() + " = " + l + "<br />");
i++;
}

Friday, May 08, 2009

Getting the Public Key Token of An Assembly

This is a useful tip. If you stumbled here, you know why you need it.

Link

Monday, May 04, 2009

Executing a Console App from ASP.Net

Well, I was fooling around with a .Net API that does google tanslations. I thought it might be a good idea to not call the translating API for bulk translations directly from the website, so I created a little console app so I can do that and do a thread.Sleep pause and control the SQL Connection opening and closing a little more robustly. Anyway, here is some sample code on how to open a console from ASP.Net in C#

 // path to the console app
string sPath = Server.MapPath("~/apps/GoogleTranslationConsole.exe");
// pass your path, and your arguments array into a ProcessStartInfo
ProcessStartInfo proc = new ProcessStartInfo(sPath,Request.Form["lagr"]);
// Incase you want to read messages back from the code
proc.RedirectStandardOutput = true;
// hide any command windows from showing up
proc.UseShellExecute = false;
proc.CreateNoWindow =
true;
// create the process that will control the console app
Process p = new Process();
p.StartInfo = proc;
p.Start();

// use console.writeline for data to return back.
// Also, be sure to either p.Dispose() of your process here or do
// do a System.Environment.Exit in your console app when work is done
//p.StandardOutput.ReadToEnd() for results.


Here is the original link that I got this info from, which is in VB.Net.

Opening a Console App in VB.Net

Note: I haven't deployed this code to production yet, I've only got it working on my local box. In a production environment you probably want to make sure that your console apps aren't accessible by the web, that your console app is secure enough so that it only does what is should do when it should do it, and that only the right people can execute it (thought for my purposes probably the IIS account will probably have permission to execute). Just something to watch for once you are to that point.

Sunday, April 12, 2009

Free C# E-Book

Download your free C# 2008 Illustrated e-book from A-Press!

Free E-Book

Source: DotNetShoutOut.com

Thursday, October 16, 2008

Basic: A Recursive Function to Find All Control ID's in a Control

Sometimes you might have a control that has a lot of other controls burried in it. Here is a small very basic recursive function to find all the control id's. I'm posting it more for my reference. Just pass in a string builder and an int.

void RecurseFindControls(Control c, ref System.Text.StringBuilder sb, ref int iLevel)
{
if (c.ID != null)
{
sb.Append ( c.ID +
"[" + iLevel.ToString () + "];" );
}
if ( c.Controls.Count > 0 )
{
iLevel++;
for ( int j = 0 ; j < c.Controls.Count ; j++ )
{
RecurseFindControls ( c.Controls[ j ],
ref sb, ref iLevel );
}
}
}

Thursday, July 31, 2008

ASP.Net Dynamic File Download Protection

I spent a little while today playing with a way to stop users who haven't registered with a site from downloading files. With the help of two examples, I came up with the following. Hope it is useful. Just copy the code by highlighting it, as some of it might slide under the right column (I know, this is a cheesy way to post code, in the queue to do is to widen this blog template and to find a better code poster. Any suggestions for either are appreciated). Anyways, here is the code snippet.

//http://www.codeproject.com/KB/aspnet/SecureFileDownload.aspx
//http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2855600&SiteID=1
if (Request.QueryString["fid"] != null) //&& Session["uid"] != null)
{
string sPath = Server.MapPath("~") + "Your path here";
string sFileName = "";
if (Request.QueryString["fid"].ToString() == "1")
{
sPath +=
"real_file_name.config";
sFileName =
"display_file_name.pdf"; //or .doc, .jpg, .mp3, whatever
Response.AddHeader("content-disposition", "attachment; filename=" + sFileName);
Response.ContentType =
"application/octet-stream";
System.IO.
FileStream fs =
System.IO.
File.Open(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
Byte[] flen = new byte[256];
int iBytes = fs.Read(flen, 0, flen.Length);
Response.Buffer =
true;
Response.BinaryWrite(flen);
while (iBytes != 0)
{
iBytes = fs.Read(flen, 0, flen.Length);
Response.BinaryWrite(flen);
}
fs.Close();
Response.End();
}


Place this in either your Page_Init or Page_Onload, adjust the paths, names, and what not and you have your file protection (in the snippet the session check is commented out, but you can see what I was getting at). For your base file path you can use Server.MapPath("~") + "/whatevedirectory/". Also if you are writting to files, it is a good idea to keep these files in your App_Data directory, as I've heard (don't know if it is true) that messing with files outside that directory may cause your app to recycle.

The above code could probably be put into an HTTPModule, you could read real file names and display names from a database, or encrypt your query string, whatever, this will give you the basics.

Thursday, July 03, 2008

OO Class Keywords and What They Do

Ok, I come from a scripting web background, and even to this day some OOP stuff I either forget or have never officially "learned." I found a good link talking about the various forms of classes in OOP, might be useful.

http://www.functionx.com/csharp2/classes2/abstraction.htm