2009/04/13

GridView: Dynamically add cells

How to add a cell dynamically (or programmatically)? If you are going to add a cell without any control in it, here is the way:
e.Row.Cells[e.Row.Cells.Add(new TableCell())].Text = "Phone";
If you are going to add a cell with a server control in it (for example, TextBox), you should do like this:
//create a textbox control & set its attributes
TextBox oTB = new TextBox();
oTB.ID = "TextBox1";
oTB.AutoPostBack = true;
oTB.Attributes.Add("onfocus", "this.select();");
//attach the event
oTB.TextChanged += new EventHandler(TextBox_TextChanged);
//hey, the phone number here is just an example
oTB.Text = "1-800-551-1155";
//here is the key point
e.Row.Cells[e.Row.Cells.Add(new TableCell())].Controls.Add(oTB);
oTB = null;

PS: Add those codes to the GridView's RowDataBound event.

AES String Encryption/Decryption

public string AESforString(string rawString, string key, string IV, bool toEncrypt)
{
  try
  {
    RijndaelManaged oAES = new RijndaelManaged();
    Rfc2898DeriveBytes oRfc2898DeriveBytes = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(IV));

    oAES.Padding = PaddingMode.PKCS7;
    oAES.Mode = CipherMode.CBC;
    oAES.KeySize = 256;
    oAES.Key = oRfc2898DeriveBytes.GetBytes(32);
    oAES.BlockSize = 128;
    oAES.IV = oRfc2898DeriveBytes.GetBytes(16);

    byte[] rawData;
    byte[] result;
    if (toEncrypt)
    {
      rawData = Encoding.UTF8.GetBytes(rawString);
      result = oAES.CreateEncryptor().TransformFinalBlock(rawData, 0, rawData.Length);
      oAES.Clear();
      return Convert.ToBase64String(result);
    }
    else
    {
      rawData = Convert.FromBase64String(rawString);
      result = oAES.CreateDecryptor().TransformFinalBlock(rawData, 0, rawData.Length);
      oAES.Clear();
      return Encoding.UTF8.GetString(result);
    }
  }
  catch (CryptographicException cex)
  {
    return cex.Message;
  }
}

2009/04/08

The "Save As" function on the web form

Here is how I implement the "Save As" function: (let users download files from server)
private void SaveAs(string contents, string fileName)
{
  try
  {
    //setup the HTTP Header and push the contents to clients
    Response.ClearHeaders();
    Response.Clear();
    Response.Expires = 0;
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.AddHeader("Content-Length", contents.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.Write(contents);
    Response.End();
  }
  catch (Exception ex)
  {
    //your error handling here
  }
}

How to call this method? This is one of the ways:
FileInfo oTargetFile = new FileInfo(Server.MapPath("Errorlog.xml"));
if (oTargetFile.Exists)
{
  using (StreamReader oStreamReader = new StreamReader(Server.MapPath("Errorlog.xml")))
  {
    SaveAs(oStreamReader.ReadToEnd(), "Errorlog.xml");
  }
}
oTargetFile = null;

2009/04/07

Calling DOS command with parameters

I saw someone was asking about how to call DOS commands and how to pass the parameters. Here is the way to do it:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "ipconfig.exe";
p.StartInfo.Arguments = @"/all";
p.Start();
p.WaitForExit();
string strResult = p.StandardOutput.ReadToEnd();

PS: If your command doesn't work when you change the parameters, try to comment out the
p.WaitForExit();

Writing texts to a file.

Here are what I use to write texts to a file. First way:
using (StreamWriter oStreamWriter = new StreamWriter(outputFilename))
{
  oStreamWriter.WriteLine(YourTextHere);
  ......
}
Second way:
using (FileStream oFileStream = new FileStream("Errorlog.txt", FileMode.Append))
{
  using (TextWriter oTextWriter = new StreamWriter(oFileStream))
  {
    oTextWriter.WriteLine("DateTime: " + DateTime.Now.ToString());
    oTextWriter.WriteLine("Message: " + ex.Message);
    oTextWriter.WriteLine("Source: " + ex.Source);
  }
}
How to choose the correct FileMode? Take a look of this graph:
This graphic is scaned from the book C# 3.0 in a Nutshell, 3rd Edition. This is a very good C# book, and I will say "Go and grab one".