# Monday, July 29, 2013
Monday, July 29, 2013 4:22:00 PM (GMT Daylight Time, UTC+01:00)
# Tuesday, June 5, 2012

The .NET Framework provides configuration files - app.config and web.config - to store application-wide configurable information.

But these are just text files, so they can be read by anyone with the proper permissions. What if I want to store sensitive information in this file, such as a password or a connection string?f

Fortunately, the .NET Framework also provides a mechanism for encrypting parts of a config file. This functionality is available in the System.Configuration namespace in the System.Configuration assembly, so you will need to set a reference to this assembly (Project | Add Reference | .NET tab) and add the following line to the top of your class file
using System.Configuration;

The ConfigurationManager.OpenExeConfiguration static method accepts the name of an assembly and returns a Configuration object that can be used to manipulate the config file. It is important to remember that, when a project is built, the project's app.config file is renamed to {AssemblyName}.exe.config and copied to the bin\Debug or bin\Release folder (depending on the build configuration). It is the {AssemblyName}.exe that is passed into the OpenExeConfiguration method and it is the config file under the bin folder that will be affected by our code.

For example, the following code creates a Configuration object to read and manipulate the config file associated with the MyAwesomeApp.exe assembly

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);

We can call the Configuration object's GetSection method to get a reference to a particular section of the config file. For example, if we want to work with the connectionStrings section, we use the code

var section = (ConnectionStringsSection) config.GetSection("connectionStrings");

Now we can check to see if the section is already encrypted (IsProtected property), encrypt the section (ProtectSection method), or decrypt the section (UnprotectSection method). The following code encrypts the connectionString section

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (!section.SectionInformation.IsProtected)
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
config.Save();


The code below decrypts the connectionString section

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
    //it is so we need to remove the encryption
    section.SectionInformation.UnprotectSection();
}
config.Save();

The final step is to write changes back to the file by calling the Configuration object's Save method.
config.Save();

Below is the unencrypted config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="MyApp_Dev" connectionString="Data Source=Server01;Initial Catalog=AwesomeDB_Dev;Integrated Security=True"/>
    <add name="MyApp_QA" connectionString="Data Source=Server01;Initial Catalog=AwesomeDB_QA;Integrated Security=True"/>
    <add name="MyApp_Prod" connectionString="Data Source=Server01;Initial Catalog=AwesomeDB;Integrated Security=True"/>
  </connectionStrings>
  <appSettings>
    <add key="CompanyName" value="The Awesome Company"/>
    <add key="CompanyPhone" value="313-555-4321"/>
  </appSettings>
</configuration>

And here is the same config file with the connectionStrings section encrypted
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAA/NM6tBoQfE2WAlH0NVuRWQQAAAACAAAAAAAQZgAAAAEAACAAAADdZOBg8ugEiLd8RlHk95C+fuXUTC706/hDeZT2XN8G0gAAAAAOgAAAAAIAACAAAABEW5bTk3uNJDoKMt26yvD+YY1v0fqe2et8KWeJOewx3UADAADGEgVw4K4nlwQjjKpu6BZYMYXeB1eovlbYrEbg/A+Kk6UhqBTdAqt6UmW/6B4M2pXWpP9VqDTDfr7GKEK06qDdXRnYfGYH1JAg2xPoI3aeA5DQP6HAIbSymXejw/B+s47L4rTT2R4PvfRfMYiMppxCrEh+eopKdvcg34JsD+o6Il+6a4TiTiYLzQ9BESoxepfY9pqaADFrLChPYzwjymAqfsAFE/n++APjb7aktViu5+AI+QM3RDEhDFzsP7Wy+UkGsPrIoyMUaLMFNibK7LZFiBL6+VHZEur+4xyI+Uu+UH194oBOX1g77nBzuTsivNgH7048JhbzeSk9mjOZrGACX433vC6neqGaJ42sC9sC16JX9CGEZrnipeoyEeR0RT1H3A38Xasn9lYkUyE3LBIJ1k0iZJoAAnCvXfmSzXoXsHjpvmmlst3SAo24TL7WsdaVliBR/6i5N6AswTOemjvFe0Rhb5zoeGX36aI4SD71DYaLxqss1MVm5gc6CEsringGeHbFRqu/kTylA6xgr8rfL/eTcjQs2zRIUTzc4/DUSsyNIUWQ0+z+BDoR/AGTSx7v2OKp2vpmHLf7kn3DxYITlpDV6voJrbmpMx9lN3Z7DYQD4vNLczGPHpKbBCEXDHNw1E7QDrQaz38Ka4pRKnCRa/GL7X8euA82bYaJmEmUEBqhcZg3mQHR31X5tUbZ3HkvMxEUcRmJITpj29V6RKEmugkWmxl3OCJzuZ3vcUSgKnQIAJkqr3YBuZR3YJjDCo7i5EElFAcpv89rM2RtSVNC7i6KLJLsISjOgzD5CktrDjgMZLtxN6BdyljvWNj0L29APvSxd5ovxgCOKXE2UYpH3l4HgX78P82wx1vBNhO5UmqP7xdz1jTi9cGP6HHNiv8qJZjlTOO2/afnDDYt/pKJqWWTRUhJiZZipC+dQ6bBYOhMZbclROzptu0fIYwqdeDxPcXalN3kjIXW4kwblSd4TxmCO01JD9eL+MFT/PSaipj7CqaAHTnpL0n40jV4WK4EaxUTuXi0/NXBUjMFw4ZTdlEnLv1jjCKZ+r2Q1YbrrI286PATrwLDbYsVVGEefp8vBsOD7xfHmIPeYolbEOq2QAAAAHoGwcm8HT1RS0pXvgOjRR37Gy1BLfG/5xsYdZqOB9nT6xthVULhqwPlAsFwDXLfNZQLnpZiocwHDf07DeQiNK8=</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>
  <appSettings>
    <add key="CompanyName" value="The Awesome Company"/>
    <add key="CompanyPhone" value="313-555-4321"/>
  </appSettings>
