Thursday, June 21, 2007

More Useful C# Code Snippets

Display Pop-Up Error Messages In An ASP.NET Application

I came across an issue in which someone needed to pop-up a Window to display an error message to users in their ASP.NET application. I did some research and discovered this very handy bit of code that will display a JavaScript Alert MessageBox that you can populate with the error message.

Below is an example I created that purposely causes a DivisonByZero Exception and displays this in a JavaScript Alert MessageBox.


int num1 = 10;
int num2 = 0;
int result;

try
{
result = n1 /n2;
}
catch (DivideByZeroException ex)
{
DisplayErrorMsg(ex);
}


private void DisplayErrorMsg(Exception ex)
{
RegisterStartupScript(Guid.NewGuid().ToString(),
string.Format("<script language='Javascript'>alert('{0}');</script>", ex.Message));
}

Populate The Display Text Of A CollapsiblePanel Control From A File

I had the need to populate the text to be displayed in an ASP.NET AJAX CollapsiblePanel Control via a text file as opposed to just embedding the text between a tag of my Content Panel. I had to display a large amount of text that displayed some Terms and Conditions and there was just to much to put between the tags. Besides it really would make the code ugly having all of that text embedded.

The solution I decided to go with was to create a Web User Control and fill the control with the text to be displayed. Then I went back to the page that I was going to display this text on and dropped the Custom Control inside of my CollapsiblePanel's ContentPanel. I then went into the HTML source of the page and surrounded the ContentPanel with a Div tag and sat the height, overflow, and background color.






<ajaxToolkit:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" runat="server"
TargetControlID="ContentPanel"
ExpandControlID="TitlePanel"
CollapseControlID="TitlePanel"
Collapsed="false"
TextLabelID="Label1"
ExpandedText="(Hide Details...)"
CollapsedText="(Show Details)"
ImageControlID="Image1"
CollapsedImage="images/expand.jpg"
ExpandedImage="images/collapse.jpg"
SuppressPostBack="true">
</ajaxToolkit:CollapsiblePanelExtender>


<asp:Panel ID="TitlePanel" runat="server" Height="30px" Width="545px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/expand.jpg"/>
Terms and Conditions
<asp:Label ID="Label1" runat="server" Text="Label">(Show Details ...)</asp:Label>
</asp:Panel>
<asp:Panel ID="ContentPanel" runat="server" Height="0px" Width="545px">                                
<div style="height:150px;overflow:scroll;background-color:ButtonFace;" >
<uc2:Terms ID="Terms1" runat="server" /></div>
</asp:Panel>

Friday, June 8, 2007

Useful C# Code Snippets

Mapping a month name to its chronological order value

The following C# code can be used to map a month name to its equivalent numeric chronological order value. You can use this code in a method and pass the month in as a string to convert for example "JUN" to 06. You can modify the array to map the full month name in place of it's three letter abbreviation.

public string MonthToNumberMapper(string month)
{
string Month = month.ToUpper();
string ConvertedMonth = null;
string[,] MonthsToConvert = new string[,]
{
{ "JAN", "01" }, { "FEB", "02" }, { "MAR", "03" }, { "APR", "04" },
{ "MAY", "05" }, { "JUN", "06" }, { "JUL", "07" }, { "AUG", "08" },
{ "SEP", "09" }, { "OCT", "10" }, { "NOV", "11" }, { "DEC", "12" }
};

// Determine the numeric month.
for (int i = 0; i < MonthsToConvert.Length / 2; i++)
{
if (Month == MonthsToConvert[i, 0])
{
ConvertedMonth = MonthsToConvert[i, 1];
break;
}
}

return ConvertedMonth;
}

Converting the text in a ComboBox Control to Uppercase
The following C# code can be placed in the TextChanged event handler of a ComboBox Control to change the case of the text entered to uppercase. This works for text entered into or selected within the ComboBox Control.

private void StateComboBox_TextChanged(object sender, EventArgs e)
{
String stateText = (string)StateComboBox.Text;
stateText = stateText.ToUpper();
StateComboBox.Text = stateText;
installStateComboBox.SelectionStart = installStateComboBox.Text.Length;
}

Saturday, June 2, 2007

Performing A Remote Registry Query To Display Installed Windows Updates

