Retrieve data from a database

Nothing advanced here, I just wanted to store this code snippet somewhere for easy reuse…

SqlConnection conn = new SqlConnection(@"...");
SqlCommand cmd = new SqlCommand("select * from employee", conn);
cmd.CommandType = CommandType.Text;

using (conn)
{
	conn.Open();
	SqlDataReader reader = cmd.ExecuteReader();
	while (reader.Read())
	{
		...
	}
}

Start process and redirect output

Function GetProcessText(ByVal process As String, ByVal param As String, _
        ByVal workingDir As String) As String
    Dim p As System.Diagnostics.Process = New System.Diagnostics.Process

    ' this is the name of the process we want to execute 
    p.StartInfo.FileName = process
    If Not (workingDir = "") Then
        p.StartInfo.WorkingDirectory = workingDir
    End If
    p.StartInfo.Arguments = param

    ' need to set this to false to redirect output
    p.StartInfo.UseShellExecute = False
    p.StartInfo.RedirectStandardOutput = True

    ' start the process 
    p.Start()

    ' read all the output
    ' here we could just read line by line and display it
    ' in an output window 
    Dim output As String = p.StandardOutput.ReadToEnd
    ' wait for the process to terminate 
    p.WaitForExit()
    Return output
End Function

Code from http://www.developerfusion.co.uk/show/4662/.

Initializing the contents of a password textfield in ASP.NET 2.0

Question
How do I initialize the contents of a password textfield in ASP.NET 2.0?

Simple anwser
You can’t! This doesn’t work (apparently this is for security reasons, although the exact motivation escapes me):

txtPassword.Text = "this sucks";

Better answer
Create an event handler for the TextBox’s PreRender event:

protected void txtPassword_PreRender(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    txt.Attributes["value"] = txt.Text;
}

Voilá! Now you can assign to the Text property as in the first example.

(Credits for this tip to David Silverlight.)

Set credentials on a WebService connection

Assuming that si is a SoapHttpClientProtocol instance, this is how set the credentials:

si.Credentials = CredentialCache.DefaultCredentials;

(If the client is a web application then impersonation must be enabled.)

or

NetworkCredential myCred = 
    new NetworkCredential(username, password, domainName); 
CredentialCache myCache = new CredentialCache(); 
myCache.Add(new Uri(si.Url), "NTLM", myCred); 
si.Credentials = myCache; 
si.UnsafeAuthenticatedConnectionSharing = true;
si.ConnectionGroupName = username;

Server Error: Failed to access IIS metabase.

I have received this error several times when trying to run an ASP.NET 2.0 application on a fresh machine:

Server Error in '/Butler/EducationSI' Application.
--------------------------------------------------------------------

Failed to access IIS metabase.


Failed to access IIS metabase.jpg

The error normally goes away when reinstalling the .Net Framework 2.0 (it might be sufficient to repair the installation in “Add or Remove Programs” in the Control Panel).

Array-sorting using generics and anonymous methods

Alternative 1 (type safe sorting using generics):

private int ComparePass(Pass x, Pass y)
{
    if (x.Starttid < y.Starttid) return -1;
    if (x.Starttid > y.Starttid) return 1;
    return 0;
}
:
:
    Pass[] results = ...;
    Array.Sort<Pass>(results, ComparePass);
:

Alternative 2 (type safe sorting using generics and an anonymous method):

Pass[] results = ...;
Array.Sort<Pass>(results,
    delegate(Pass x, Pass y)
    {
        if (x.Starttid < y.Starttid) return -1;
        if (x.Starttid > y.Starttid) return 1;
        return 0;
    });

Alternative 3 (type safe sorting using generics and an anonymous method using a default comparer):

Pass[] results = ...;
Array.Sort<Pass>(results, 
    delegate(Pass x, Pass y)
    {
        return Comparer.Default.Compare(x.Starttid, y.Starttid);
    });

Draw icon with the alpha channel enabled

Here’s how to draw an icon in a control utilizing the icon’s built-in alpha channel.

private void cmdEmail_Paint(object sender, 
  System.Windows.Forms.PaintEventArgs e)
{
  System.Drawing.Icon icon;
  icon = new Icon(
    GetType().Module.Assembly.GetManifestResourceStream(
      "ActiveSolution.Lernia.SFI.WinClient.Images.mail.ico"),
    16, 16); 
  e.Graphics.DrawIcon(icon,0,0);
}

The name of the icon resource is easily found using ildasm. Double-click on the “M A N I F E S T” node and look for the icon in the window that opens.

SoapHeaders to Web Services in .Net

SoapHeaders can be used to send “extra” and optional parameters to web service methods and is a technique which can be extremely useful. See the following example:

Server-side (MyService.asmx):

public class MyService : System.Web.Services.WebService
{
   public class AddDateHeader : SoapHeader
   {
      public bool AddDate;
   }
   public AddDateHeader myheader;
   ...

   [WebMethod]
   [SoapHeader("myheader")]
   public string HelloWorld()
   {
      if (myheader != null && myheader.AddDate == true)
         return "Hello World " + DateTime.Now.ToString();
      else
         return "Hello World";
   }

Client-side:

localhost.MyService si = new localhost.MyService();
si.AddDateHeaderValue = new localhost.AddDateHeader();
si.AddDateHeaderValue.AddDate = true;
MessageBox.Show(si.HelloWorld());

Furthermore, these headers can be accessed in SoapExtension components. For example, there might be a SoapHeader that controls the transport of data.

Example:

Public Overrides Sub ProcessMessage(ByVal message As SoapMessage)
    Dim compress As Boolean = False
    Dim header As SoapHeader
    For Each header In message.Headers
        If header.GetType().Name = "Compress" Then
            compress = True
        End If
    Next
    ...

Sometimes it’s useful to have the header sent in both directions (both to and from the service). In this case, apply the attribute to the web method with the Direction attribute:

[SoapHeader("myheader", Direction = SoapHeaderDirection.InOut)]
public string HelloWorld()
{
    ...