﻿<?xml version="1.0" encoding="utf-8"?><rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><ttl>60</ttl><title>BLOG.CSHARPHELPER.COM</title><link>http://blog.csharphelper.com</link><lastBuildDate>Sat, 18 May 2013 09:56:28 GMT</lastBuildDate><pubDate>Sat, 18 May 2013 09:56:28 GMT</pubDate><language>en</language><copyright /><itunes:subtitle> </itunes:subtitle><itunes:author /><itunes:summary /><description /><itunes:owner><itunes:name /><itunes:email>RodStephens@vb-helper.com</itunes:email></itunes:owner><itunes:explicit>no</itunes:explicit><itunes:category text="Arts" /><item><title>How to send an SMS text message in C#</title><link>http://blog.csharphelper.com/2013/05/17/how-to-send-an-sms-text-message-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;img alt="" src="http://www.csharphelper.com/howto_send_sms.png" style="float: right; margin: 5px; border-width: 0px; border-style: solid;"&gt;
This example finishes the series showing how to make a C# program send an SMS (Short Message Service) message. You could use this technique to make a program monitor some sort of ongoing process and send you a message if there is a problem.
&lt;p&gt;&lt;/p&gt;
The example &lt;a href="http://blog.csharphelper.com/2013/05/15/how-to-extract-only-some-of-the-information-from-a-json-file-in-c.aspx"&gt;How to extract only some of the information from a JSON file in C#&lt;/a&gt; demonstrates how you can download a JSON file that contains information about SMS gateway email addresses and extract the carrier and email information. The example &lt;a href="http://blog.csharphelper.com/2013/05/16/how-to-send-an-email-message-in-c.aspx"&gt;How to send an email message in C#&lt;/a&gt; shows how to send an email.
&lt;p&gt;&lt;/p&gt;
This example combines the techniques demonstrated in those examples to send an SMS message.
&lt;p&gt;&lt;/p&gt;
When the program starts, it uses the techniques demonstrates by the &lt;a href="http://blog.csharphelper.com/2013/05/15/how-to-extract-only-some-of-the-information-from-a-json-file-in-c.aspx"&gt;first example&lt;/a&gt; to get the SMS carrier information.
&lt;p&gt;&lt;/p&gt;
The program executes the following code when you fill in the information and click Send.
&lt;p&gt;&lt;/p&gt;
&lt;br clear="right"&gt;

&lt;pre&gt;&lt;tt&gt;// Send the message.
private void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        string carrier_email = cboEmail.SelectedItem.ToString();
        string phone = txtPhone.Text.Trim().Replace("-", "");
        phone = phone.Replace("(", "").Replace(")", "").Replace("+", "");
        string to_email = phone + "@" + carrier_email;

        SendEmail(txtToName.Text, to_email,
            txtFromName.Text, txtFromEmail.Text,
            txtHost.Text, int.Parse(txtPort.Text),
            chkEnableSSL.Checked, txtPassword.Text,
            txtSubject.Text, txtBody.Text);

        MessageBox.Show("Message sent");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The program first gets the SMS carrier's email address from the cboEmail ComboBox. The email address the program uses must not contain any characters other than digits so the code trims the address to remove spaces. It also removes the -, (, ), and + characters.
&lt;p&gt;&lt;/p&gt;
Next the code appends the @ symbol and the carrier's SMS gateway email address. The result should look something like this:
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;    2345678901@sms.airfiremobile.com&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The program finishes by calling the SendEmail method described in &lt;a href="http://blog.csharphelper.com/2013/05/16/how-to-send-an-email-message-in-c.aspx"&gt;the second post mentioned above&lt;/a&gt; to send the message to this email address.
&lt;p&gt;&lt;/p&gt;
That's all there is to it! The tools you need to download the JSON carrier data, parse the data, and send the email message are somewhat involved. Once you've built those tools, however, sending the SMS message is comparatively easy.
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Download Example" hspace="10" href="http://www.csharphelper.com/examples/howto_send_sms.zip"&gt;&lt;img alt="" src="http://www.csharphelper.com/Download.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>system</category><category>miscellany</category><comments>http://blog.csharphelper.com/2013/05/17/how-to-send-an-sms-text-message-in-c.aspx#Comments</comments><guid isPermaLink="false">2aa0dc82-1153-4467-b2f2-5f875e4fa2f6</guid><pubDate>Fri, 17 May 2013 14:30:00 GMT</pubDate></item><item><title>How to send an email message in C#</title><link>http://blog.csharphelper.com/2013/05/16/how-to-send-an-email-message-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_send_email.png" align="right" border="0" hspace="5" vspace="5"&gt;

The next tool you need to make a program send an SMS message is a method for sending an email. In recent years this has become harder because there are few email providers willing to let you send anonymous emails. Now to send an email, you need to create a NetworkCredential object that specifies your email server, user name, and password.
&lt;p&gt;&lt;/p&gt;
This example uses the following SendEmail method to send an email.
&lt;p&gt;&lt;/p&gt;
&lt;br clear="right"&gt;

&lt;pre&gt;&lt;tt&gt;using System.Net;
using System.Net.Mail;