</configuration>

Here is a complete code snippet for getting a config and toggling the decryption of the connectionStrings section

string appName = "MyAwesomeApp.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
    section.SectionInformation.UnprotectSection();
}
else
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
config.Save();

One of the nice things about using these libraries to encrypt config file sections is that we don’t need to change our code that reads the values in this section. For example, the following code

string connectionString = section.ConnectionStrings["MyApp_Dev"].ConnectionString;
.Net | C#
Tuesday, June 5, 2012 4:01:00 PM (GMT Daylight Time, UTC+01:00)
# Saturday, May 12, 2012

Here is Bill Wagner's presentation at GANG10, the October 1 event celebrating 10 years of the Great Lakes Area .NET User Group. Bill talks about asynchronous programming, including the new features coming in C# 5.

.Net | C# | Video
Saturday, May 12, 2012 3:39:00 PM (GMT Daylight Time, UTC+01:00)
# Friday, May 4, 2012

At Codeslingers last night, someone pulled out some coding Katas. For those who don’t know, a Kata is a coding exercise that is designed to practice your programming skills, rather than to solve a particular business problem. I was handed the classic “FizzBuzz” problem. The assignment:

Create a function that will print the integers from 1 to 100 with the following exceptions:

  • If a number is divisible by 3, print the word “Fizz” in place of that number.
  • If a number is divisible by 5, print the word “Buzz” in place of that number.
  • If a number is divisible by both 3 and 5, print the word “FizzBuzz” in place of that number.

The output should look something like the following:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

I started with a C# console application because that is the language with which I am most familiar. It was able to finish the following in under 2 minutes. It took me 5 minutes to write the unit tests.

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i < 100; i++)
        {
            var p = FizzBuzz(i);
            Console.WriteLine(p);
        }
        Console.ReadLine();
    }

    protected static string FizzBuzz(int i)
    {
        if (i % 15 == 0)
            return "FizzBuzz";
        if (i % 3 == 0)
            return "Fizz";
        if (i % 5 == 0)
            return "Buzz";
        return i.ToString();
    }
}

I only occasionally code in JavaScript, so I tackled that language next. Someone recommended using http://jsfiddle.net/
as an online IDE for writing and sharing JavaScript, so I tried it and liked it. Of course, JavaScript is a dynamic language and one of my big challenges was spelling things correctly without all the help Visual Studio provides when writing in a statically-typed language. In my case, I misspelled the id of a div, which cost me at least 15 minutes. I created the following boilerplate HTML:

<html>
    <body>
        <div id="fizzbuzz"></div>
    </body>
</html>

Then, I used the following JavaScript (plus a bit of jQuery) to output the FizzBuzz results:

