ADMIN

The Newtonsoft.Json library contains a number of tools for working with JSON from within your .NET application.

New ASP.NET applications created in Visual Studio already contain a reference to the Newtonsoft.Json library. But if you want to add the library to a different project type or if you want to update the version installed by default with an ASP.NET application, you can right-click your project in the Visual Studio Solution Explorer and select "Manage NuGet Package..." and search for Newtonsoft.Json. Select the "Newtonsoft.Json" package (Fig 1) and click either "Install" or "Update".

Newtonsoft is very good at serializing .NET objects into JSON objects.

One feature that I find useful is its ability to rename attributes in my classes. For example, if I have a class named "SocialSecurityNumber" in my C# class and the client consuming my JSON object expects that same property to be named "ssn", I can make this transformation declaratively by adding the JsonProperty attribute to the class property, as shown in Listing 1.

[JsonProperty("ssn")]

public string SocialSecurityNumber { get; set; }

By convention, C# developers tend to name public properties with mixed case (capitalize the first letter of each word); while JavaScript and JSON developers tend to name properties using Camel casing (capitalize the first letter of each word, except the first word). In the past, I used the JsonProperty attribute to accomplish this, renaming every variable that would be serialized to JSON, as in the following example:

[JsonProperty("firstName")]

publicstring FirstName { get; set; }

[JsonProperty("lastName")]

publicstring LastName { get; set; }

For projects with many objects and many properties, this can be a tedious task. Fortunately, I recently learned a shortcut.

ASP.NET contains a Formatters class that controls how items are formatted and Newtonsoft.Json can tap into this. The following code, when run at the start of your application, converts all properties to Camel-Case as you transform them to JSON.

I added this code to the Register method of the WebApiConfig class in my ASP.NET MVC project, so that it is run when the application starts up, before any serialization is done.

Another useful setting is to add carriage returns and line feeds to the JSON that is created. This has the disadvantage of making your JSON slightly larger; but it makes it much easier for human beings to read, which can be very useful during debugging. This is accomplished with the following line:

The Null Coalescing operator has been around since the early days of C#. Yet it still remains unused by most developers. I'm guessing this is because they are unaware of it, rather than deliberately rejecting it.

The operator is simply a double question mark ("??"). Some people refer to it as the "Elvis Operator" because, if you squint your eyes just right, the curvy parts of each question mark resemble the waves of singer Elvis Presley's famous pompadour-style hair while the dots resemble his eyes.

The King

The operator takes 2 arguments and returns a single value. If the first argument is not null, the null coalescing operator returns that argument; otherwise, it returns the second argument.

This is clarified by the following 2 examples

String a = "first";

String b = "second";

String c = a ?? b;

Console.WriteLine(c);

// Output: first

String d = null;

String e = "second";

String f = d ?? e;

Console.WriteLine(f);

// Output: second

Of course, the code snippet

String f = d ?? e;

is identical to the following:

String f = "";

if (a == null)

f = e;

else

f = d;

The arguments must be nullable and the examples above work because "string" is nullable by default. You may need to use the nullable version of other data types as in the example below that features integers.

int? g = 1;

int? h = 2;

int? i = g ?? h;

Console.WriteLine(i);

// Output: 1

int? j = null;

int? k = 2;

int? l = j ?? k;

Console.WriteLine(l);

// Output: 2

You can even use this operator with custom classes and objects, as in the following example.

public class Person

{

public string FirstName { get; set; }

public string LastName { get; set; }

}

class Program

{

static void Main(string[] args)

{

Person m = null;

Person n = new Person() { FirstName = "David", LastName = "Giard" };

Person o = m ?? n;

Console.WriteLine(o.FirstName);

Console.ReadLine();

}

}

So why bother using the null coalescing operator? Why not continue to use the longer "if/else" version if the results are the same. There are a couple reasons to use the null coalescing operator: Converting Nullable properties to Non-Nullable properties and Ease of Reading.

Converting to Non-Nullable Properties

The Null Coalescing operator is useful for converting a nullable property into a non-nullable property.

For example, the following example, returns "N/A" for the FavoriteColor property if none is assigned. This assures that FavoriteColor will never return Null.

private string _favoriteColor;

public string FavoriteColor

{

get { return _favoriteColor ?? "N/A"; }

set { _favoriteColor = value; }

}

Ease of reading

The single line of a code allowed by the Null coalescing operator tends to be much more terse and more clear than the multiple lines of an IF/ELSE construct. This is particularly true if you have a lot of similar checks in a row. Given the following examples, it is much easier to read the first than the second. Once you are comfortable with the syntax, it is easy to see what the code is doing. Even though you are almost certainly familiar with the syntax of an "if" construct, you still must pause to step through the code and think about what the second example is doing.

Some will argue that the Null Coalescing operator is more difficult to read because so many are unfamiliar with it. This seems a weak argument to me, given how long it has been in the language and how useful it is. As a developer, we owe it to ourselves to become familiar with the core structures of our language of choice and this includes the operators.

C# contains a single operator that handles conditional logic in a single statement. It is generally written as "?:" (making it difficult to find using a search engine) and it is often referred to as the conditional operator, although the official documentation does not give it this name.

I write about it here, not because it is new or extra cool, but because I believe it is underused by C# developers.

The syntax is: condition ? ValueIfTrue : ValueIfFalse;

where

condition is a boolean expression to test

ValueIfTrue is the value to return if the condition expression is true

ValueIfFalse is the value to return if the condition expression is false

An example should clarify this:

1:int x;

2:string y;

3: x = 1;

4: y = x >= 0 ? "Positive" : "Negative";

5: Console.WriteLine(y);

6:

7: x = -1;

8: y = x >= 0 ? "Positive" : "Negative";

9: Console.WriteLine(y);

The output of this code snippet is:

Positive
Negative

The expression

x >= 0 ? "Positive" : "Negative";

returns the string "Positive" if x is at least 0 and "Negative" if x is less than 0.

Of course the same expression could be written like the following:

1: x = 1;

2:if (x >= 0)

3: {

4: y = "Positive";

5:}

6:else

7: {

8: y = "Negative";

9:}

10: Console.WriteLine(y);

11:

12:x = -1;

13:if (x >;= 0)

14: {

15: y = "Positive";

16:}

17:else

18: {

19: y = "Negative";

20:}

21: Console.WriteLine(y);

But this requires more typing (which provides more changes for errors); and (more importantly), it takes more time to read, so it cannot be digested as quickly by someone reviewing the code later. Of course, I'm assuming that the code reviewer is familiar with this operator, but I don't think that's an unreasonable expectation, given that it has been in the C# language over 10 years.

Many developers are not familiar with ?: operator, but they should be. It simplifies code and makes it easier to read.

Here is the full code of a console application demonstrating these concepts:

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

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

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

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.

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.

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:

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.

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:

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.

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.

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

Your web code runs under a context with insufficient privileges to drop a table; and

You are validating all user inputs to ensure a user cannot enter anything bad.

There are problems with this reasoning.

A clever hacker can sometimes trick a user into running code under elevated privileges. Often there are multiple steps to an attack.

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 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

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.

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

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.

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

Loop through some data

yield return within the loop

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.

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.

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.

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

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)

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.

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.

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.

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

publicstring 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#.

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.

publicstring 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.

publicstring 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?

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.

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

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”.

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.