C# Force file download

20 11 2007

To force a file to download, instead of being opened by the browser create a page called (something like) force.aspx and populate it with the C# code below. Then in the page containing the link that you want to force as a download use: <a href=”force.aspx?f=filename.ext”>Download</a> as the link, replacing filename.ext with the relevant filename.

The Code:

<%@ Page Language="C#" %><%
String File = "";
if (Request.Params.Get("f") != null) File = Convert.ToString(Request.Params.Get("f"));
if (File != "")
{
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename=" + File);
string FilePath = MapPath(File);
Response.WriteFile(FilePath);
Response.End();
}
else
{
Response.Write("Error: Invalid parameters.");
}
%>





Get month name based in int

20 03 2007

for (int i = 1; i <= 12; i++)

{

DateTime date = new DateTime(1,i,1);

DropDownDOBMonth.Items.Add(date.ToString(“MMM”));

}

 

More date formats.





Random number function

16 03 2007

private int RandomNumber(int min, int max)
{
Random random =
new Random();
return random.Next(min, max);
}

read moreĀ 





C# Date Formats

8 02 2007

Article here.





isEmail

1 02 2007

The following C# function returns true if the supplied inputEmail is a valid email address.

private static bool isEmail(string inputEmail)
{
  inputEmail =
NulltoString(inputEmail);
  string strRegex = @”^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}” +
  @”\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\” +
  @”.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$”;
  Regex re = new Regex(strRegex);
  if (re.IsMatch(inputEmail))
  return (true);
  else
  return (false);
}





isMobile

31 01 2007

This function returns true if the string provided is a valid South African mobile phone number in the following format: 27821234567.

private static bool isMobile(string inputMobile)
{
    inputMobile =
NulltoString(inputMobile);
    string strRegex = “(^27[78][2347][0-9]{7})”;
    Regex re = new Regex(strRegex);
    if (re.IsMatch(inputMobile))
        return (true);
    else
        return (false);
}





Assigning DB Null values to variables

31 01 2007

Database null values cannot be cast, or converted to a local variable. To get around this use the following snippet when assigning the value to the vairable, to first check if the database value is null. dr is the data reader.

String Message = “”;
if (!dr["Message"].Equals(DBNull.Value)) Message = dr["Message"].ToString();