C# 3.0 – Part II :: Object & Collection Initializers

7 11 2008

In part I, the feature discussed was auto-implemented properties. Here we’ll make use of the classes defined in part I to demonstrate object initializers.

Notice that no constructor was declared in the classes defined. The compiler creates a default constructor (empty constructor), but this isn’t new in 3.0. What is new, is a way to set the properties of the object as it is initialized.

// declare and initialize an instance of the Address class
Address homeAddress = new Address()
{
// set the properties using C# 3.0 object initializer feature
Street = "123 Some Street",
City = "Newport Beach",
State = "CA",
PostalCode = "92626",
AddressType = AddressType.Home
};

We can then use the homeAddress instance to instantiate a Person object, also defined in part I.

Person person = new Person()
{
ID = 1,
FirstName = "John",
LastName = "Doe",
Addresses = new List<Address>(){ homeAddress }
};

Notice that we’ve initialized the collection of addresses of the person instance, as the object itself is initialized. Collection Initializers is also a new feature of C# 3.0. Instead of calling the Add method of a collection, we can simply list the objects, similar to that of arrays.

We can even combine the initialization of objects and collections into one big block of code.

Person person = new Person()
{
ID = 1,
FirstName = "John",
LastName = "Doe",
Addresses = new List<Address>()
{
new Address()
{
Street = "123 Some Street",
City = "Newport Beach",
State = "CA",
PostalCode = "92626",
AddressType = AddressType.Home
}}};

Probably the most interesting to me are the collection initializers. I’ve often have had to create lookup dictionaries for one reason or another. Typically the process is declare and instantiate the dictionary and then populate with lookup values.

Dictionary<int, string> numberLookup = new Dictionary()<int, string>();
numberLookup.Add(1, "one");
numberLookup.Add(2, "two");

Instead, we can instantiate like so:

Dictionary<int, string> numberLookup = new Dictionary()<int, string>()
{
{ 1, "one" },
{ 2, "two" }};





C# 3.0 – Part I :: Auto-Implemented Properties

7 11 2008

I’ve been playing around with VS 2008 and looking at some of the new features implemented for the next version of C#. Here’s some features that I found to be time saving.

Auto-Implemented Properties
Encapsulating properties has always been a pain, even with code snippets. C# 3.0 allows the declaration of backing fields with auto implemented properties, as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sample
{
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Address> Addresses { get; set; }
}

public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public AddressType AddressType { get; set; }
}

public enum PhoneType
{
Home,
Work,
Fax,
Mobile
}

public enum AddressType
{
Home,
Work
}
}

I added a an enumeration and List of addresses to play with collections later. A caveat to the auto-implemented properties is that you can’t have complex get or set accessors and mutators. You’re probably thinking what’s the point? You can get the same thing with making the backing fields themselves public. I agree that the use is limited; however, there is that option to make the mutator private in order to make the property read only. The feature isn’t ground breaking but it does save some time when you’re making some simple container class.





Validating Embeded Digital Signatures

31 10 2008

I had a recent project that had a feature of being able to update itself as determined by a web service. The service provided information as to the URI of the files to be updated. The client component grabs the files, in zip format, downloads it and extracts and either replaces files in the application or executes it; replacement and/or execution determined by the meta-data from the service. As a precaution, we wanted to ensure that the files executed really are from us. To verify, we implemented a rule that only digitally signed dll’s and exe’s would be allowed to run by our updater.

The challenge was being able to verify the digital signatures. Initially I was using the System.Security.Cryptography.X509Certificates.X509Certificate class to validate the certificate. The idea is to validate the certificate chain to the root CA and verify the publisher.

What I ran into was that the .NET classes only successfully validated .NET assemblies, but not all. The final solution was to create a wrapper class that calls the WinVerifyTrust method of wintrust.dll.
Read the rest of this entry »





LINQ: Except and Intersect

16 10 2007

As of this writing, I’m currently involved in developing a production appliction making use of LINQ, Orcas Beta 2 (Visual Studio 2008), ADO.NET and the .NET 3.5 framework.  I just wanted to put down my recent experience using Except, which is akin to the not in operation in SQL statements.

The task is simple enough.  I have a database containing class/course schedules and a many-to-many relationship table called Registrations that has a uniqueness constraint across two foreign keys, one to the Course table and the other to the Registrant table.  I wanted to be able to present two sets of collections.  One, given a particular course, be able to get the collection of registered Registrants; the second, is a collection of Registrants that are not registered for the course.

In SQL, we’d have something like this:

-- Get registered Registrants
SELECT r.* FROM Registrant AS r JOIN Registrations AS reg ON r.registrantId = reg.registrantId
WHERE reg.courseId = @courseId;

-- Registrants not registered for the course
SELECT * FROM Registrant registrantId NOT IN
(SELECT r.registrantId FROM Registrant AS r JOIN Registrations AS reg ON r.registrantId = reg.registrantId
WHERE reg.courseId = @courseId);

-- Alternate query without using NOT IN
SELECT r.* FROM Registrant AS r LEFT JOIN Registrations AS reg ON r.registrantId = reg.registrantId AND reg.registrantId IS NULL;

With LINQ, the one point I found with Except and Intercept is that the comparison is done at the object level, unlike in SQL where we include/exclude based on the value of a particular property/column.


var regList = (from r1 in Registrant
select r1).Except(from r2 in Registrant
join reg in Registrations on r2.registrantId equals reg.registrantId
where reg.courseId == (new Guid(courseId))
select r2);
/*
Note that in SQL we just needed to specify the registrantId's we want to exclude while with LINQ we need to compare apples to apples.
*/





Getting the client UTC Offset with ASP.NET

21 09 2007

I have a database where date and time are stored in GMT/UTC to have a uniform time zone reference.  The problem is that it isn’t very user friendly to display the GMT/UTC values.  In addition, we wanted to get the offset without having the user log in and get preference settings.

 Our approach was to get the client offset with JavaScript and added a function that is fired when the page is loaded.


<script>
function GetClientUtcOffset()
{
    var d = new Date();
    document.forms[0]["UtcOffset"].value
        = d.getTimezoneOffset();
}
</script>

Note that the method getTimezoneOffset() returns the unit value in minutes.  Within the body of the page we call the function during the onload event of the body and used a hidden field for the UTC Offset value that we’ll be getting that we’ll be accessing in our code behind.

<body onload="GetClientUtcOffset();">
  <form id="form1" runat="server">
      <input type="hidden" runat="server" id="UtcOffset" />
  .
  .
  .

In our code behind, we got the value and put it in a cookie. The alternative was to put it in a session.


protected void Page_Load(object sender, EventArgs e)
{
  if (IsPostBack && Request.Cookies["utcOffset"] == null)
  {
      HttpCookie utcOffsetCookie =
        new HttpCookie("utcOffset", "0");
      if (!string.IsNullOrEmpty(UtcOffset.Value))
          utcOffsetCookie.Value = UtcOffset.Value;
      Response.Cookies.Add(utcOffsetCookie);
  }
}

At this point, you can retrieve the cookie from any other page and adjust your time values accordingly. Only caveat to this is that the client must hit the page first and then send a post back to get the value of their offset. In our case, we added the code on our login page since we didn’t allow annonymous access to the site.

Read the rest of this entry »