// Send an email message.
private void SendEmail(string to_name, string to_email,
    string from_name, string from_email,
    string host, int port, bool enable_ssl, string password,
    string subject, string body)
{
    // Make the mail message.
    MailAddress from_address = new MailAddress(from_email, from_name);
    MailAddress to_address = new MailAddress(to_email, to_name);
    MailMessage message = new MailMessage(from_address, to_address);
    message.Subject = subject;
    message.Body = body;

    // Get the SMTP client.
    SmtpClient client = new SmtpClient()
    {
        Host = host,
        Port = port,
        EnableSsl = enable_ssl,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(from_address.Address, password),
    };

    // Send the message.
    client.Send(message);
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The method creates MailAddress objects to represent the From and To email addresses. You can use strings for these when you make the MailMessage but then you can't associate a human-friendly name (like "Rod Stephens") with the email addresses.
&lt;p&gt;&lt;/p&gt;
Next the program creates a MailMessage, passing its constructor the From and To addresses. The code then sets the MailMessage's Subject and Body fields.
&lt;p&gt;&lt;/p&gt;
The method then creates an SmtpClient object. It sets the client's host and port so it knows where to send the email. The method sets the EnableSsl property according to the value it was passed as a parameter. If your email server uses SSL (Secure Sockets Layer--Gmail uses this), check the box on the form so this is set to true.
&lt;p&gt;&lt;/p&gt;
The code also sets UseDefaultCredentials to false and sets the client's Credentials property to a new NetworkCredential object containing your email user name and password.
&lt;p&gt;&lt;/p&gt;
Finally the method calls the SmtpClient's Send method to send the email.
&lt;p&gt;&lt;/p&gt;
The System.Net.Mail.MailMessage class supports some other features that you might want to use. For example, it has CC and Bcc properties that let you send courtesy copies and blind courtesy copies. The version shown here is good enough for the next post, which sends an SMS message.
&lt;p&gt;&lt;/p&gt;
The following code shows how the program calls the SendEmail method.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Send the message.
private void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        SendEmail(txtToName.Text, txtToEmail.Text,
            txtFromName.Text, txtFromEmail.Text,
            txtHost.Text, int.Parse(txtPort.Text),
            chkEnableSSL.Checked, txtPassword.Text,
            txtSubject.Text, txtBody.Text);
        MessageBox.Show("Message sent");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This code simply calls SendEmail passing it the values you entered on the form.
&lt;p&gt;&lt;/p&gt;
Note that the form's initial values for host and port (smtp.gmail.com and 587) work for Gmail. If you want to use some other email host, you'll need to change those values.
&lt;p&gt;&lt;/p&gt;
The next post will bring together the results of this post and the previous JSON posts to send an SMS message.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_send_email.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>system</category><category>miscellany</category><comments>http://blog.csharphelper.com/2013/05/16/how-to-send-an-email-message-in-c.aspx#Comments</comments><guid isPermaLink="false">079d21d3-e0ca-4b04-b9bf-24f3675ecb6b</guid><pubDate>Thu, 16 May 2013 17:18:54 GMT</pubDate></item><item><title>How to extract only some of the information from a JSON file in C#</title><link>http://blog.csharphelper.com/2013/05/15/how-to-extract-only-some-of-the-information-from-a-json-file-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_parse_unknown_json.png" align="right" border="0" hspace="5" vspace="5"&gt;

Recall from my post &lt;a href="http://blog.csharphelper.com/2013/05/11/anatomy-of-an-example.aspx"&gt;Anatomy of an example&lt;/a&gt; that my original goal with this series of articles was to write a program to send an SMS message. To do that, I want to download a file listing SMS gateway email addresses. The example &lt;a href="http://blog.csharphelper.com/2013/05/13/download-and-display-a-text-file-whenever-a-program-starts-in-c.aspx"&gt;Download and display a text file whenever a program starts in C#&lt;/a&gt; shows how to download the file.
&lt;p&gt;&lt;/p&gt;
That file is a JSON format file. The example &lt;a href="http://blog.csharphelper.com/2013/05/14/use-json-to-serialize-and-deserialize-objects-in-c.aspx"&gt;Use JSON to serialize and deserialize objects in C#&lt;/a&gt; shows how to use JSON to serialize and deserialize objects. You could use that technique to deserialize the SMS gateway file. You would define an object that represents the kinds of data contained in the SMS gateway file and then simply deserialize the file.
&lt;p&gt;&lt;/p&gt;
After staring for quite a while at the file, I decided that this would be fairly hard. It's a big file with a complex structure and it contains lots of information that I don't really need, so I decided on a different approach. (One that also makes a good blog post.)
&lt;p&gt;&lt;/p&gt;
Instead of trying to understand the structure of the entire JSON file, this example reads it without really knowing what it represents and then sifts through it to find the data it needs.
&lt;p&gt;&lt;/p&gt;
The following text shows the structure of the JSON file (with LOTS of data omitted).
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;{
        "info" : "JSON array ...",
        "license" : "MIT or LGPL...",
        "lastupdated" : "2012-07-01",
        "countries" : {
                "us" : "United States",
                "ca" : "Canada",
                "ar" : "Argentina",
                "aw" : "Aruba",
            ...
        },
        "sms_carriers" : {
                "us" : {
                        "airfire_mobile" : ["Airfire Mobile",
                            "{number}@sms.airfiremobile.com"],
                        "alltel" : ["Alltel", "{number}@message.alltel.com"],
                        ...
                        "at_and_t_mobility" : ["AT&amp;amp;T Mobility (Cingular)",
                            "{number}@txt.att.net",
                            "{number}@cingularme.com",
                            "{number}@mobile.mycingular.com"],
                        ...
                },
                "ca" : {
                        "aliant" : ["Aliant", "{number}@chat.wirefree.ca"],
                        ...
                },
            ...
        },
        "mms_carriers" : {
                "us" : {
                        "alltel" : ["Alltel", "{number}@mms.alltel.com"],
                        ...
                },
                ...
        }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
Notice that the us/at_and_t_mobility carrier supports three email addresses. Normally you can use the first one if a carrier has more than one email address, but the program displays them all in case you know which one you want to use.
&lt;p&gt;&lt;/p&gt;
The following code shows the two classes that the program uses to store the information it gets from the file.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;public class CarrierInfo
{
    public string CarrierAbbreviation, CarrierName;
    public List&amp;lt;string&amp;gt; Emails = new List&amp;lt;string&amp;gt;();

    public override string ToString()
    {
        return CarrierName;
    }
}

public class CountryInfo
{
    public string CountryAbbreviation, CountryName;
    public List&amp;lt;CarrierInfo&amp;gt; Carriers = new List&amp;lt;CarrierInfo&amp;gt;();

    public override string ToString()
    {
        return CountryName;
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The CarrierInfo class stores a cell phone carrier's abbreviation and name, and a list of supported SMS gateway email addresses.
&lt;p&gt;&lt;/p&gt;
The CountryInfo class stores a country's abbreviation and name, and a list of carriers that are available in that country.
&lt;p&gt;&lt;/p&gt;
The code that reads the data is fairly long but not super complicated. Basically it loads the data into a dictionary where the keys are strings and the values are objects. Many of the values are also dictionaries with a similar structure.
&lt;p&gt;&lt;/p&gt;
For example, the file's top-level data is stored in a dictionary with keys info, license, lastupdated, countries, sms_carriers, and mms_carriers. The sms_carriers entry is a dictionary with keys us, ca, and other country abbreviations. Each of the entries in the sms_carriers dictionary is another dictionary with keys that are carrier abbreviations and with values that are arrays holding a carrier's name and email addresses.
&lt;p&gt;&lt;/p&gt;
The following code shows how the program reads the data.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Add a reference to System.Web.Extensions.dll.
using System.Web.Script.Serialization;

using System.IO;
using System.Net;
...
private void Form1_Load(object sender, EventArgs e)
{
    // Get the data file.
    const string url = "https://raw.github.com/cubiclesoft/" +
        "email_sms_mms_gateways/master/sms_mms_gateways.txt";
    string serialization = GetTextFile(url);

    // Add a reference to System.Web.Extensions.dll.
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Dictionary&amp;lt;string, object&amp;gt; dict =
        (Dictionary&amp;lt;string, object&amp;gt;)serializer.DeserializeObject(serialization);

    // Get the countries.
    Dictionary&amp;lt;string, CountryInfo&amp;gt; country_infos =
        new Dictionary&amp;lt;string, CountryInfo&amp;gt;();
    Dictionary&amp;lt;string, object&amp;gt; countries =
        (Dictionary&amp;lt;string, object&amp;gt;)dict["countries"];
    foreach (KeyValuePair&amp;lt;string, object&amp;gt; pair in countries)
    {
        CountryInfo country_info = new CountryInfo()
            { CountryAbbreviation = pair.Key, CountryName = (string)pair.Value };
        country_infos.Add(country_info.CountryAbbreviation, country_info);
    }

    // Get the SMS carriers.
    Dictionary&amp;lt;string, object&amp;gt; sms_carriers =
        (Dictionary&amp;lt;string, object&amp;gt;)dict["sms_carriers"];
    foreach (KeyValuePair&amp;lt;string, object&amp;gt; pair in sms_carriers)
    {
        // Get the corresponding CountryInfo.
        CountryInfo country_info = country_infos[pair.Key];

        // Get the country's carriers.
        Dictionary&amp;lt;string, object&amp;gt; carriers =
            (Dictionary&amp;lt;string, object&amp;gt;)pair.Value;
        foreach (KeyValuePair&amp;lt;string, object&amp;gt; carrier_pair in carriers)
        {
            // Create a CarrierInfo for this carrier.
            CarrierInfo carrier_info = new CarrierInfo()
                { CarrierAbbreviation = carrier_pair.Key };
            country_info.Carriers.Add(carrier_info);
            object[] carrier_values = (object[])carrier_pair.Value;
            carrier_info.CarrierName = (string)carrier_values[0];
            for (int email_index = 1; email_index &amp;lt;
                carrier_values.Length; email_index++)
            {
                string email = (string)carrier_values[email_index];
                carrier_info.Emails.Add(email.Replace("{number}", ""));
            }
        }
    }

    // Display the countries.
    cboCountry.Items.Clear();
    foreach (CountryInfo country in country_infos.Values)
    {
        cboCountry.Items.Add(country);
    }

    // Make an initial selection.
    cboCountry.SelectedIndex = 0;
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The program defines the URL where it will get the file. It then uses the GetTextFile method described in &lt;a href="http://blog.csharphelper.com/2013/05/13/download-and-display-a-text-file-whenever-a-program-starts-in-c.aspx"&gt;Download and display a text file whenever a program starts in C#&lt;/a&gt; to get the file.
&lt;p&gt;&lt;/p&gt;
Next the code creates a JavaScriptSerializer. Unlike the serializers described in the previous example that serializes and deserializes objects, this serializer doesn't know what kind of object it is deserializing.
&lt;p&gt;&lt;/p&gt;
The program call's the serializer's DeserializeObject method. That method returns a Dictionary that contains strings associated with objects. The objects hold various kinds of data depending on what's in the JSON file.
&lt;p&gt;&lt;/p&gt;
This example gets the "countries" entry from the dictionary. This entry is another dictionary that contains the abbreviations and names of countries used by the JSON file.
&lt;p&gt;&lt;/p&gt;
The program loops through the country dictionary's key/value pairs. For each country pair, the program stores the country's abbreviation and name in a CountryInfo object. It stores the new CountryInfo object in a dictionary named country_infos using the country's abbreviation as the key.
&lt;p&gt;&lt;/p&gt;
Next the program returns to the dictionary that represents the JSON file's highest level of data and gets the sms_carriers entry in that dictionary. This entry is another dictionary that holds information about the carriers that are represented in the file.
&lt;p&gt;&lt;/p&gt;
The program loops over the carrier information. Because the carriers are grouped by country, the keys in the key/value pairs are country abbreviations. The program uses those to look up the corresponding CountryInfo object in the country_infos dictionary.
&lt;p&gt;&lt;/p&gt;
Next the program uses the value part of the carrier's key/value pair to get the information about the carrier. It creates a CarrierInfo object and adds it to the appropriate CountryInfo object's Carriers list. Finally the code adds the email addresses for the carrier to the CarrierInfo object's Emails list.
&lt;p&gt;&lt;/p&gt;
The method then displays the names of the countries it loaded in the cboCountry ComboBox. It finishes by selecting the first country in the ComboBox so the program always has country selected.
&lt;p&gt;&lt;/p&gt;
The program's remaining code updates its ComboBox's when the user makes a selection. When the user selects a country, the carriers ComboBox displays a list of the carriers available in that country. When the user selects a carrier, the email addresses ComboBox displays a list of email addresses provided by that carrier.
&lt;p&gt;&lt;/p&gt;
The following code shows how the program responds when the user picks a country.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Display the selected country's carriers.
private void cboCountry_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cboCountry.SelectedIndex &amp;lt; 0)
    {
        cboCarrier.SelectedIndex = -1;
    }
    else
    {
        // Get the selected CountryInfo object.
        CountryInfo country = cboCountry.SelectedItem as CountryInfo;
        Console.WriteLine("Country: " + country.CountryAbbreviation +
            ": " + country.CountryName);

        // Display the CountryCarrier's carriers.
        cboCarrier.DataSource = country.Carriers;
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
If the user has selected a country, the program converts the selected country into its corresponding CountryInfo object. It then sets the cboCarrier ComboBox's DataSource property to the country's Carriers property. That property is a list of CarrierInfo objects so the ComboBox displays them.
&lt;p&gt;&lt;/p&gt;
When the user picks a carrier from the carriers ComboBox, the following code executes.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Display the selected carrier's emails addresses.
private void cboCarrier_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cboCarrier.SelectedIndex &amp;lt; 0)
    {
        cboEmail.SelectedIndex = -1;
    }
    else
    {
        // Get the selected CarrierInfo object.
        CarrierInfo carrier = cboCarrier.SelectedItem as CarrierInfo;
        Console.WriteLine("Carrier: " + carrier.CarrierName);

        // Display the Carrier's email addresses.
        cboEmail.DataSource = carrier.Emails;
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This code converts the selected carrier into its CarrierInfo object. It then sets the email address ComboBox's DataSource property to the CarrierInfo object's Emails property so it displays the list of available email addresses.
&lt;p&gt;&lt;/p&gt;
The program doesn't do anything when the user selects an email address.
&lt;p&gt;&lt;/p&gt;
At this point, you can download the SMS gateway file and get the information you need out of it to find an SMS gateway email address. The next step is to send email to that address. The next two posts explain how to do that.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_parse_unknown_json.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>serialization</category><category>algorithms</category><comments>http://blog.csharphelper.com/2013/05/15/how-to-extract-only-some-of-the-information-from-a-json-file-in-c.aspx#Comments</comments><guid isPermaLink="false">2e75bd99-3856-4b4a-b86f-3b4419785278</guid><pubDate>Wed, 15 May 2013 21:49:29 GMT</pubDate></item><item><title>Use JSON to serialize and deserialize objects in C#</title><link>http://blog.csharphelper.com/2013/05/14/use-json-to-serialize-and-deserialize-objects-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;img alt="" src="http://www.csharphelper.com/howto_use_json.png" style="float: right; margin: 5px; border-width: 0px; border-style: solid;"&gt;
JSON (JavaScript Object Notation) is a standard for textual storage and interchange of information, much as XML is. Before you roll your eyes and ask if we really need another language to do what XML does, consider how verbose XML is. Even relatively simple object hierarchies can take up a considerable amount of space when represented by XML. JSON is a more compact format that stores the same kinds of information in less space.
&lt;p&gt;&lt;/p&gt;
When XML first came out, I thought to myself, "This is a really verbose language. It could be so much more concise. I guess people are willing to spend the extra space to get a more readable format. And after all, storage space is cheaper and network speed is faster than ever before." If you remember having similar thoughts, *now* you can roll your eyes.
&lt;p&gt;&lt;/p&gt;
JSON's basic data types are:
&lt;p&gt;&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Number
    &lt;/li&gt;
    &lt;li&gt;String
    &lt;/li&gt;
    &lt;li&gt;Boolean
    &lt;/li&gt;
    &lt;li&gt;Array (sequence of values separated by commas and enclosed in brackets [ ])
    &lt;/li&gt;
    &lt;li&gt;Object (a collection of key:value pairs with pairs separated by commas and the whole collection surrounded by braces { })
    &lt;/li&gt;
    &lt;li&gt;null
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
For example, the following text shows a JSON representation of a Customer object.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;{
  "City":"Bugsville",
  "EmailAddresses":
  [
    "somewhere@someplace.com",
    "nowhere@noplace.com",
    "root@everywhere.org"
  ],
  "Name":"Rod Stephens",
  "Orders":
  [
    {"Description":"Pencils, dozen","Price":1.13,"Quantity":10},
    {"Description":"Notepad","Price":0.99,"Quantity":3},
    {"Description":"Cookies","Price":3.75,"Quantity":1}
  ],
  "PhoneNumbers":
  [
    {"Key":"Home","Value":"111-222-3333"},
    {"Key":"Cell","Value":"222-333-4444"},
    {"Key":"Work","Value":"333-444-5555"}
  ],
  "State":"CA",
  "Street":"1337 Leet St",
  "Zip":"98765"
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
Some of the fields such as City, Name, and State are simple string values. The EmailAddresses value is an array of strings.
&lt;p&gt;&lt;/p&gt;
The Orders value is an array of Order objects, each of which has a Description, Price, and Quantity. (Really this should be a collection of Order objects, each of which has a collection of OrderItem objects that have Description, Price, and Quantity properties, but the structure shown here is complicated enough already.)
&lt;p&gt;&lt;/p&gt;
The PhoneNumbers value is a dictionary where the keys are phone number types (Home, Cell, Work) and the values are the phone number strings.
&lt;p&gt;&lt;/p&gt;
This example builds a Customer object. It then serializes it into a JSON format and then deserializes it to re-create the original object.
&lt;p&gt;&lt;/p&gt;
The following code shows the Order class.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Add a reference to System.Runtime.Serialization.
using System.Runtime.Serialization;

namespace howto_use_json
{
    [Serializable]
    public class Order
    {
        [DataMember]
        public string Description;

        [DataMember]
        public int Quantity;

        [DataMember]
        public decimal Price;

        // Return a textual representation of the order.
        public override string ToString()
        {
            decimal total = Quantity * Price;
            return Description + ": " +
                Quantity.ToString() + " @ " +
                Price.ToString("C") + " = " +
                total.ToString("C");
        }
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
To allow the program to serialize Order objects, the class must be marked with the Serializable attribute. That attributes is defined in the System.Runtime.Serialization namespace so the code includes a using statement to make using that namespace easier. To use the namespace, you also need to add a reference to System.Runtime.Serialization at design time.
&lt;p&gt;&lt;/p&gt;
The fields within the class are marked with the DataMember attribute so the serializer knows to serialize them.
&lt;p&gt;&lt;/p&gt;
The last part of the class is a ToString method that simply returns a textual representation of the object's values.
&lt;p&gt;&lt;/p&gt;
The following code shows the Customer class.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Add a reference to System.Runtime.Serialization.
using System.Runtime.Serialization;

// Add a reference to System.ServiceModel.Web.
using System.Runtime.Serialization.Json;

using System.IO;

namespace howto_use_json
{
    [Serializable]
    public class Customer
    {
        [DataMember]
        public string Name = "";

        [DataMember]
        public string Street = "";

        [DataMember]
        public string City = "";

        [DataMember]
        public string State = "";

        [DataMember]
        public string Zip = "";

        [DataMember]
        public Dictionary&amp;lt;string, string&amp;gt; PhoneNumbers = new Dictionary&amp;lt;string, string&amp;gt;();

        [DataMember]
        public List&amp;lt;string&amp;gt; EmailAddresses = new List&amp;lt;string&amp;gt;();

        [DataMember]
        public Order[] Orders = null;

        ... (Other code shown later) ...
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This class starts much as the Order class does. It also uses the System.Runtime.Serialization namespace so it includes the corresponding using statement.
&lt;p&gt;&lt;/p&gt;
The class also uses the System.Runtime.Serialization.Json namespace (which requires you to add a reference to System.ServiceModel.Web) and the System.IO namespaces so it also includes using statements for them.
&lt;p&gt;&lt;/p&gt;
The class's definition starts by defining some simple properties such as Name, Street, and City.
&lt;p&gt;&lt;/p&gt;
The class defines the PhoneNumbers member as a Dictionary&amp;lt;string, string&amp;gt;. It defines the EmailAddresses member as List&amp;lt;string&amp;gt;. The serializer automatically converts these into the appropriate JSON types.
&lt;p&gt;&lt;/p&gt;
To make serializing and deserializing objects easier, the class includes the methods ToJson and FromJson. The ToJson method shown in the following code returns a JSON representation of an object.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Return the JSON serialization of the object.
public string ToJson()
{
    // Make a stream to serialize into.
    using (MemoryStream stream = new System.IO.MemoryStream())
    {
        // Serialize into the stream.
        DataContractJsonSerializer serializer
            = new DataContractJsonSerializer(typeof(Customer));
        serializer.WriteObject(stream, this);
        stream.Flush();

        // Get the result as text.
        stream.Seek(0, SeekOrigin.Begin);
        using (StreamReader reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This method creates a MemoryStream in which to write. It then creates a DataContractJsonSerializer object to serialize the Customer object. It calls the serializer's WriteObject method to write the current Customer object into the stream and flushes the stream.
&lt;p&gt;&lt;/p&gt;
Next the code rewinds the stream to the beginning, creates an associated StreamReader, and uses the reader's ReadToEnd method to get the serialization out of the stream and return it. (This seems needlessly awkward to me. If you find a simpler method, &lt;a href="mailto:RodStephens@CSharpHelper.com"&gt;email me&lt;/a&gt;.
&lt;p&gt;&lt;/p&gt;
The static FromJson method shown in the following code takes a JSON serialization of a Customer object, uses it to re-create the object, and returns the new object.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Create a new Customer from a JSON serialization.
public static Customer FromJson(string json)
{
    // Make a stream to read from.
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(json);
    writer.Flush();
    stream.Position = 0;

    // Deserialize from the stream.
    DataContractJsonSerializer serializer
        = new DataContractJsonSerializer(typeof(Customer));
    Customer cust = (Customer)serializer.ReadObject(stream);

    // Return the result.
    return cust;
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This method creates a MemoryStream and an associated StreamWriter. It uses the writer to write the JSON serialization into the stream. It then flushes the writer and rewinds the stream.
&lt;p&gt;&lt;/p&gt;
Next the code creates a DataContractJsonSerializer object to deserialize the Customer object. It calls the serializer's ReadObject to read the object's serialization from the stream, casts the result into a Customer object, and returns the object.
&lt;p&gt;&lt;/p&gt;
The ToString method shown in the following code is the last piece of the Customer class. It simply returns a textual representation of the Customer object.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Return a newline separated text representation.
public override string ToString()
{
    // Display the basic information.
    string result = "Customer" + Environment.NewLine;
    result += "    " + Name + Environment.NewLine;
    result += "    " + Street + Environment.NewLine;
    result += "    " + City + " " + State + " " + Zip + Environment.NewLine;

    // Display phone numbers.
    result += "    Phone Numbers:" + Environment.NewLine;
    foreach (KeyValuePair&lt;string,&gt; pair in PhoneNumbers)
    {
        result += "        " + pair.Key + ": " + pair.Value + Environment.NewLine;
    }

    // Display email addresses.
    result += "    Email Addresses:" + Environment.NewLine;
    foreach (string address in EmailAddresses)
    {
        result += "        " + address + Environment.NewLine;
    }

    // Display orders.
    result += "    Orders:" + Environment.NewLine;
    foreach (Order order in Orders)
    {
        result += "        " + order.ToString() + Environment.NewLine;
    }

    return result;
}&lt;/string,&gt;&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The ToString method is a bit long but reasonably straightforward.
&lt;p&gt;&lt;/p&gt;
The following shows how the main program demonstrates JSON serialization by serializing and deserializing a Customer object.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;private void Form1_Load(object sender, EventArgs e)
{
    // Make an object to serialize.
    Customer cust = new Customer()
    {
        Name = "Rod Stephens",
        Street = "1337 Leet St",
        City = "Bugsville",
        State = "CA",
        Zip = "98765",
        PhoneNumbers = new Dictionary&lt;string,&gt;()
        {
            {"Home", "111-222-3333"},
            {"Cell", "222-333-4444"},
            {"Work", "333-444-5555"},
        },
        EmailAddresses = new List&lt;string&gt;()
        {
            "somewhere@someplace.com",
            "nowhere@noplace.com",
            "root@everywhere.org",
        },
    };
    cust.Orders = new Order[3];
    cust.Orders[0] = new Order()
    {
        Description = "Pencils, dozen",
        Quantity = 10,
        Price = 1.13m
    };
    cust.Orders[1] = new Order()
    {
        Description = "Notepad",
        Quantity = 3,
        Price = 0.99m
    };
    cust.Orders[2] = new Order()
    {
        Description = "Cookies",
        Quantity = 1,
        Price = 3.75m
    };

    // Display the serialization.
    string serialization = cust.ToJson();
    txtJson.Text = serialization;
    txtJson.Select(0, 0);

    // Deserialize.
    Customer new_cust = Customer.FromJson(serialization);
    txtProperties.Text = new_cust.ToString();
    txtProperties.Select(0, 0);
}&lt;/string&gt;&lt;/string,&gt;&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The form's Load event handler starts by initializing a Customer object complete with phone numbers, email addresses, and Order objects.
&lt;p&gt;&lt;/p&gt;
Next the code calls the Customer object's ToJson method to get its serialization and display it in the txtJson TextBox. (Notice that the JSON serialization in the picture doesn't include nice line breaks and formatting to align the data nicely. It sacrifices that to save space.)
&lt;p&gt;&lt;/p&gt;
The code then calls the Customer class's FromJson method to deserialize the serialization and create a new Customer object. It finishes by using the new object's ToString method to show its properties in the txtProperties TextBox.
&lt;p&gt;&lt;/p&gt;
This example may seem complicated but it's actually not too bad. It's a bit longer than it might otherwise be because the Customer and Order classes include several useful data types such as a list, dictionary, and array of objects. The actual JSON code in the ToJson and FromJson methods is somewhat confusing but it's fairly short. Those methods also make using JSON to serialize and deserialize objects easy in practice.
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Download Example" hspace="10" href="http://www.csharphelper.com/examples/howto_use_json.zip"&gt;&lt;img alt="" src="http://www.csharphelper.com/Download.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>serialization</category><category>algorithms</category><comments>http://blog.csharphelper.com/2013/05/14/use-json-to-serialize-and-deserialize-objects-in-c.aspx#Comments</comments><guid isPermaLink="false">b816f0f6-0b0e-49ba-9615-9602ce488818</guid><pubDate>Tue, 14 May 2013 22:19:57 GMT</pubDate></item><item><title>Download and display a text file whenever a program starts in C#</title><link>http://blog.csharphelper.com/2013/05/13/download-and-display-a-text-file-whenever-a-program-starts-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;img alt="" style="float: right; margin: 5px; border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/howto_download_text_file.png"&gt;
When this example program starts, it downloads a file from the internet and displays it. You could do something similar to display a message of the day or announcements for your program.
&lt;p&gt;&lt;/p&gt;
The program uses the following Load event handler to start the process.
&lt;p&gt;&lt;/p&gt;
&lt;br clear="right"&gt;
&lt;pre&gt;&lt;tt&gt;// Download and display the text file.
private void Form1_Load(object sender, EventArgs e)
{
    const string url = "https://raw.github.com/cubiclesoft/email_sms_mms_gateways/master/sms_mms_gateways.txt";
    txtFile.Text = GetTextFile(url);
    txtFile.Select(0, 0);
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The code defines the URL of the file to download. It then calls the GetTextFile method described next to download the file and displays the result in the txtFile TextBox.
&lt;p&gt;&lt;/p&gt;
The following code shows the GetTextFile method.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;using System.IO;
using System.Net;
...
// Get the text file at a given URL.
private string GetTextFile(string url)
{
    try
    {
        url = url.Trim();
        if (!url.ToLower().StartsWith("http")) url = "http://" + url;
        WebClient web_client = new WebClient();
        MemoryStream image_stream = new MemoryStream(web_client.DownloadData(url));
        StreamReader reader = new StreamReader(image_stream);
        string result = reader.ReadToEnd();
        reader.Close();
        return result;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error downloading file " +
            url + '\n' + ex.Message,
            "Download Error",
            MessageBoxButtons.OK,
            MessageBoxIcon.Error);
    }
    return "";
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The code first uses the string class's Trim method to remove leading and trailing whitespace from the URL (just in case). Then if the URL doesn't begin with "http," the code adds "http://" to the beginning of the URL. (The code only checks for "http" so it can also handle "https" as in the URL used by this example.)
&lt;p&gt;&lt;/p&gt;
Next the code creates a WebClient object. It uses the client's DownloadData method to get the file. DownloadData returns an array of bytes so the program creates a memory stream associated with the array and then makes a StreamReader to read the memory stream. The code calls the reader's ReadToEnd method and closes the reader. Finally it returns the string read by the StreamReader.
&lt;p&gt;&lt;/p&gt;
There are several ways this method could fail (file doesn't exist, improper permissions, not connected to the network, network failure, and so on) so the code does all its work within a try-catch block.
&lt;p&gt;&lt;/p&gt;
With a it more work, you can download other files such as pictures or RTF format files to display more than just text. If you really want a fancy announcement page downloaded from the internet, you might be better off placing a WebBrowser control on the form and making it navigate to a web page.
&lt;p&gt;&lt;/p&gt;
If you examine the file that this example downloads, you'll see that it contains JSON-formatted data listing SMS gateway email addresses. My next blog post provides a brief introduction to JSON. The post after that explains how to read the data in the text file that this example downloads and displays.
&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_download_text_file.zip" hspace="10" alt="Download Example"&gt;&lt;img alt="" style="border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/Download.png"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img alt="" style="border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/Twitter.png"&gt;&lt;/a&gt;</description><category>internet</category><category>web</category><category>files</category><comments>http://blog.csharphelper.com/2013/05/13/download-and-display-a-text-file-whenever-a-program-starts-in-c.aspx#Comments</comments><guid isPermaLink="false">8664bba4-e9f5-497c-8a44-229e04b05013</guid><pubDate>Mon, 13 May 2013 22:26:12 GMT</pubDate></item><item><title>Anatomy of an example</title><link>http://blog.csharphelper.com/2013/05/11/anatomy-of-an-example.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;Sometimes someone asks me a question that leads to an interesting example that I post here. Usually I have to think of something interesting myself. Occasionally that leads to a new idea, which leads to a new idea, and so on.
&lt;p&gt;&lt;/p&gt;
This time I thought I would write an example that sends a SMS (Short Message Service) text message. I knew that you could do that by sending an email to the appropriate address. That lead to two threads of research: sending an email (which is a bit of a hassle) and finding the format of the necessary email address.
&lt;p&gt;&lt;/p&gt;
The email address depends on the intended recipient's phone number and carrier so I went online to try to find a list of the carriers' SMS gateway email addresses. Wikipedia has a  decent list but it's in the form of a table that would require a lot of manual retyping to use. Eventually I found a much better list at &lt;a href="https://github.com/cubiclesoft/email_sms_mms_gateways"&gt;https://github.com/cubiclesoft/email_sms_mms_gateways&lt;/a&gt;.
&lt;p&gt;&lt;/p&gt;
That gateway list is updated reasonably frequently (as I write this, the last update was 25 days ago) so that lead to a new topic: how to download a file whenever a program starts so it can use the latest version of the file.
&lt;p&gt;&lt;/p&gt;
The gateway file is also stored in JSON (JavaScript object notation) format so that lead to the final topic for this example: JSON. Or actually the final two topics. JSON is a data storage format with a purpose similar to that of XML (eXtensible Markup Language). One of the easier ways to use either XML or JSON is to serialize and deserialize objects. So that's the first topic: how to use JSON to serialize and deserialize objects.
&lt;p&gt;&lt;/p&gt;
Unfortunately the SMS gateway file contains a fairly long and complicated pile of data and the file's web site doesn't provide a definition for a class into which a program could deserialize the data. That leads to the final (really) topic in the series: how to read JSON data when you don't really understand or care about all of the data.
&lt;p&gt;&lt;/p&gt;
So from this one idea, to send an SMS message, came the following topics:
&lt;p&gt;&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/13/download-and-display-a-text-file-whenever-a-program-starts-in-c.aspx"&gt;Download and display a text file whenever a program starts in C#&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/14/use-json-to-serialize-and-deserialize-objects-in-c.aspx"&gt;Use JSON to serialize and deserialize objects in C#&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/15/how-to-extract-only-some-of-the-information-from-a-json-file-in-c.aspx"&gt;How to extract only some of the information from a JSON file in C#&lt;/a&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/16/how-to-send-an-email-message-in-c.aspx"&gt;How to send an email message in C#&lt;/a&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/17/how-to-send-an-sms-text-message-in-c.aspx"&gt;How to send an SMS text message in C#&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
So I'll be posting these examples in the next several days.
&lt;p&gt;&lt;/p&gt;
Meanwhile my latest book is finally available:
&lt;p&gt;&lt;/p&gt;
&lt;a href="wwwwww.amazon.com/MCSD-Certification-Toolkit-Exam-70-483/dp/1118612094"&gt;
&lt;img alt="" src="http://www.csharphelper.com/c_cert_smaller.jpg" style="float: right; margin: 5px; border-width: 0px; border-style: solid;"&gt;
&lt;/a&gt;
&lt;font color="blue"&gt;
&lt;blockquote&gt;
&lt;a href="http://www.amazon.com/MCSD-Certification-Toolkit-Exam-70-483/dp/1118612094"&gt;MCSD Certification Toolkit (Exam 70-483): Programming in C#&lt;/a&gt;
&lt;br&gt;
By Tiberiu Covaci, Rod Stephens, Vincent Varallo, and Gerry O'Brien
&lt;br&gt;
$59.99, 648 pages, May 2012
&lt;br&gt;
ASIN: B00CP2PZB0
&lt;/blockquote&gt;
&lt;/font&gt;
&lt;p&gt;&lt;/p&gt;
The link above is for the paperback edition, but a Kindle edition is also available.
&lt;p&gt;&lt;/p&gt;
To help get some reviews going, I'll announce a drawing for five free copies of this book in the next few days. Stay tuned...
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>miscellany</category><comments>http://blog.csharphelper.com/2013/05/11/anatomy-of-an-example.aspx#Comments</comments><guid isPermaLink="false">20a583b3-3179-4ad9-a6af-6b5a9b43d921</guid><pubDate>Sat, 11 May 2013 19:15:53 GMT</pubDate></item><item><title>Congratulations to winners of the book drawing</title><link>http://blog.csharphelper.com/2013/05/10/congratulations-to-winners-of-the-book-drawing.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;a href="http://blog.csharphelper.com/2013/05/01/book-drawing-visual-basic-2012-programmers-reference.aspx"&gt;
&lt;img alt="" src="http://www.csharphelper.com/vb_2012_prog_ref_tiny.jpg" style="float: right; margin: 5px; border-width: 0px; border-style: solid;"&gt;
&lt;/a&gt;

Congratulations to the following winners of &lt;a href="http://blog.csharphelper.com/2013/05/01/book-drawing-visual-basic-2012-programmers-reference.aspx"&gt;the drawing&lt;/a&gt; for copies of &lt;a href="http://www.vb-helper.com/vb_prog_ref.htm"&gt;Visual Basic 2012 Programmer's Reference&lt;/a&gt;:
&lt;p&gt;&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;John Bisschop
    &lt;/li&gt;
    &lt;li&gt;Scott Earleywine
    &lt;/li&gt;
    &lt;li&gt;Ken Holmberg
    &lt;/li&gt;
    &lt;li&gt;Ken Rambo
    &lt;/li&gt;
    &lt;li&gt;Tony Ropson
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
I'll probably have a drawing for a couple other new books (this time more C#-related) in the next month or two so stay tuned!</description><comments>http://blog.csharphelper.com/2013/05/10/congratulations-to-winners-of-the-book-drawing.aspx#Comments</comments><guid isPermaLink="false">0d649905-51e0-434c-8988-804cd2c6da4e</guid><pubDate>Fri, 10 May 2013 16:09:45 GMT</pubDate></item><item><title>Make an owner drawn ListBox that left and right justifies columns of values in C#</title><link>http://blog.csharphelper.com/2013/05/08/make-an-owner-drawn-listbox-that-left-and-right-justifies-columns-of-values-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;center&gt;
&lt;img alt="" src="http://www.csharphelper.com/howto_listbox_ownerdraw_columns.png" style="margin-top: 5px; margin-bottom: 5px; border-width: 0px; border-style: solid;"&gt;
&lt;/center&gt;
The following examples show different ways to make a ListBox control format and align values.
&lt;ul&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/03/right-justify-values-in-a-listbox-in-c.aspx"&gt;Right-justify values in a ListBox in C#&lt;/a&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/05/06/use-the-listbox-controls-formatstring-property-to-format-values-in-c.aspx"&gt;Use the ListBox control's FormatString property to format values in C#&lt;/a&gt;
    &lt;/li&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2009/12/04/set-tab-positions-inside-a-listbox-or-textbox-in-c.aspx"&gt;Set tab positions inside a ListBox or TextBox in C#&lt;/a&gt;
    &lt;/li&gt;
&lt;/ul&gt;
Unfortunately the ListBox doesn't provide a way to line up multiple columns of left and right justified values. You can do that yourself by making an owner-drawn ListBox, but it requires some extra work.
&lt;p&gt;&lt;/p&gt;
This example uses the techniques described in &lt;a href="http://blog.csharphelper.com/2013/05/07/draw-rows-of-data-in-left-and-right-justified-columns-in-c.aspx"&gt;Draw rows of data in left and right justified columns in C#&lt;/a&gt; to make an owner-drawn ListBox draw values in justified columns.
&lt;p&gt;&lt;/p&gt;
When the program starts, it executes the following code.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Make the ListBox owner-drawn and give it data.
private void Form1_Load(object sender, EventArgs e)
{
    lstBooks.DrawMode = DrawMode.OwnerDrawVariable;
    lstBooks.Items.AddRange(Values);
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This code makes the ListBox owner-drawn and gives it some data. The variable Values is an array of arrays of strings. In other words, it contains values for each row and each row holds an array of strings.
&lt;p&gt;&lt;/p&gt;
When you use an owner-drawn ListBox, you must handle two key events: MeasureItem and DrawItem. The MeasureItem event handler shown in the following code is called to tell the owner-drawn ListBox how much room it should leave for a menu item.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Row and column sizes.
private float RowHeight, RowWidth;
private float[] ColWidths = null;

private const float RowMargin = 10;
private const float ColumnMargin = 10;

// Return the desired size of an item.
private void lstBooks_MeasureItem(object sender, MeasureItemEventArgs e)
{
    // Measure the data if we haven't already done so.
    if (ColWidths == null)
    {
        // Get the row and column sizes.
        GetRowColumnSizes(e.Graphics, lstBooks.Font, Values, out RowHeight, out ColWidths);

        // Add margins.
        for (int i = 0; i &amp;lt; ColWidths.Length; i++) ColWidths[i] += ColumnMargin;
        RowHeight += RowMargin;

        // Get the total row width.
        RowWidth = ColWidths.Sum();
    }

    // Set the desired size.
    e.ItemHeight = (int)RowHeight;
    e.ItemWidth = (int)RowWidth;
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
If ColWidths is null, then the program has not yet measured the data. In that case, this code calls the GetRowColumnSizes method to calculate the maximum row height and the column widths for the data values. For more information on this method, see the previous example &lt;a href="http://blog.csharphelper.com/2013/05/07/draw-rows-of-data-in-left-and-right-justified-columns-in-c.aspx"&gt;Draw rows of data in left and right justified columns in C#&lt;/a&gt;.
&lt;p&gt;&lt;/p&gt;
The code then adds a margin to each column's width and to the maximum row height so the values aren't too crowded when they are drawn.
&lt;p&gt;&lt;/p&gt;
Finally the event handler sets e.ItemHeight and e.ItemWidth to tell the owner-drawn control how much room to allow for the menu item.
&lt;p&gt;&lt;/p&gt;
The following DrawItem event handler is called when the owner-drawn ListBox needs to draw a menu item.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Draw an item.
private void lstBooks_DrawItem(object sender, DrawItemEventArgs e)
{
    string[] values = (string[])lstBooks.Items[e.Index];
    e.DrawBackground();
    if ((e.State &amp;amp; DrawItemState.Selected) == DrawItemState.Selected)
    {
        DrawRow(e.Graphics, lstBooks.Font, SystemBrushes.HighlightText, null,
            e.Bounds.X, e.Bounds.Y, RowHeight, ColWidths,
            VertAlignments, HorzAlignments, values, false);
    }
    else
    {
        DrawRow(e.Graphics, lstBooks.Font, Brushes.Black, null,
            e.Bounds.X, e.Bounds.Y, RowHeight, ColWidths,
            VertAlignments, HorzAlignments, values, false);
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This code gets the data for the ListBox row that it needs to draw. It then calls e.DrawBackground to draw an appropriate background. (If the item is selected (the user clicked it), the background is blue. If the item is not selected, the background is white.)
&lt;p&gt;&lt;/p&gt;
The code then calls the DrawRow method to draw the row in the ListBox. If the ListBox item is selected (the user clicked it), then it draws the item with the system-defined text highlight color. If the item is not selected, the code calls DrawRow to draw the row with black text.
&lt;p&gt;&lt;/p&gt;
The code also passes the call to DrawBox the X and Y coordinates of the row's upper left corner as given by the event handler's e.Bounds parameter.
&lt;p&gt;&lt;/p&gt;
The following code shows the DrawRow method.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Draw the items in columns.
private void DrawRow(Graphics gr, Font font, Brush brush, Pen box_pen,
    float x0, float y0, float row_height, float[] col_widths,
    StringAlignment[] vert_alignments, StringAlignment[] horz_alignments,
    string[] values, bool draw_box)
{
    // Create a rectangle in which to draw.
    RectangleF rect = new RectangleF();
    rect.Height = row_height;

    using (StringFormat sf = new StringFormat())
    {
        float x = x0;
        for (int col_num = 0; col_num &amp;lt; values.Length; col_num++)
        {
            // Prepare the StringFormat and drawing rectangle.
            sf.Alignment = horz_alignments[col_num];
            sf.LineAlignment = vert_alignments[col_num];
            rect.X = x;
            rect.Y = y0;
            rect.Width = col_widths[col_num];

            // Draw.
            gr.DrawString(values[col_num], font, brush, rect, sf);

            // Draw the box if desired.
            if (draw_box) gr.DrawRectangle(box_pen,
                rect.X, rect.Y, rect.Width, rect.Height);

            // Move to the next column.
            x += col_widths[col_num];
        }
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This method makes a RectangleF and a StringFormat that it will use to draw the row's items and then loops through those items. For each item, the code sets the StringFormat's Alignment and LineAlignment properties and draws the item at the appropriate location. If the draw_box parameter is true, the code also draws the RectangleF. (This is mostly for debugging.)
&lt;p&gt;&lt;/p&gt;
After it draws each item, it increases the X coordinate so it is ready to draw the next item.
&lt;p&gt;&lt;/p&gt;
This example is fairly complicated but still manageable. An alternative would be to use a ListView control instead of a ListBox. The behavior isn't quite the same so it doesn't provide exactly the same look and feel, but the ListView lets you set up more of the details about column justification interactively at design time.
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Download Example" hspace="10" href="http://www.csharphelper.com/examples/howto_listbox_ownerdraw_columns.zip"&gt;&lt;img alt="" src="http://www.csharphelper.com/Download.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>graphics</category><category>fonts</category><category>controls</category><category>lists</category><comments>http://blog.csharphelper.com/2013/05/08/make-an-owner-drawn-listbox-that-left-and-right-justifies-columns-of-values-in-c.aspx#Comments</comments><guid isPermaLink="false">5231bdf8-071f-4314-a73a-399519ad7947</guid><pubDate>Wed, 08 May 2013 15:27:34 GMT</pubDate></item><item><title>Draw rows of data in left and right justified columns in C#</title><link>http://blog.csharphelper.com/2013/05/07/draw-rows-of-data-in-left-and-right-justified-columns-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;center&gt;
&lt;img alt="" src="http://www.csharphelper.com/howto_align_columns_gdi.png" style="margin-top: 5px; margin-bottom: 5px; border-width: 0px; border-style: solid;"&gt;
&lt;/center&gt;
This example draws a series of rows with columns left or right justified. The program uses the following code to define the data it will draw and the row and column alignments.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// The values.
private string[][] Values =
    {
        new string[] { "C# 24-Hour Trainer", ... , "10/10/2010" },
        new string[] { "Beginning Database Design Solutions", ... , "8/8/2008" },
        ...
    };

// The column alignments.
private StringAlignment[] VertAlignments =
{
    StringAlignment.Center,
    StringAlignment.Center,
    ...
};
private StringAlignment[] HorzAlignments =
{
    StringAlignment.Near,
    StringAlignment.Near,
    StringAlignment.Far,
    StringAlignment.Far,
    StringAlignment.Far,
};&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The data that will be drawn is an array of arrays of strings. In other words, each row is represented by an array of string values.
&lt;p&gt;&lt;/p&gt;
The VertAlignments array holds the vertical alignments that should be used to draw each row. The HorzAlignments array holds the horizontal alignments for the data's columns.
&lt;p&gt;&lt;/p&gt;
The most interesting part of the program involves two methods: GetRowColumnSizes and DrawTextRowsColumns. The following code shows the GetRowColumnSizes method, which returns the data's maximum row height and the widths of the data's columns.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Return the items' sizes.
private void GetRowColumnSizes(Graphics gr, Font font,
    string[][] values, out float max_height, out float[] col_widths)
{
    // Make room for the column sizes.
    int num_cols = values[0].Length;
    col_widths = new float[num_cols];

    // Examine each row.
    max_height = 0;
    foreach (string[] row in values)
    {
        // Measure the row's columns.
        for (int col_num = 0; col_num &amp;lt; num_cols; col_num++)
        {
            SizeF col_size = gr.MeasureString(row[col_num], font);
            if (col_widths[col_num] &amp;lt; col_size.Width)
                col_widths[col_num] = col_size.Width;
            if (max_height &amp;lt; col_size.Height)
                max_height = col_size.Height;
        }
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This method takes as parameters a Graphics object similar to the one that the program will later use to draw the data and the font that it will use. The code loops through the rows of data. For each row, it loops through the row's columns. For each column entry, the code uses the Graphics object's MeasureString method to see how big that entry will be when displayed and it updates the maximum row height and that column's width.
&lt;p&gt;&lt;/p&gt;
The max_height and col_width parameters are output parameters so the calling code learns the maximum row height and the column widths.
&lt;p&gt;&lt;/p&gt;
The following code shows the DrawTextRowsColumns method.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Draw the items in columns.
private void DrawTextRowsColumns(Graphics gr, Font font, Brush brush, Pen box_pen,
    float x0, float y0, float row_height, float[] col_widths,
    StringAlignment[] vert_alignments, StringAlignment[] horz_alignments,
    string[][] values, bool draw_box)
{
    // Create a rectangle in which to draw.
    RectangleF rect = new RectangleF();
    rect.Height = row_height;

    using (StringFormat sf = new StringFormat())
    {
        foreach (string[] row in values)
        {
            float x = x0;
            for (int col_num = 0; col_num &amp;lt; row.Length; col_num++)
            {
                // Prepare the StringFormat and drawing rectangle.
                sf.Alignment = horz_alignments[col_num];
                sf.LineAlignment = vert_alignments[col_num];
                rect.X = x;
                rect.Y = y0;
                rect.Width = col_widths[col_num];

                // Draw.
                gr.DrawString(row[col_num], font, brush, rect, sf);

                // Draw the box if desired.
                if (draw_box) gr.DrawRectangle(box_pen,
                    rect.X, rect.Y, rect.Width, rect.Height);

                // Move to the next column.
                x += col_widths[col_num];
            }

            // Move to the next line.
            y0 += row_height;
        }
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This method loops through the rows in the data and the columns in each row. For each data value, the code creates a RectangleF that is the maximum row height tall and that column's width wide. It sets a StringFormat object's Alignment and LineAlignment values to properly position the data and then draws it. If the draw_box parameter is true, the code also draws a box around the entry.
&lt;p&gt;&lt;/p&gt;
After drawing each entry in a row, the code advances the variable x to the position where it should draw the next entry. After it finishes a row, the code advances variable y0 so it is ready to draw the next row.
&lt;p&gt;&lt;/p&gt;
The final piece to the example is the PictureBox's Paint event handler shown in the following code.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Display the data aligned in columns.
private void picColumns_Paint(object sender, PaintEventArgs e)
{
    using (Font font = new Font("Times New Roman", 12))
    {
        // Get the row and column sizes.
        float row_height;
        float[] col_widths;
        GetRowColumnSizes(e.Graphics, font, Values, out row_height, out col_widths);

        // Add column margins.
        const float margin = 10;
        for (int i = 0; i &amp;lt; col_widths.Length; i++) col_widths[i] += margin;

        // Draw.
        e.Graphics.Clear(Color.White);
        e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
        DrawTextRowsColumns(e.Graphics, font, Brushes.Black, Pens.Blue,
            margin / 2, margin / 2, row_height, col_widths,
            VertAlignments, HorzAlignments, Values, true);
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
This code calls the GetRowColumnSizes method to get the maximum row height and the column widths. It adds a margin to each column width so the results aren't too crowded.
&lt;p&gt;&lt;/p&gt;
Finally the code clears the PictureBox's background and calls the DrawTextRowsColumns method to draw the data.
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Download Example" hspace="10" href="http://www.csharphelper.com/examples/howto_align_columns_gdi.zip"&gt;&lt;img alt="" src="http://www.csharphelper.com/Download.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>graphics</category><category>fonts</category><category>lists</category><comments>http://blog.csharphelper.com/2013/05/07/draw-rows-of-data-in-left-and-right-justified-columns-in-c.aspx#Comments</comments><guid isPermaLink="false">0d6f8070-475d-4a0e-a7b4-909c82234e81</guid><pubDate>Tue, 07 May 2013 16:27:27 GMT</pubDate></item><item><title>Use the ListBox control's FormatString property to format values in C#</title><link>http://blog.csharphelper.com/2013/05/06/use-the-listbox-controls-formatstring-property-to-format-values-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img alt="" src="http://www.csharphelper.com/howto_listbox_formatstring.png" style="float: right; margin: 5px; border-width: 0px; border-style: solid;"&gt;
The ListBox control's FormatString property determines how the control formats the values it displays. This can be particularly useful if you need to display values that need special formatting such as dates and currency amounts.
&lt;p&gt;&lt;/p&gt;
When it starts, this example uses the following code to display formatted values.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;private void Form1_Load(object sender, EventArgs e)
{
    double[] prices =
    {
        13.38, 7.75, 50.61, 532.21, 8.29, 111.11, 962.38,
        49.27, 4.06, 98.45, 896.13, 7.51, 592.09, 238.29,
    };
    lstC.FormatString = "C";
    lstC.RightToLeft = RightToLeft.Yes;
    lstC.DataSource = prices;

    DateTime[] dates =
    {
        new DateTime(2013, 4, 1),
        new DateTime(2013, 3, 21),
        new DateTime(2013, 7, 18),
        new DateTime(2013, 9, 9),
        new DateTime(2013, 11, 30),
        new DateTime(2013, 2, 12),
        new DateTime(2013, 4, 1),
        new DateTime(2013, 3, 21),
        new DateTime(2013, 7, 18),
        new DateTime(2013, 9, 9),
        new DateTime(2013, 11, 30),
        new DateTime(2013, 2, 12),
    };
    lstNone.RightToLeft = RightToLeft.Yes;
    lstNone.DataSource = dates;

    lstD.FormatString = "D";
    lstD.RightToLeft = RightToLeft.Yes;
    lstD.DataSource = dates;
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The code first create an array of doubles. It sets the lstC ListBox control's FormatString property to C so it displays the values as currency. The code also sets the control's RightToLeft property to Yes so the values are aligned on the right. It then sets the control's DataSource property to the array of values so the control displays them.
&lt;p&gt;&lt;/p&gt;
Next the program creates a list of dates. It sets the lstNone ListBox control's LeftToRight property to Yes and sets its DataSource property so the control displays the dates. The program doesn't set the control's FormatString property so it displays the values with their default formatting.
&lt;p&gt;&lt;/p&gt;
The program finishes by displaying the same dates but using the "D" long date format.
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Download Example" hspace="10" href="http://www.csharphelper.com/examples/howto_listbox_formatstring.zip"&gt;&lt;img alt="" src="http://www.csharphelper.com/Download.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>controls</category><comments>http://blog.csharphelper.com/2013/05/06/use-the-listbox-controls-formatstring-property-to-format-values-in-c.aspx#Comments</comments><guid isPermaLink="false">007880de-e05c-4b8e-bf48-03ae74573e25</guid><pubDate>Mon, 06 May 2013 17:44:10 GMT</pubDate></item><item><title>Right-justify values in a ListBox in C#</title><link>http://blog.csharphelper.com/2013/05/03/right-justify-values-in-a-listbox-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img alt="" src="http://www.csharphelper.com/howto_listbox_righttoleft.png" style="float: right; margin: 5px; border-width: 0px; border-style: solid;"&gt;
Sometimes you need to align values on the right in a ListBox. One example where you might want to do that is if you are displaying numbers and want to align them at their decimal points.
&lt;p&gt;&lt;/p&gt;
This example uses the following code to display numbers aligned on the right.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;private void Form1_Load(object sender, EventArgs e)
{
    double[] values =
    {
        111111.111111, 888888.888888,
        13.38, 7.75, 50.61, 532.21, 8.29, 111.11, 962.38,
        49.27, 4.06, 98.45, 896.13, 7.51, 592.09, 238.29,
    };
    lstPrices.DataSource = values;

    lstRightAligned.RightToLeft = RightToLeft.Yes;
    lstRightAligned.DataSource = values;
    
    lstFixedWidth.RightToLeft = RightToLeft.Yes;
    lstFixedWidth.DataSource = values;
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The code sets the DataSource for three ListBox controls to an array of double values. Note that all of the values (except the first two, which I'll explain in a moment) have 2 digits after the decimal point so their decimal points line up.
&lt;p&gt;&lt;/p&gt;
The key is to set a ListBox's RightToLoeft property. This makes the control align the values it displays on their right edge instead of on their left edge.
&lt;p&gt;&lt;/p&gt;
Note that some fonts, even some that are not fixed-width fonts, still use fixed widths for digits so numbers line up nicely. In the middle ListBox, which uses the default font MS Sans Serif, the first two entries display 6 digits after the decimal point but their decimal points still line up. In the ListBox on the right, which uses the Arial font, the 1s are thinner than the 8s so the decimal points of the first two entries don't line up. (The other decimal points in that ListBox don't line up perfectly either but it's hard to tell because there are only 2 digits after the decimal point so it's very close.)
&lt;p&gt;&lt;/p&gt;
&lt;a alt="Download Example" hspace="10" href="http://www.csharphelper.com/examples/howto_listbox_righttoleft.zip"&gt;&lt;img alt="" src="http://www.csharphelper.com/Download.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a alt="Follow me on Twitter" hspace="10" href="http://twitter.com/CSharpHelper"&gt;&lt;img alt="" src="http://www.csharphelper.com/Twitter.png" style="border-width: 0px; border-style: solid;"&gt;&lt;/a&gt;</description><category>controls</category><comments>http://blog.csharphelper.com/2013/05/03/right-justify-values-in-a-listbox-in-c.aspx#Comments</comments><guid isPermaLink="false">3187f267-4fc6-4877-b231-784d5acf848f</guid><pubDate>Fri, 03 May 2013 14:38:01 GMT</pubDate></item><item><title>Delete large numbers of files easily and quickly in C#</title><link>http://blog.csharphelper.com/2013/05/02/delete-large-numbers-of-files-easily-and-quickly-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img alt="" style="float: right; margin: 5px; border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/howto_delete_files.png"&gt;
A while ago I needed to delete a large number of files that were created when I opened old projects in a newer version of Visual Studio. (As far as I know, there's no way to tell Visual Studio not to create these files.) I don't know why, but Windows Explorer was taking several seconds to delete each file and there were almost a hundred so the whole thing was taking far too long. Rather than waiting the 5 or so minutes it would have taken to delete them all, I wrote this program to delete the files. (This probably took longer than waiting for Windows Explorer to do the job but it was more interesting and if this happens again I'll have the program ready.)
&lt;p&gt;&lt;/p&gt;
Enter a directory path and a pattern to match and click List Files to see a list of the files matching the pattern in the directory you entered and its subdirectories. Initially all of the matching files are checked in the CheckedListBox. Review the list to make sure you want to delete the files, uncheck any that you want to keep, and click Delete to make the files go away forever.
&lt;p&gt;&lt;/p&gt;
If you want to move the files into the recycle bin instead of permanently deleting them, see this example:
&lt;p&gt;&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;a href="http://blog.csharphelper.com/2011/01/25/move-files-and-directories-into-the-recycle-bin-wastebasket-see-how-many-items-are-in-the-recycle-bin-and-empty-the-recycle-bin-in-c.aspx"&gt;Move files and directories into the recycle bin (wastebasket), see how many items are in the recycle bin, and empty the recycle bin in C#&lt;/a&gt;
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
The following code shows how the program lists the files that match the pattern you entered.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// List the selected files.
private void btnListFiles_Click(object sender, EventArgs e)
{
    clstFiles.Items.Clear();
    try
    {
        DirectoryInfo dir_info = new DirectoryInfo(txtPath.Text);
        foreach (FileInfo file_info in dir_info.GetFiles(
            txtPattern.Text, SearchOption.AllDirectories))
        {
            int index = clstFiles.Items.Add(file_info.FullName);
            clstFiles.SetItemChecked(index, true);
        }
        lblNumFiles.Text = clstFiles.Items.Count + " files";
        btnDelete.Enabled = clstFiles.CheckedIndices.Count &amp;gt; 0;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
The code starts by clearing the CheckedListBox. It then creates a DirectoryInfo object representing the directory path that you entered. It uses that object's GetFiles method to get a collection of FileInfo objects representing the files matching the pattern that you entered.
&lt;p&gt;&lt;/p&gt;
The program adds each file's name to the CheckedListBox and checks it. The code uses the index of the newly added file to check it instead of simply checking the last item in the list because the control's Sorted property is set to true. That means the new file may not be added to the end of the list. (Alternatively you could add all of the files and then check them all afterwards.)
&lt;p&gt;&lt;/p&gt;
This piece of code finishes by displaying the number of files listed and enabling the Delete button.
&lt;p&gt;&lt;/p&gt;
The following code shows how the program deletes the checked files.
&lt;p&gt;&lt;/p&gt;
&lt;pre&gt;&lt;tt&gt;// Delete the checked files.
private void btnDelete_Click(object sender, EventArgs e)
{
    string[] filenames = new string[clstFiles.CheckedItems.Count];
    clstFiles.CheckedItems.CopyTo(filenames, 0);
    foreach (string filename in filenames)
    {
        Console.WriteLine(filename);
        try
        {
            File.Delete(filename);
            clstFiles.Items.Remove(filename);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error deleting file. " + ex.Message);
            if (MessageBox.Show("Error deleting file. " + ex.Message +
                Environment.NewLine + Environment.NewLine +
                "Continue?", "Continue?",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == DialogResult.No)
                break;
        }
    }

    lblNumFiles.Text = clstFiles.CheckedItems.Count + " files";
    btnDelete.Enabled = clstFiles.CheckedItems.Count &amp;gt; 0;
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
Normally if you just want to loop through the checked items in a CheckedListBox, you can iterate over its CheckedItems collection. However, this example removes files from the CheckedListBox as they are deleted. A C# program cannot modify a collection while it is iterating over it so this code first copies the file names into an array. It then loops through the array so it can remove items from the CheckedListBox with no problems.
&lt;p&gt;&lt;/p&gt;
As it loops through the file names, the code displays the name in the Console window. It uses File.Delete to permanently delete the file and then removes the file name from the CheckedListBox.
&lt;p&gt;&lt;/p&gt;
If anything goes wrong, the code displays a MessageBox telling you what the problem is and asking if you want to continue. If you click No, the code breaks out of the loop. (I figure if something goes wrong, then it might happen a lot of times. For example, if you don't have delete permission on a directory containing hundreds of files, the program may fail hundreds of times and it could take you a while to close each MessageBox separately. This gives you a way to stop the process.
&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_delete_files.zip" hspace="10" alt="Download Example"&gt;&lt;img alt="" style="border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/Download.png"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img alt="" style="border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/Twitter.png"&gt;&lt;/a&gt;</description><category>system</category><category>files</category><comments>http://blog.csharphelper.com/2013/05/02/delete-large-numbers-of-files-easily-and-quickly-in-c.aspx#Comments</comments><guid isPermaLink="false">7446eb59-f250-4842-aa6a-489611438d21</guid><pubDate>Thu, 02 May 2013 20:41:20 GMT</pubDate></item><item><title>Book Drawing: Visual Basic 2012 Programmer's Reference</title><link>http://blog.csharphelper.com/2013/05/01/book-drawing-visual-basic-2012-programmers-reference.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;h3&gt;This drawing is closed&lt;/h3&gt;

&lt;a href="http://www.vb-helper.com/vb_prog_ref.htm"&gt;
&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;font style="font-size: 12px;"&gt;&lt;/font&gt;&lt;img alt="" style="float: right; margin: 5px; border-width: 0px; border-style: solid;" src="http://www.csharphelper.com/vb_prog_ref.png"&gt;
&lt;/a&gt;
&lt;blockquote&gt;
&lt;font color="blue" size="3"&gt;
Visual Basic 2012 Programmer's Reference
&lt;br&gt;
$44.99, 840 pages, 2012
&lt;br&gt;
John Wiley &amp;amp; Sons
&lt;br&gt;
ISBN 13: 978-1118314074
&lt;/font&gt;
&lt;/blockquote&gt;
Book sales these days are heavily driven by reviews and this book hasn't gotten enough. In an attempt to generate more reviews, I'm giving away 4 copies of the book. Here are some details:
&lt;p&gt;&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;By entering the drawing, you promise to post a review. I don't want you to promise a &lt;b&gt;good&lt;/b&gt; review, just an &lt;b&gt;honest&lt;/b&gt; review. I think this is a good book and it can stand for itself.
    &lt;/li&gt;
    &lt;li&gt;This is a Visual Basic book not a C# book. All of the same ideas apply to both languages but if you're not interested in Visual Basic, then you may find translating the details to be annoying.
    &lt;/li&gt;
    &lt;li&gt;This book also focuses on the programming language not on Metro issues (or whatever Microsoft is calling the new Windows 8 style today). It uses Visual Studio Express 2012 for Windows Desktop, which you can download for free &lt;a href="http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-for-windows-desktop"&gt;here&lt;/a&gt;.
    &lt;/li&gt;
    &lt;li&gt;To enter, send an email with the subject "Book drawing" to &lt;a href="mailto:RodStephens@CSharpHelper.com"&gt;RodStephens@CSharpHelper.com&lt;/a&gt; by May 7, 2013.
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
If you want a fast-paced in-depth introduction to Visual Basic, sign up for the drawing and you might win a free book!
&lt;p&gt;&lt;/p&gt;
(If by some chance you already own a copy of this book, or a copy of any of my books, please post a review! Reviews are what sells books and without sales I can't keep writing. Please don't make me get a real job!)</description><category>books</category><comments>http://blog.csharphelper.com/2013/05/01/book-drawing-visual-basic-2012-programmers-reference.aspx#Comments</comments><guid isPermaLink="false">78ed74d2-e116-4f90-9c87-632d80ee485d</guid><pubDate>Wed, 01 May 2013 18:59:30 GMT</pubDate></item><item><title>Make a modal context menu in C#</title><link>http://blog.csharphelper.com/2013/05/01/make-a-modal-context-menu-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_modal_contextmenu.png" align="right" border="0" hspace="5" vspace="5"&gt;

Sorry for the long hiatus. I've been finishing the initial draft for a book about algorithms and it turned out to be more time consuming than I had expected. I'll post details when it is closer to publication.
&lt;p&gt;&lt;/p&gt;
Not long ago, someone asked me whether you could make a modal context menu. He wanted to be able to display a floating menu and make the user pick a selection before continuing.
&lt;p&gt;&lt;/p&gt;
The ContextMenuStrip control doesn't work that way. Context menus are supposed to pop up when the user wants them not when the program wants to display them. I think the idea is that if the user made the menu appear, then the user should be able to make the menu disappear.
&lt;p&gt;&lt;/p&gt;
However, with some work you can make a form that behaves a lot like a modal context menu. This is a fairly long post so it's divided into two sections:
&lt;p&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="#dialog_form"&gt;The Dialog Form&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="#main_form"&gt;The Main Form&lt;/a&gt;
&lt;/li&gt;&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;
&lt;h3&gt;&lt;a name="dialog_form"&gt;The Dialog Form&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;/p&gt;

This example includes a form named ModalMenuForm that contains a single ListBox named lstItems. The program displays the user's choices (Pink, Light Green, and Light Blue) in the ListBox, but ListBox controls don't behave like ContextMenuStrips so the form needs to do some extra work to make it look like a context menu.
&lt;p&gt;&lt;/p&gt;
To make the ListBox look like a context menu, the ListBox is owner drawn. For information about owner-drawn ListBox controls, see these posts:
&lt;p&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://blog.csharphelper.com/2011/06/22/make-an-owner-drawn-listbox-in-c.aspx"&gt;Make an owner-drawn ListBox in C#&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.csharphelper.com/2011/06/23/make-an-owner-drawn-listbox-that-displays-pictures-in-c.aspx"&gt;Make an owner-drawn ListBox that displays pictures in C#&lt;/a&gt;
&lt;/li&gt;&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;
When the form loads, it uses the following code to set up the owner-drawn ListBox.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Get the form ready.
private void ModalMenuForm_Load(object sender, EventArgs e)
{
    // Make the ListBox owner-drawn.
    lstItems.DrawMode = DrawMode.OwnerDrawVariable;

    // Set form properties.
    this.FormBorderStyle = FormBorderStyle.None;
    this.KeyPreview = true;

    // Make the form fit the ListBox.
    this.ClientSize = lstItems.Size;
}&lt;/tt&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;

This code makes the ListBox owner-drawn. It also sets the form's FormBorderStyle property to false so it doesn't display window controls, a title bar, or a border.
&lt;p&gt;&lt;/p&gt;
The code sets the form's KeyPreview property to true so it can look for the Enter and Esc keys. Finally this code resizes the form to fit the ListBox.
&lt;p&gt;&lt;/p&gt;
The form uses the following code to draw the owner-drawn ListBox.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// See: Make an owner-drawn ListBox in C#
// &lt;a href="http://blog.csharphelper.com/2011/06/22/make-an-owner-drawn-listbox-in-c.aspx"&gt;blog.csharphelper.com/2011/06/22/make-an-owner-drawn-listbox-in-c.aspx&lt;/a&gt;

// Calculate the size of an item.
private int ItemMargin = 5;
private void lstItems_MeasureItem(object sender, MeasureItemEventArgs e)
{
    // Get the ListBox and the item.
    ListBox lst = sender as ListBox;
    string txt = lst.Items[e.Index].ToString();

    // Measure the string.
    SizeF txt_size = e.Graphics.MeasureString(txt, this.Font);

    // Set the required size.
    e.ItemHeight = (int)txt_size.Height + 2 * ItemMargin;
    e.ItemWidth = (int)txt_size.Width;
}

// Draw the item.
private void lstItems_DrawItem(object sender, DrawItemEventArgs e)
{
    // Get the ListBox and the item.
    ListBox lst = sender as ListBox;
    string txt = lst.Items[e.Index].ToString();

    // Draw the background.
    e.DrawBackground();

    if ((e.State &amp;amp; DrawItemState.Selected) == DrawItemState.Selected)
    {
        // Selected. Draw with the system highlight color.
        e.Graphics.DrawString(txt, this.Font,
            SystemBrushes.HighlightText, e.Bounds.Left, e.Bounds.Top + ItemMargin);
    }
    else
    {
        // Not selected. Draw with ListBox's foreground color.
        using (SolidBrush br = new SolidBrush(e.ForeColor))
        {
            e.Graphics.DrawString(txt, this.Font, br,
                e.Bounds.Left, e.Bounds.Top + ItemMargin);
        }
    }

    // Don't draw the focus rectangle for
    // this example because the user cannot use
    // the arrow keys to change the selection.
    //// Draw the focus rectangle if appropriate.
    //e.DrawFocusRectangle();
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The MeasureItem event handler returns the size needed for each of the menu items. The DrawItem event handler actually draws the items when needed. (See the links earlier for more details.)
&lt;p&gt;&lt;/p&gt;
There are three points worth mentioning in the DrawItem event handler. First, if the mouse is over the item being drawn, the DrawBackground method draws an appropriate highlighted background. (In the picture, the Light Green choice is highlighted.)
&lt;p&gt;&lt;/p&gt;
Second, if the item being drawn is selected, the code draws its text with the system highlight color so it looks like a highlighted menu item.
&lt;p&gt;&lt;/p&gt;
Third, the code does not draw a focus rectangle around the selected item. The focus rectangle shows which item is selected if you are tabbing among controls. Because you can't tab off of the modal ListBox, there's no reason to do this. (Besides, it looks funny.)
&lt;p&gt;&lt;/p&gt;
The form needs a few other pieces of code to make the ListBox look like a context menu. The following two event handlers make the ListBox select an appropriate item when the mouse moves over it.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Select the ListBox item under the mouse.
private void lstItems_MouseMove(object sender, MouseEventArgs e)
{
    int index = lstItems.IndexFromPoint(e.Location);
    if (lstItems.SelectedIndex != index) lstItems.SelectedIndex = index;
}

// If the form isn't closing, deselect the ListBox item.
private void lstItems_MouseLeave(object sender, EventArgs e)
{
    // If the form is closing, leave the selection alone.
    if (DialogResult != DialogResult.None) return;
    if (lstItems.SelectedIndex != -1) lstItems.SelectedIndex = -1;
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The MouseMove event handler selects the item that is under the mouse.
&lt;p&gt;&lt;/p&gt;
The MouseLeave event handler deselects all items.
&lt;p&gt;&lt;/p&gt;
If the user clicks on an item, the following code executes.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;private void lstItems_Click(object sender, EventArgs e)
{
    if (lstItems.SelectedIndex &amp;lt; 0) DialogResult = DialogResult.Cancel;
    else DialogResult = DialogResult.OK;
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This code sets the form's DialogResult property to OK or Cancel, depending on whether the ListBox has an item selected. Setting DialogResult automatically makes the form close and returns control to the program that displayed the form. It also makes the call to ShowDialog used to display the form return the value if DialogResult (either OK or Cancel).
&lt;p&gt;&lt;/p&gt;
If the user presses a key while the context menu form is visible, the following code executes.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Close the dialog if the user presses Escape or Enter.
private void ModalMenuForm_KeyDown(object sender, KeyEventArgs e)
{
    // If the user pressed Escape, return DialogResult.Cancel.
    if (e.KeyCode == Keys.Escape) DialogResult = DialogResult.Cancel;

    // If the user pressed Escape, return
    // DialogResult.OK if a color is selected.
    if (e.KeyCode == Keys.Enter)
    {
        if (lstItems.SelectedIndex &amp;lt; 0) DialogResult = DialogResult.Cancel;
        else DialogResult = DialogResult.OK;
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
If the user presses Escape, this code sets DialogResult to Cancel to close the form.
&lt;p&gt;&lt;/p&gt;
If the user presses Enter, the code sets DialogResult to either OK or Cancel depending on whether an item is currently selected in the ListBox. (If you don't want the user to be able to close the context menu without making any selection, comment out all of the statements that set DialogResult equal to Cancel.)
&lt;p&gt;&lt;/p&gt;
The final piece of the context menu form is the following SelectedColor property.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Return the color selected in the ListBox.
public Color SelectedColor
{
    get
    {
        if (lstItems.SelectedItem == null) return SystemColors.Control;
        string color_name = lstItems.SelectedItem.ToString().Replace(" ", "");
        return Color.FromName(color_name);
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This read-only property returns the color that is currently selected in the ListBox. The code that displays the context menu should use this property to see which color the user selected. (In a program that uses the menu to select something else, you probably wouldn't want this property to return a color. Instead it could return the selection's index, the selection's text, or some other appropriate value.)
&lt;p&gt;&lt;/p&gt;
To find the color selected by the user, this code takes the name of the selected ListBox item (such as "Light Green"), removes any spaces (to get "LightGreen"), and uses the Color class's FromName method to get the appropriate color.
&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;
&lt;h3&gt;&lt;a name="main_form"&gt;The Main Form&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;&lt;/p&gt;

The main form uses the following code to display the context menu form.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Display the "modal context menu."
private void btnModalMenu_Click(object sender, EventArgs e)
{
    // Create and initialize the dialog.
    ModalMenuForm dlg = new ModalMenuForm();
    Point pt = new Point(btnModalMenu.Right, btnModalMenu.Bottom);
    PositionDialog(dlg, pt);

    // Display the dialog.
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        this.BackColor = dlg.SelectedColor;
    }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The code creates a new context menu form. It then gets a Point representing the location where the modal context menu should appear. This example positions the context menu at the lower right corner of the form's Modal Menu button. (See the picture.)
&lt;p&gt;&lt;/p&gt;
Next the code calls the PositionDialog method (shown shortly) to position the context menu form at that location.
&lt;p&gt;&lt;/p&gt;
The code then displays the context menu form by calling its ShowDialog method. ShowDialog displays the form modally and returns OK or Cancel depending on whether the user accepted or canceled the menu.
&lt;p&gt;&lt;/p&gt;
The following code shows the final piece to the example, the PositionDialog method.

&lt;pre&gt;&lt;tt&gt;// Position the dialog over the indicated point in this form's copordinates.
private void PositionDialog(Form dlg, Point location)
{
    // Translate into screen coordinates.
    Point pt = this.PointToScreen(location);
    Screen screen = Screen.FromControl(dlg);

    // Adjust if this is at an edge of the screen.
    if (pt.X &amp;lt; screen.WorkingArea.X)
        pt.X = screen.WorkingArea.X;
    if (pt.Y &amp;lt; screen.WorkingArea.Y)
        pt.Y = screen.WorkingArea.Y;
    if (pt.X &amp;gt; screen.WorkingArea.Right - dlg.Width)
        pt.X = screen.WorkingArea.Right - dlg.Width;
    if (pt.Y &amp;gt; screen.WorkingArea.Bottom - dlg.Height)
        pt.Y = screen.WorkingArea.Bottom - dlg.Height;

    // Position the dialog.
    dlg.StartPosition = FormStartPosition.Manual;
    dlg.Location = pt;
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This method converts the indicated point from form the main form's coordinates to screen coordinates. It then gets the screen that holds the dialog. It adjusts the indicated point if necessary to keep the dialog on the screen. The method finishes by setting the dialog's StartPosition and Location properties so it begins in the desired location when it is displayed.
&lt;p&gt;&lt;/p&gt;
For more details, see these posts:
&lt;p&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/04/17/find-the-screen-object-on-which-a-form-is-running-in-c.aspx"&gt;Find the Screen object on which a form is running in C#&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.csharphelper.com/2013/04/18/position-a-form-so-it-does-not-stick-off-the-edge-of-the-screen-in-c.aspx"&gt;Position a form so it does not stick off the edge of the screen in C#&lt;/a&gt;
&lt;/li&gt;&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;
The process isn't as easy as displaying a ContextMenuStrip, but if you follow each of the steps you should be able to display a homegrown modal context menu.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_modal_contextmenu.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>menus</category><category>forms</category><comments>http://blog.csharphelper.com/2013/05/01/make-a-modal-context-menu-in-c.aspx#Comments</comments><guid isPermaLink="false">949e74c5-a800-4faf-b76b-c251ceba17e3</guid><pubDate>Wed, 01 May 2013 18:09:01 GMT</pubDate></item><item><title>Understand the startup form (or main form) in C#</title><link>http://blog.csharphelper.com/2013/04/19/understand-the-startup-form-or-main-form-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_startup_form.png" align="right" border="0" hspace="5" vspace="5"&gt;

When a C# Windows Forms program starts, it displays a startup form. That form has a special place in the program's life cycle. If that form ever closes, the application ends.
&lt;p&gt;&lt;/p&gt;
The program can create and close as many other forms as it wants in any order without closing the program. The startup form is special in that respect.
&lt;p&gt;&lt;/p&gt;
When you click this example's New Form button, the following code displays a new instance of the main form.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Display a new form with a blue background.
private void btnNewForm_Click(object sender, EventArgs e)
{
    Form1 frm = new Form1();
    frm.BackColor = Color.LightBlue;
    frm.Show();
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This code simply creates a new instance of the form, sets its background color to light blue so you can distinguish the new forms from the startup form, and displays the form.
&lt;p&gt;&lt;/p&gt;
Run the program and create and close a few forms. Then create a form or two and close the startup form to see that the whole program stops.
&lt;p&gt;&lt;/p&gt;
This is not really much of a problem as long as you are aware of the situation.
&lt;p&gt;&lt;/p&gt;
So what can you do if you don't want the user to stop the application by closing the main form? This example uses the following FormClosing event handler to prevent the startup form from closing if any form's "Prevent Startup From Closing" CheckBox is checked.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// If this is the main form and any other forms have their
// Prevent Startup From Closing boxes checked, don't close.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // See if this is the main form.
    if (this == Application.OpenForms[0])
        // See if any form has the CheckBox checked.
        foreach (Form1 frm in Application.OpenForms)
            if (frm.chkPreventStartupFromClosing.Checked)
            {
                e.Cancel = true;
                break;
            }
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
If the form that is executing the FormClosing event handler is the startup form, then it is first in the Application object's OpenForms collection. If this is the startup form, then the code loops through all of the open forms. If the CheckBox on any open form is checked, then the event handler sets e.Cancel to true to prevent the form from closing.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_startup_form.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>forms</category><comments>http://blog.csharphelper.com/2013/04/19/understand-the-startup-form-or-main-form-in-c.aspx#Comments</comments><guid isPermaLink="false">f9b94402-cd1c-4f81-ba84-f6dd827cfc75</guid><pubDate>Fri, 19 Apr 2013 14:05:07 GMT</pubDate></item><item><title>Position a form so it does not stick off the edge of the screen in C#</title><link>http://blog.csharphelper.com/2013/04/18/position-a-form-so-it-does-not-stick-off-the-edge-of-the-screen-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_position_form_popup.png" align="right" border="0" hspace="5" vspace="5"&gt;

In the picture, the program initially positioned the top form so it was hanging off the right and bottom edges of the screen. The program's code moved the form so it fit in the screen's lower right corner.
&lt;p&gt;&lt;/p&gt;
When you click this form's New Form button, the following code displays a new instance of the program's form.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Position a new instance of this form
// just to the right and below the button.
private void btnShowForm_Click(object sender, EventArgs e)
{
    // Get the location in this form's coordinate system.
    Point form_pt = new Point(
        btnShowForm.Left + btnShowForm.Width / 2,
        btnShowForm.Top + btnShowForm.Height / 2);

    // Translate into the screen coordinate system.
    Point screen_pt = this.PointToScreen(form_pt);

    // Create the new form.
    Form1 frm = new Form1();

    // Make sure the form will be completely on the screen.
    Screen screen = Screen.FromControl(this);
    if (screen_pt.X &amp;lt; 0) screen_pt.X = 0;
    if (screen_pt.Y &amp;lt; 0) screen_pt.Y = 0;
    if (screen_pt.X &amp;gt; screen.WorkingArea.Right - frm.Width)
        screen_pt.X = screen.WorkingArea.Right - frm.Width;
    if (screen_pt.Y &amp;gt; screen.WorkingArea.Bottom - frm.Height)
        screen_pt.Y = screen.WorkingArea.Bottom - frm.Height;

    // Position the new form.
    frm.StartPosition = FormStartPosition.Manual;
    frm.Location = screen_pt;
    frm.Show();
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The code makes a Point representing the center of the button. It calls PointToScreen to translate the point's coordinates to screen coordinates.
&lt;p&gt;&lt;/p&gt;
The code then creates a new form. It gets the Screen object that is displaying the form and adjusts the Point's coordinates to ensure that the form is completely on that Screen.
&lt;p&gt;&lt;/p&gt;
Finally the code sets the form's position and displays the form.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_position_form_popup.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>forms</category><comments>http://blog.csharphelper.com/2013/04/18/position-a-form-so-it-does-not-stick-off-the-edge-of-the-screen-in-c.aspx#Comments</comments><guid isPermaLink="false">95d6e091-5b28-4e50-a5a1-8f0e965971a5</guid><pubDate>Thu, 18 Apr 2013 22:47:10 GMT</pubDate></item><item><title>Find the Screen object on which a form is running in C#</title><link>http://blog.csharphelper.com/2013/04/17/find-the-screen-object-on-which-a-form-is-running-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_get_forms_screen.png" align="right" border="0" hspace="5" vspace="5"&gt;

This is an issue if the user is using more than one monitor.
&lt;p&gt;&lt;/p&gt;
When this program starts, it uses the following code to get the Screen object that holds the form and display its device name, whether it is the primary screen, and its working area.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;private void Form1_Load(object sender, EventArgs e)
{
    Screen screen = Screen.FromControl(this);
    txtDeviceName.Text = screen.DeviceName;
    txtIsPrimary.Text = screen.Primary.ToString();
    txtWorkingArea.Text = screen.WorkingArea.ToString();
    txtDeviceName.Select(0, 0);
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The only non-obvious part of this code is the first statement where the program uses Screen.FromControl to get the Screen object holding the form.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_get_forms_screen.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>forms</category><comments>http://blog.csharphelper.com/2013/04/17/find-the-screen-object-on-which-a-form-is-running-in-c.aspx#Comments</comments><guid isPermaLink="false">2b0ec9a0-98f9-4d47-811e-c452b2330eb6</guid><pubDate>Wed, 17 Apr 2013 16:39:22 GMT</pubDate></item><item><title>Position a form over a location on the creating form in C#</title><link>http://blog.csharphelper.com/2013/04/16/position-a-form-over-a-location-on-the-creating-form-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_position_form_over_form.png" align="right" border="0" hspace="5" vspace="5"&gt;

When you click this example's button, the program uses the following code to display a new instance of the form positioned next to the button's lower left corner (as shown in the picture).
&lt;br clear="right"&gt;
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Position a new instance of this form
// just to the right and below the button.
private void btnShowForm_Click(object sender, EventArgs e)
{
    // Get the location in this form's coordinate system.
    Point form_pt = new Point(btnShowForm.Right, btnShowForm.Bottom);

    // Translate into the screen coordinate system.
    Point screen_pt = this.PointToScreen(form_pt);

    // Create and position the form.
    Form1 frm = new Form1();
    frm.StartPosition = FormStartPosition.Manual;
    frm.Location = screen_pt;
    frm.Show();
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The code creates a Point that holds the new form's desired location in this form's coordinate system. It then calls the form's PointToScreen method to convert the point into screen coordinates.
&lt;p&gt;&lt;/p&gt;
The code finishes by creating, positions, and displaying a new form. The only trick here is remembering to set the new form's StartPosition property to Manual so the form is positioned where its Location property says it should be.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_position_form_over_form.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>forms</category><comments>http://blog.csharphelper.com/2013/04/16/position-a-form-over-a-location-on-the-creating-form-in-c.aspx#Comments</comments><guid isPermaLink="false">77c66838-c616-4846-84e8-bb8301cf4bdf</guid><pubDate>Tue, 16 Apr 2013 19:06:27 GMT</pubDate></item><item><title>Apply a filter to make a color embossed image in C#</title><link>http://blog.csharphelper.com/2013/04/07/apply-a-filter-to-make-a-color-embossed-image-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_image_filters3.png" align="right" border="0" hspace="5" vspace="5"&gt;

This example extends the earlier one &lt;a href="http://blog.csharphelper.com/2012/05/16/use-image-processing-techniques-to-pixellate-an-image-and-create-other-effects-in-c.aspx"&gt;Apply filters to images to perform edge detection, smoothing, embossing, and more in C#&lt;/a&gt; by adding a new filter that embosses a color image without removing most of the color information. The filter's kernel is:
&lt;p&gt;&lt;/p&gt;

&lt;center&gt;
&lt;table&gt;
  &lt;tbody&gt;&lt;tr&gt;&lt;td align="right" width="20"&gt;1&lt;/td&gt;&lt;td align="right" width="20"&gt;1&lt;/td&gt;&lt;td align="right" width="20"&gt;-1&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td align="right" width="20"&gt;1&lt;/td&gt;&lt;td align="right" width="20"&gt;1&lt;/td&gt;&lt;td align="right" width="20"&gt;-1&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td align="right" width="20"&gt;1&lt;/td&gt;&lt;td align="right" width="20"&gt;-1&lt;/td&gt;&lt;td align="right" width="20"&gt;-1&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;/center&gt;

&lt;p&gt;&lt;/p&gt;
The kernel divides the result by 1 and uses no offset so it retains most of the image's color information. See the &lt;a href="http://blog.csharphelper.com/2012/05/16/use-image-processing-techniques-to-pixellate-an-image-and-create-other-effects-in-c.aspx"&gt;previous post&lt;/a&gt; for more information about how kernels work.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_image_filters3.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>algorithms</category><category>graphics</category><comments>http://blog.csharphelper.com/2013/04/07/apply-a-filter-to-make-a-color-embossed-image-in-c.aspx#Comments</comments><guid isPermaLink="false">e9d08861-f5a4-461b-9aa5-3f5c4f29c5e8</guid><pubDate>Sun, 07 Apr 2013 15:10:43 GMT</pubDate></item><item><title>Use listeners to send Debug and Trace information into a file in C#</title><link>http://blog.csharphelper.com/2013/03/31/use-listeners-to-send-debug-and-trace-information-into-a-file-in-c.aspx?ref=rss</link><dc:creator>Rod Stephens</dc:creator><description>&lt;img src="http://www.csharphelper.com/howto_debug_trace_listeners.png" align="right" border="0" hspace="5" vspace="5"&gt;

By default, the Debug and Trace class send messages to the Console window. Sometimes it might be nice to capture that text and save it in a file. This example shows how you can do that.
&lt;p&gt;&lt;/p&gt;
The Debug and Trace classes have a shared Listener collection that contains listener objects. The classes actually send their message to those objects not directly to the Console window. (Initially the Listeners collection contains a single listener that sends the text it receives to the Console window.) 
&lt;p&gt;&lt;/p&gt;
You can remove the default listener from the collection if you like and you can add new listeners to the collection. This example uses the following code to add a TextWriterListener that appends the text it receives to a text file.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Make the listener.
private void Form1_Load(object sender, EventArgs e)
{
    string trace_file = Application.StartupPath + "//trace.txt";
    Trace.Listeners.Add(new TextWriterTraceListener(trace_file));
    Trace.AutoFlush = true;
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
The code composes a file name. It then creates a TextWriterTraceListener, passing its constructor the file name, and adds the new listener to the Trace object's Listener collection. The Debug and Trace classes share Listeners collections so this listener will write both Trace and Debug messages into the file.
&lt;p&gt;&lt;/p&gt;
By default the Debug and Trace classes do not flush text buffers into text files so if the program ends without you explicitly flushing the output, some or all of the text may not be written into the file. The program avoids this problem by setting the Trace object's AutoFlush property to true.
&lt;p&gt;&lt;/p&gt;
If you enter a message in the program's TextBox and click Debug, the program executes the following code.
&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;tt&gt;// Send a message to the Debug listeners.
private void btnDebug_Click(object sender, EventArgs e)
{
    Debug.WriteLine(txtMessage.Text);
    txtMessage.Clear();
    txtMessage.Focus();
}&lt;/tt&gt;&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;
This code uses the Debug.WriteLine method to send a message to the listeners. The default listener sends the text to the Console window and the other listener appends the text to the text file trace.txt.

&lt;p&gt;&lt;/p&gt;
&lt;a href="http://www.csharphelper.com/examples/howto_debug_trace_listeners.zip" hspace="10" alt="Download Example"&gt;&lt;img src="http://www.csharphelper.com/Download.png" border="0"&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href="http://twitter.com/CSharpHelper" hspace="10" alt="Follow me on Twitter"&gt;&lt;img src="http://www.csharphelper.com/Twitter.png" border="0"&gt;&lt;/a&gt;</description><category>debugging</category><comments>http://blog.csharphelper.com/2013/03/31/use-listeners-to-send-debug-and-trace-information-into-a-file-in-c.aspx#Comments</comments><guid isPermaLink="false">3132bf2e-52cf-4b15-a908-88851cc97215</guid><pubDate>Mon, 01 Apr 2013 02:31:32 GMT</pubDate></item></channel></rss>