I received my first exposure to WMI(Windows Management Instrumentation) and accessing the Registry using C# when I worked on a personal project I came up with. I wanted to display the installed Windows Updates of Servers within a small network I created using VMware that consisted of a Domain Controller, a couple of additional Windows Servers, and a Windows XP Pro machine along with some additional information about the servers. I will show some sample code that demonstrates how to query a Remote Registry and retrieve a list of the installed updates in a Windows Application. NOTE: Your user account will need to be a member of the Domain Admins Group.

The first thing I did was to drop a ListView Control on an empty Windows form. I then configured a few properties such as setting the Form's size to a width of 450 and the ListView Control's Dock property to Fill. I added a few column headers to the ListView Control's Columns collection such as (Type, Description, Installed Date, and Installed By). Finally I set the ListView Control's View property to Details.

To query the registry remotely you will need to include a reference to the System.Management namespace and setup a couple of attributes to deal with Access Permissions to the registry as well as the Initial Hive location.

using System.Security.Permissions;

using System.Management;

using Microsoft.Win32;



[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, Read = @"HKEY_LocalMachine\SOFTWARE")]

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]

The SecurityAction.RequestMinimum requests a minimum group of permissions that is needed for the code to execute. Also the UnmanagedCode Parameter is set to true, because when working with the Registry you are dealing with Unmanaged code.

The ConnectionsOptions object contains the information needed to authenticate the user. Next a collection of WMI objects is returned after querying Win32_OperatingSystem from the Management classes.

string serverName = "192.168.239.128";



ConnectionOptions co = new ConnectionOptions();

co.Username = "username";

co.Password = "password";



ManagementScope ms = new ManagementScope("\\\\" + serverName + "\\root\\cimv2", co);

ObjectQuery objQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");

ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(ms, objQuery);

ManagementObjectCollection queryCollection = objSearcher.Get();

I perform a comparison on the OS Version number to display the proper registry information for a particular Windows OS. In this case it is for Windows 2000 and Windows 2003 Servers.

foreach (ManagementObject mo in queryCollection)

{

int ver = String.Compare(mo["Version"].ToString(), "5.2.3790");

if (ver == 0)

{

updateListView.Items.Clear();

RegistryKey win2003Key;

win2003Key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName).OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("Updates").OpenSubKey("Windows Server 2003").OpenSubKey("SP2");

foreach (string subKeyName in win2003Key.GetSubKeyNames())

{

using (RegistryKey tempKey = win2003Key.OpenSubKey(subKeyName))

{

foreach (string valueName in tempKey.GetValueNames())

{

if (String.Equals(valueName, "Description"))

{

ListViewItem value = new ListViewItem(tempKey.GetValue("Type").ToString());

value.SubItems.Add(tempKey.GetValue(valueName).ToString());

value.SubItems.Add(tempKey.GetValue("InstalledDate").ToString());

value.SubItems.Add(tempKey.GetValue("InstalledBy").ToString());

updateListView.Items.AddRange(new ListViewItem[] { value });

}

}

}

}

}

else if (ver < 0)

{

updateListView.Items.Clear();

RegistryKey win2000Key;

win2000Key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName).OpenSubKey("SOFTWARE").OpenSubKey("Microsoft").OpenSubKey("Updates").OpenSubKey("Windows 2000").OpenSubKey("SP5");

foreach (string subKeyName in win2000Key.GetSubKeyNames())

{

using (RegistryKey tempKey = win2000Key.OpenSubKey(subKeyName))

{

foreach (string valueName in tempKey.GetValueNames())

{

if (String.Equals(valueName, "Description"))

{

ListViewItem value = new ListViewItem(tempKey.GetValue("Type").ToString());

value.SubItems.Add(tempKey.GetValue(valueName).ToString());

value.SubItems.Add(tempKey.GetValue("InstalledDate").ToString());

value.SubItems.Add(tempKey.GetValue("InstalledBy").ToString());

updateListView.Items.AddRange(new ListViewItem[] { value });

}

}

}

}

}

}

I drill down through the registry and retrieve the values for the updates populating the ListView Control with the name of the update, when it was installed, and who installed it.

This example has been based on a simple virtual network configured with Active Directory. In an actual network environment a few changes would have to be made depending upon the level of security imposed as well as any group policies in place and possibly other factors.