for (i = 1; i <= 100; i++) {
    $("#fizzbuzz").append(function() {
        var newLine = i;
        if (i % 3 === 0) {
            newLine = "Fizz";
        }
        if (i % 5 === 0) {
            newLine = "Buzz";
        }
        if (i % 15 === 0) {
            newLine = "FizzBuzz";
        }
        var newDiv = $("<div>").text(newLine);
        return newDiv;
    });
}

A simple program like this provides a fun way to practice an old language and to learn a new language. Next up, I’ll try this program with F# and Ruby, since I have very little experience with these languages.

Friday, May 4, 2012 12:40:00 AM (GMT Daylight Time, UTC+01:00)
# Friday, April 13, 2012

SQL Injection  is one of the most frequently-exploited vulnerabilities in the software world. It refers to user-entered data making its way into commands sent to back-end systems. It is common because so many developers are unaware of the risk and how to mitigate it.

Most of the applications I work with read from and write to a relational database, such as Microsoft SQL Server.  I frequently run across ADO.NET code like the following:

string lastName = "'Adams'";
string sql = "Select * from dbo.Customer where LastName = '" + lastName + "'";
string connString = ConfigurationManager.ConnectionStrings["LocalConn"].ConnectionString;
using (var conn = new SqlConnection(connString))
{
    conn.Open();
    var cmd = conn.CreateCommand();
    cmd.CommandText = sql;
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine("Bad Name: {0} {1}", reader["FirstName"], reader["LastName"]);
    }
}

This code is designed to call a stored procedure like the following:

CREATE PROCEDURE [dbo].[GetCustomersByFirstName]
    @FirstName NVARCHAR(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    SET NOCOUNT ON;

    SELECT 
            Id, 
            FirstName, 
            LastName
        FROM dbo.Customer
        WHERE FirstName = @FirstName
        ORDER BY Id
END

GO

This method of code has several disadvantages

  1. This code is not optimal because SQL Server does not have a chance to reuse a cached query plan unless the user happens to send the exact same text into SQL Server.
  2. The string concatenation opens the system to SQL Injection attacks.

A SQL Injection Attack is an attempt by an unscrupulous user to pass malicious commands to a database. In the above example, imagine that the variable x was provided by a user inputting text into a text box on a web age. An evil user might type something like

"Smith';DROP TABLE Customer;//"

If that code runs with sufficient permissions, it would wreak havoc on your database. The following query would be passed to SQL Server.
Select * from dbo.Customer where LastName = 'Smith';DROP Table Customer;//'

Clearly, dropping the customer table is not what your code is intended to do.

Many of you will read the above example and decide that you are safe because

  1. Your web code runs under a context with insufficient privileges to drop a table; and
  2. You are validating all user inputs to ensure a user cannot enter anything bad.

There are problems with this reasoning.

  1. A clever hacker can sometimes trick a user into running code under elevated privileges. Often there are multiple steps to an attack.
  2. Even if you have caught every possible injection possibility in your user interface, you cannot guarantee that every call to this API will be made only from your UI for all eternity. You may open up the API to the public or you may subcontract writing a mobile application that calls this API or you may hire a new programmer who doesn't know better.

The point is that you need to check security at every level of your application. And part of checking security is to not trust your inputs.

A far better approach than concatenating strings to form a SQL statement is to create parameter instances; set the value of each parameter; and add these parameters to a Parameters collection.

The code below shows how to do this.

string lastName = "Adams";
string sql = "Select * from dbo.Customer where LastName = @LastName";
string connString = ConfigurationManager.ConnectionStrings["LocalConn"].ConnectionString;
using (var conn = new SqlConnection(connString))
{
    conn.Open();
    var cmd = conn.CreateCommand();
    cmd.CommandText = sql;
    SqlParameter lnParam = cmd.CreateParameter();
    lnParam.ParameterName = "@LastName";
    lnParam.Value = lastName;
    cmd.Parameters.Add(lnParam);
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine("Good Name: {0} {1}", reader["FirstName"], reader["LastName"]);
    }
    Console.WriteLine();

Pass an unexpected parameter here and it will no t be executed on the end of the query because SQL Server is expecting a parameter for a specific use.

The same pattern works if I want to pass in a dynamic string of SQL. Passing Parameter instances is more secure than concatenating SQL and passing that string to SQL Server.

Below is a console application that uses the vulnerable string concatenation method to call SQL Server via ADO.NET

using System;
using System.Configuration;
using System.Data.SqlClient;

namespace PassingSql_WrongWay
{
    class Program
    {
        static void Main(string[] args)
        {
            CallSqlQuery();
            CallStoredProc();
            Console.ReadLine();
        }

        private static void CallSqlQuery()
        {
            string lastName = "'Adams'";
            //string lastName = "Adams';DROP TABLE dbo.ExtraTable;--";
            string sql = "Select * from dbo.Customer where LastName = '" + lastName + "'";
            string connString = ConfigurationManager.ConnectionStrings["LocalConn"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.CommandText = sql;
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("Bad Name: {0} {1}", reader["FirstName"], reader["LastName"]);
                }
            }
            Console.WriteLine();
        }

        private static void CallStoredProc()
        {
            string firstName = "James";
            string sql = "EXEC GetCustomersByFirstName '" + firstName + "'";
            string connString = ConfigurationManager.ConnectionStrings["LocalConn"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.CommandText = sql;
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("Bad Name: {0} {1}", reader["FirstName"], reader["LastName"]);
                }
                Console.WriteLine();
            }
        }
    }
}

Below is a similar console app, using the more secure parameters pattern

using System;
using System.Configuration;
using System.Data.SqlClient;

namespace PassingSql_RightWay
{
    class Program
    {
        static void Main(string[] args)
        {
            CallSqlQuery();
            CallStoredProc();
            Console.ReadLine();
        }

        private static void CallSqlQuery()
        {
            string lastName = "Adams";
            //string lastName = "Adams;DROP TABLE dbo.ExtraTable;--";
            string sql = "Select * from dbo.Customer where LastName = @LastName";
            string connString = ConfigurationManager.ConnectionStrings["LocalConn"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.CommandText = sql;
                SqlParameter lnParam = cmd.CreateParameter();
                lnParam.ParameterName = "@LastName";
                lnParam.Value = lastName;
                cmd.Parameters.Add(lnParam);
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("Good Name: {0} {1}", reader["FirstName"], reader["LastName"]);
                }
                Console.WriteLine();
            }
        }

        private static void CallStoredProc()
        {
            string firstName = "James";
            string storedProcName = "GetCustomersByFirstName";
            string connString = ConfigurationManager.ConnectionStrings["LocalConn"].ConnectionString;
            using (var conn = new SqlConnection(connString))
            {
                conn.Open();
                var cmd = conn.CreateCommand();
                cmd.CommandText = storedProcName;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                SqlParameter lnParam = cmd.CreateParameter();
                lnParam.ParameterName = "@FirstName";
                lnParam.Value = firstName;
                cmd.Parameters.Add(lnParam);
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("Good Name: {0} {1}", reader["FirstName"], reader["LastName"]);
                }
                Console.WriteLine();
            }
        }
    }
}

If you wish to use the above code, create a new database named TestData and run the following SQL DDL to create the database objects.

USE [TestData]
GO

/****** Object:  Table [dbo].[ExtraTable]    
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExtraTable](
    [foo] [nchar](10) NULL,
    [bar] [nchar](10) NULL
) ON [PRIMARY]
GO

/****** Object:  Table [dbo].[Customer]    
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [nvarchar](50) NULL,
    [LastName] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO

INSERT INTO dbo.Customer (FirstName, LastName) VALUES ('George', 'Washington') 
GO 
INSERT INTO dbo.Customer (FirstName, LastName) VALUES ('John', 'Adams') 
GO 
INSERT INTO dbo.Customer (FirstName, LastName) VALUES ('Thomas', 'Jefferson') 
GO 
INSERT INTO dbo.Customer (FirstName, LastName) VALUES ('James', 'Madison') 
GO 
INSERT INTO dbo.Customer (FirstName, LastName) VALUES ('James', 'Monroe') 
GO 
INSERT INTO dbo.Customer (FirstName, LastName) VALUES ('John Quincy', 'Adams') 
GO 

/****** Object:  StoredProcedure [dbo].[GetCustomersByFirstName]   
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetCustomersByFirstName]
    @FirstName NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
            Id, 
            FirstName, 
            LastName
        FROM dbo.Customer
        WHERE FirstName = @FirstName
        ORDER BY Id
END
GO

With a little bit of thought and a few lines of code, you can significantly reduce the risk of SQL injection in your ADO.NET code.

.Net | C# | SQL Server
Friday, April 13, 2012 12:13:00 AM (GMT Daylight Time, UTC+01:00)
# Monday, April 9, 2012
Monday, April 9, 2012 3:03:00 PM (GMT Daylight Time, UTC+01:00)
# Monday, February 28, 2011
Monday, February 28, 2011 6:15:00 PM (GMT Standard Time, UTC+00:00)
# Monday, January 31, 2011
# Monday, September 13, 2010

At the June 2010 Great Lakes Area .Net User Group meeting, Microsoft Regional Director Bill Wagner shows off many of the new features of C# 4.0

Here is that presentation captured on video.

C# | Video
Monday, September 13, 2010 3:48:14 AM (GMT Daylight Time, UTC+01:00)
# Thursday, May 13, 2010

The var keyword was introduced in C# 3.0 and is used to declare a new variable.

The var keyword looks suspiciously like the variant keyword from Visual Basic 6. However, unlike variant, var is used to specify a strongly-typed variable. The type of the variable is inferred by the value initially assigned to that variable. As a result, whenever we use var to declare a variable, we must assign a value to the variable on the same line. So

var myString = "Hello";

is valid, but

var myString;

is not.

As mentioned earlier, the type of a variable is inferred from the value assigned to it, so in the line

var myString = "Hello";

is equivalent to

string myString = "Hello";

and

var myNum = 99;

is equivalent to

int myNum = 99;

The compiler is smart enough to recognize that "Hello" is a string and 99 is an integer and type the variable appropriately. This type checking is done at compile time, so the following code is invalid and will not compile

var x = 99;
x = "Hello";

because x is an integer, it is not possible to assign a string to it and the compiler knows this.

The var keyword is also smart enough to infer data types from the return types of functions. For example, if I have a function that returns an int and I assign the results of that function to a variable declared with the var keyword, that variable will be defined as an int. Here is a sample

static int AddNumbers(int x, int y)
{
return x + y;
}
var sum = AddNumbers(2,3);

The variable sum is an int because AddNumbers returns an int.

Earlier this year, following a user group presentation and someone noticed my use of the var keyword in my demos. The appropriateness of var became a Twitter debate and the subject of at least one blog post.

As long as I follow the rules, the compiler doesn't care whether I declare a variable using var or the explicit data type. So when do I use var? I use var when I think it will improve readability.

Consider the following 2 (equivalent) lines of code

Line 1: Customer cust = new Customer();
Line 2: var cust = new Customer();

Both lines are the same as far as the compiler is concerned. But the second line of code is more concise and easy to read. I have communicated the same information in a shorter command and with no loss of information. It should be obvious to anyone reading the second line that the variable cust contains a Customer object. In this case, I would declare the variable with the 'var' keyword because it is more readable.

The last example may not seem like there is much difference in readability between the two lines, but check out the following two equivalent lines

Line1: Dictionary<int, string> dict = new Dictionary<int, string>();
Line2: var dict = new Dictionary<int, string>();

Clearly, Line2 is more readable than Line1 in this case.

Now consider the following (equivalent) lines of code

Line 1: Customer cust = RetrievePrimaryCustomer();
Line 2: var cust = RetrievePrimaryCustomer();

Both lines are the same as far as the compiler is concerned. But I can't be sure, just from looking at the declaration, what data type is returned by the RetrievePrimaryCustomer method. The compiler knows the type, but I need to go through one or more manual steps to figure it out. In this case, the first option is more readable because it provides to anyone reading my code more information about the variable.

So my rule for using var is simple:

If the data type is obvious to anyone reading my code, use the var keyword; Otherwise explicitly specify the data type.

The var keyword is a useful shortcut that can help make your code more readable.

C#
Thursday, May 13, 2010 12:42:27 PM (GMT Daylight Time, UTC+01:00)
# Monday, January 18, 2010

Episode 64

In this interview, author and developer Bill Wagner discusses the dynamic features in the upcoming C# 4.0.

Monday, January 18, 2010 3:03:20 PM (GMT Standard Time, UTC+00:00)
# Sunday, September 13, 2009

Back To Basics

The yield return and yield break keywords are shortcuts introduced in C# 3.0. They are designed to assist you in a method that returns IEnumerable <T>.
Often such methods consist of the following steps

  1. Create an empty IEnumerable set.
  2. Loop through some data (via a while, foreach or other construct)
  3. Add to the set within your loop.
  4. Exit the loop when some limit is reached.
  5. Return the set.

A sample of such code is shown below.

public IEnumerable<Int32> GetOddNumbers_Old(Int32 maxNumber)
{
    List<Int32> oddSet = new List<Int32>();
    int num = 0;
    while (true)
    {
        System.Threading.Thread.Sleep(1000);
        num++;
        if (num % 2 == 1)
        {
            oddSet.Add (num);
        }
        if (num >= maxNumber)
        {
            break;
        }
    }

    return oddSet;
}

The new yield keywords allow you to shorten your code to only the following steps

  1. Loop through some data
  2. yield return within the loop
  3. yield break if a limit is reached before the loop is complete

That’s it. There is no need to explicitly create or return your IEnumerable set.

The yield return statement appends a value to the IEnumerable set. The yield break statement exits any looping construct to prevent more items being added to the return set. If you omit yield break, the loop exits as it normally would.

The difference between using the yield return and simply returning a set is subtle. Returning a set at the end of the method returns the entire set at once. The client must wait until the method is complete before it can use any values in the return set. Each time the yield return statement executes, the client has access to another element in the set. Essentially the set trickles back a little at a time. This can provide a gain in performance or perceived performance if you have a large set to return.

Here is a sample that returns the same results as above, using yield return and yield break.

public IEnumerable<Int32> GetOddNumbers_Yield(Int32 maxNumber)
{
    int num = 0;
    while (true)
    {
System.Threading.Thread.Sleep(1000); num++; if (num % 2 == 1) { yield return num; } if (num >= maxNumber) { yield break; } } }

If we call the two methods above, we will get the same results but they will return in slightly different ways. I added the System.Threading.Thread.Sleep(1000); line to help demonstrate this. That line simply pauses execution for 1 second each time the loop executes.

Assume the above two methods are in a class named MyMethods.  The following code will call each.

Console.WriteLine("Get Odd Numbers using old way:");
MyMethods mm = new MyMethods();
IEnumerable<Int32> oddNumbers2 = mm.GetOddNumbers_Old(11);
foreach (Int32 n in oddNumbers2)
{
    Console.WriteLine(n);
}

Console.WriteLine();


Console.WriteLine("Get Odd Numbers using new YIELD keyword:");
IEnumerable<Int32> oddNumbers1 = mm.GetOddNumbers_Old(11);
foreach (Int32 n in oddNumbers1)
{
    Console.WriteLine(n);
}

Console.ReadLine();

The above code produces the following output

Get Odd Numbers using old way:
1
3
5
7
9
11

Get Odd Numbers using new YIELD keyword:
1
3
5
7
9
11

Notice that both methods return the same data. However, if you watch the code as it runs, you will notice the first method waits 12 seconds, then immediately outputs all odd numbers; while the second method outputs a number every 2 seconds. Each method returns the same values and each takes the same amount of time, but the second method uses yield return, so the client is able to output a bit of data each time a yield return executes.

There are a few restrictions to using the yield keywords

  • These keywords cannot appear in blocks marked "unsafe"
  • These keywords cannot appear in a method with ref or out parameters
  • The yield return statement is not allowed inside a try-catch block, although it may be located inside a try-finally block.
  • A yield break statement may not be located inside a finally block.

You can download this sample code at DemoYield.zip (45.06 KB)


Mike Wood contributed to this article.

Sunday, September 13, 2009 2:44:07 PM (GMT Daylight Time, UTC+01:00)
# Saturday, September 12, 2009

Back To Basics

Prior to C# 3.0, we had two common ways to initialize the public properties of an object.

  1. We could use the default constructor to instantiate the object; then, use a separate line of code to assign a value to each property. (Listing 1)
  2. We could create a constructor that accepts an argument for each property; and write code in this constructor to assign to each public property the value passed in for each corresponding argument. (Listing 2 and Listing 3)

The first method is quite verbose and requires a lot of code for complex objects.

Listing 1:

Customer cust1 = new Customer();
cust1.CustomerID = 1;
cust1.FirstName = "George";
cust1.LastName = "Washington";
cust1.StreetAddress = "111 A St";
cust1.City = "Aville";
cust1.State = "MI";
cust1.ZipCode = "10001";

Listing 2:

class Customer
{
    public Int32 CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public Customer
        (
        Int32 customerID,
        string firstName,
        string lastName,
        string streetAddress,
        string city,
        string state,
        string zipCode
        )
    {
        CustomerID = customerID;
        FirstName = firstName;
        LastName = lastName;
        StreetAddress = streetAddress;
        City = city;
        State = state;
        ZipCode = zipCode;
    }
}

Listing 3:

Customer cust2 = new Customer
    (
    2,
    "John",
    "Adams",
    "222 B Ave",
    "Beetown",
    "MI",
    "20002"
    );

The second method is more elegant, but assumes we always want to initialize every single public property at object instantiation. Of course, we could create multiple constructors to accommodate times when we only want to initialize certain variables but this can get complex in a hurry when our class has a lot of public properties.

Beginning with C# 3.0, we can now initialize public properties in the same line of that instantiates an object; and we can do so without creating a new constructor. We use object initializers to do this. 

Using object initializers we can still use the default constructor (or any public constructor we want); but we can set public properties by appending the property assignments within a set of curly braces at the end of the object initializer, as shown in listing 4.

Listing 4:

Customer cust4 = new Customer() 
            {   CustomerID = 4, 
                FirstName = "James", 
                LastName = "Monroe" 
            };

This new C# feature is known as object initializers. This method gives us a great deal of flexibility. At the time we instantiate an object, we can decide which properties to initialize. And we can do so without creating a plethora of constructors for the object or return to the verbose way of assigning property values after an object's instantiation.

Object initializers are most useful when you instantiate a class in many different places throughtout an application.

Download this code to view and run a simple application that uses object initializers DemoObjectInitializers.zip (24.92 KB)
Saturday, September 12, 2009 2:10:03 PM (GMT Daylight Time, UTC+01:00)
# Friday, September 11, 2009

Back To Basics

Automatic properties were introduced in C# 3.0 as a convenience to developers.

C# and Visual Basic .Net provide two ways for a class to maintain state: Fields and Properties.

A field is a simply a public variable defined inside a class, such as in the following example

public string foo;

A property looks much like a field to the outside world, but exposes two methods – a “getter” to allow you to retrieve the value of the property and a “setter” to allow you to assign a value to the property. The following sample demonstrates how to implement a read-write property in C#.

private string _firstName;
public string FirstName
{
    get
    {
        return _firstName;
    }
    set
    {
        _firstName = value;
    }
}

This is a common use of property getters and setters – to assign and retrieve the value from a private variable. Because there is no extra logic in these methods, similar functionality could be achieved using a field, but I prefer to use properties in case I decide later to add some validations or calculations to the setter or getter. Making a change like that to a property will not break the class signature, forcing a recompile of dependent objects.

But this is a lot of typing for such simple functionality. So much in fact that Visual Studio 2005 provided a right-click accelerator to type much of it for you.

Beginning with C# 3.0, automatic properties provide a shorthand notation for this functionality.  Simply provide the scope, the type and the name of the property, followed by “{get; set; }” and the framework will automatically create a private variable for you and provide code to save and retrieve to/from that private variable. This is all done behind the scenes for us so we don’t need to write any of this code.  Below is a sample of the code we need to write for a public property.

public string FirstName { get; set; }

To make a property read-only, simply omit the "set" keyword. To make it write-only, omit the "get" keyword. Below is syntax for the same property if I wanted it to be read-only.

public string FirstName { get; }

The only disadvantage to automatic properties is that the rest of the code in our class no longer has access to the private variables create by the framework. Even from within the same class, we must go through the public property in order to get or set the private variable.

This is a small price to pay for the amount of code we are saving.

Automatic properties not only require less typing, they are far easier to read when your class has a bunch of properties. Which of the following easier to read?

public string FirstName { get; set; }
public string LastName { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }

or

private string _firstName;
public string FirstName
{
    get
    {
        return _firstName;
    }
    set
    {
        _firstName = value;
    }
}

private string _lastName;
public string LastName
{
    get
    {
        return _lastName;
    }
    set
    {
        _lastName = value;
    }
}

private string _streetAddress;
public string StreetAddress
{
    get
    {
        return _streetAddress;
    }
    set
    {
        _streetAddress = value;
    }
}

private string _city;
public string City
{
    get
    {
        return _city;
    }
    set
    {
        _city = value;
    }
}

private string _state;
public string State
{
    get
    {
        return _state;
    }
    set
    {
        _state = value;
    }
}

private string _zip;
public string Zip
{
    get
    {
        return _zip;
    }
    set
    {
        _zip = value;
    }
}

I think you’ll agree that it is far easier to read and understand the more terse syntax of the first example.  And code that is easier to understand is easier to maintain.

Because both syntax versions compile to the same Intermediate Language, I recommend always using the newer Automatic Properties syntax when you create properties that do nothing more than save and retrieve state.

Download the following sample code to see automatic properties in action: DemoAutomaticProperties.zip (26.83 KB)
Friday, September 11, 2009 1:17:17 PM (GMT Daylight Time, UTC+01:00)
# Saturday, September 5, 2009

Back To Basics

Extensions methods are a new feature of C# 3.0 and they are easier to use than they first appear.

An extension method is a method that is external to an existing class but appears as if it were a method on that class.

The rules for creating an extension method are simple.

  1. Create a static method
  2. The first parameter of the static method should be the type of the class you wish to extend
  3. Precede the parameter type of this first parameter with the "this" keyword.
  4. Call the method as if it were a method of the class. Omit the first parameter.

An example should clarify this. Assume we have a class Customer with properties FirstName and LastName as shown below

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

We can create a new static class MyExtensions with a static method GetFullName that returns the formatted first and last name of the customer. We do so with the following code

   public static class MyExtensions
    {
        public static string GetFullName(this Customer cust)
        {
            string custName = cust.FirstName + " " + cust.LastName;
            return custName.Trim();
        }
    }

Notice the parameter with the "this" keyword. That parameter format tells the compiler that this is an extension method and that it should extend the Customer class. As long as MyExtensions is in the same namespace or in a namespace available to our code (via the "using" statement), we can call this new extension method with the following code

Customer cust 
    = new Customer 
         { FirstName = "David", 
           LastName = "Giard" 
         };
string fName = cust.GetFullName();
Console.WriteLine(fName);

The code above outputs:

   David Giard

As you can see in the above code, it looks as if the GetFullName method is part of the Customer class.

We can add parameters to our extension methods as we would to any other method. The first parameter (with the “this” keyword) is always used to specify the class we are extending. All other parameters act just like normal parameters. The following extension method accepts a parameter “salutation”.

public static string GetGreeting(this Customer cust, string salutation)
{
    string custName = cust.FirstName + " " + cust.LastName;
    custName = custName.Trim();
    return salutation + “ “ + custName + ":"; 
}

Although the extension method has two parameters, we only need to pass the second parameter when calling it, as shown

Customer cust = new Customer { FirstName = "David", LastName = "Giard" };
string greeting = cust.GetGreeting("Dear");
Console.WriteLine(greeting);

The code above outputs:

   Dear David Giard:

In our examples, we were adding extension methods to a class that we just created. Of course, in this case, it would have been simpler to just modify the original class.  But extension methods are more useful if you are working with someone else’s class and modifying the source code is not an option. Extension methods often offer a simpler solution than inheriting from an existing class.

The real power of extension methods comes from the fact that you can even add methods to sealed classes. It is difficult to add functionality to a sealed class because we cannot inherit from it. Change the Customer class to sealed and re-run the code to prove that it still works.

public sealed class Customer

Here is the all code in the above sample

using System;

namespace TestExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer { FirstName = "David", LastName = "Giard" };

            string fn = cust.GetFullName();
            Console.WriteLine(fn);

            string greeting = cust.GetGreeting("Dear");
            Console.WriteLine(greeting);

            Console.ReadLine();

        }
    }


    public sealed class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }


    public static class MyExtensions
    {
        public static string GetFullName(this Customer cust)
        {
            string n = cust.FirstName + " " + cust.LastName;
            return n.Trim();
        }

        public static string GetGreeting(this Customer cust, string salutation)
        {
            string custName = cust.FirstName + " " + cust.LastName;
            custName = custName.Trim();
            return salutation + " " + custName + ":"; 
        }
    }

}

You can download the sample code at TestExtensionMethods.zip (24.26 KB)

 

Saturday, September 5, 2009 2:52:43 AM (GMT Daylight Time, UTC+01:00)