Sean's Blog

My Development Blog

  Home  |   Contact  |   Syndication    |   Login
  14 Posts | 0 Stories | 60 Comments | 0 Trackbacks

News

Twitter












Archives

.NET Development

Wednesday, January 27, 2010 #

Some colleagues and I are in the process of revising/introducing some Configuration Management best-practices at the company we work for. In particular, we are introducing a new concurrent source control system (Subversion) and we have had a couple of healthy debates come up in regard to what should/shouldn’t get committed to source control.

On one side, we have those with a more purist belief that only the following should be committed to source control:

  1. Anything necessary to build the project (e.g., source code and any 3rd party libraries that your project makes use of)
  2. Related objects, such as images or flash files that are required to deploy a website

In another we camp, we have those that believe in using the source control system for more than just source:

  1. Anything necessary to build the project (e.g., source code and any 3rd party libraries that your project makes use of)
  2. Related objects, such as images or flash files that are required to deploy a website
  3. The compiled assemblies at the end of each build
  4. Related documents (e.g., project timeline, requirements, etc.)

In regard to the first camp, nobody disagrees with the value of having the ability to grab components related to a specific build, at any point in time. For example, if a client asks for release 1.7.9.132, it’s imperative we have the ability to grab that release quickly and that it be identical to the original release (for example, not compiled under a new version of the compiler). Their argument is that committing the compiled assemblies into source control will clutter the repository without adding value. Their preference is to maintain a separate location on a file server, which is designated to storing versioned releases in a hierarchal fashion, on the file system.

The above mentioned concept could easily be implemented by a manual process or a build process that is run on a Continuous Integration server at the time the source is committed to the trunk; however, the less purist camp believes in providing a “one stop shop” for everything.

Another concern of the purist camp is that concurrent version control systems do not lend themselves nicely to working with binary documents (e.g., Word files). For example, to ensure that no two people work on the same binary document, at the same time, document authors must first lock the file before making edits. While this could work, another author may attempt to edit the file at the same time, not realizing the file has been locked (often, an svn commit is required before any subsequent users realize that the file has been locked). This will cause any subsequent user with having to “shelve” their changes and manually merge them, at another time. It is believed that a document control server, such as SharePoint, would better suit document versioning.

For those that have gone down this path, could you please share your words of wisdom?


Sunday, December 06, 2009 #

For copying and pasting source from Visual Studio into my blog posts, I have found CopySourceAsHtml to be very helpful. For those that are not familiar with it, CopySourceAsHtml integrates nicely with Visual Studio by adding a context menu item, which allows you to easily copy source code from your source files. All of the HTML formatting is handled by the add in.

As far as I’m aware, there is currently no official release of CopySourceAsHtml for Visual Studio 2010. The good news, however, is that I was able to modify the associated .Addin file to make it work. This is not an official “workaround” from the CopySourceAsHtml developers; I just happened to find that it worked. Thus far, I have not encountered any issues with using CopySourceAsHtml within Visual Studio 2010 (at the time of this posting, I’m using the Visual Studio 2010 beta 2 release).

To integrate CopySourceAsHtml with Visual Studio 2010, please follow the instructions, below:

  1. Locate the CopySourceAsHtml.AddIn file (by default, it’s located in, C:\Program Files\J.T. Leigh & Associates\CopySourceAsHtml)
  2. Copy and paste this file into the Addin directory for Visual Studio 2010 (locate this by selecting Tools –> Options –> Add-in/Macros Security)
  3. Edit the XML in the .Addin file, changing the text within the <Version> elements to 10.0.
  4. Change the text in the <Description> element so that it references Visual Studio 2010 rather than 2008.
  5. Restart Visual Studio 2010 if it was already open
  6. Check Tools –> Add-in Manager and verify that the CopySourceAsHtml add in is checked to enable it.

Add-in Dialog

Your updated XML should look like this:

<?xml version="1.0" encoding="utf-8" standalone="no"?>

<Extensibility xmlns="http://schemas.microsoft.com/AutomationExtensibility">

  <HostApplication>

    <Name>Microsoft Visual Studio Macros</Name>

    <Version>10.0</Version>

  </HostApplication>

  <HostApplication>

    <Name>Microsoft Visual Studio</Name>

    <Version>10.0</Version>

  </HostApplication>

  <Addin>

    <FriendlyName>CopySourceAsHtml</FriendlyName>

    <Description>Adds support to Microsoft Visual Studio 2010 for copying source code, syntax highlighting, and line numbers as HTML.</Description>

    <Assembly>JTLeigh.Tools.Development.CopySourceAsHtml, Version=3.0.3215.1, Culture=neutral, PublicKeyToken=bb2a58bdc03d2e14, processorArchitecture=MSIL</Assembly>

    <FullClassName>JTLeigh.Tools.Development.CopySourceAsHtml.Connect</FullClassName>

    <LoadBehavior>1</LoadBehavior>

    <CommandPreload>0</CommandPreload>

    <CommandLineSafe>0</CommandLineSafe>

  </Addin>

</Extensibility>

Update: For anybody that wants to help test, I have submitted this update as a patch to the CopySourceAsHtml project.


Thursday, December 03, 2009 #

With .NET 4.0 right around the corner, I thought it would be cool to download Visual Studio 2010 beta 2 and start playing around with the next release of Entity Framework.

The initial release of Entity Framework came with a great deal of criticism. To make matters worse, there was a large uproar when it was rumored that Microsoft would be abandoning LINQ to SQL, in favor of Entity Framework. This was because, at the time, many developers felt Entity Framework was an inferior technology to LINQ to SQL. To set things right, Microsoft proactively moved forward with improving Entity Framework, in time for the 4.0 release of the .NET Framework. This is good news because my initial impressions, so far, have been nothing but positive.

One of the concerns that many developers had with the initial Entity Framework release was the difficulty in building a repository. Having said that, the first thing I did upon opening Visual Studio 2010 was to build one. Soon into my test project, I noticed some interesting things. The first thing that really caught my attention was the IObjectSet interface, which provides the ability to modify data objects. Every bit as important, the ObjectContext class now has a generic CreateObjectSet<TEntity>() method. As soon as I saw these two things, I realized the potential, not only for creating a repository, but for creating a generic repository. That’s right, one generic class that can perform all of the CRUD operations for your entire application.

To start out, I built a generic interface for our repository. Notice that with the exception of the two SaveChanges() methods, every method either takes an object of type T as a parameter, or returns an object (either a collection or a single entity), also of type T.

public interface IRepository<T> : IDisposable where T : class

{

    IQueryable<T> Fetch();

    IEnumerable<T> GetAll();

    IEnumerable<T> Find(Func<T, bool> predicate);

    T Single(Func<T, bool> predicate);

    T First(Func<T, bool> predicate);

    void Add(T entity);

    void Delete(T entity);

    void Attach(T entity);

    void SaveChanges();

    void SaveChanges(SaveOptions options);

}

 

Moving onward, implementing the interface was a breeze. Take note of the constructor and the call to CreateObjectSet() off of the global _context variable. This is the magic that makes the generic repository possible.

 

/// <summary>

/// A generic repository for working with data in the database

/// </summary>

/// <typeparam name="T">A POCO that represents an Entity Framework entity</typeparam>

public class DataRepository<T> : IRepository<T> where T : class

{

 

    /// <summary>

    /// The context object for the database

    /// </summary>

    private ObjectContext _context;

 

    /// <summary>

    /// The IObjectSet that represents the current entity.

    /// </summary>

    private IObjectSet<T> _objectSet;

 

    /// <summary>

    /// Initializes a new instance of the DataRepository class

    /// </summary>

    public DataRepository()

        : this(new AdventureWorksEntities())

    {

    }

 

    /// <summary>

    /// Initializes a new instance of the DataRepository class

    /// </summary>

    /// <param name="context">The Entity Framework ObjectContext</param>

    public DataRepository(ObjectContext context)

    {

        _context = context;

        _objectSet = _context.CreateObjectSet<T>();

    }

 

    /// <summary>

    /// Gets all records as an IQueryable

    /// </summary>

    /// <returns>An IQueryable object containing the results of the query</returns>

    public IQueryable<T> Fetch()

    {

        return _objectSet;

    }

 

    /// <summary>

    /// Gets all records as an IEnumberable

    /// </summary>

    /// <returns>An IEnumberable object containing the results of the query</returns>

    public IEnumerable<T> GetAll()

    {

        return GetQuery().AsEnumerable();

    }

 

    /// <summary>

    /// Finds a record with the specified criteria

    /// </summary>

    /// <param name="predicate">Criteria to match on</param>

    /// <returns>A collection containing the results of the query</returns>

    public IEnumerable<T> Find(Func<T, bool> predicate)

    {

        return _objectSet.Where<T>(predicate);

    }

 

    /// <summary>

    /// Gets a single record by the specified criteria (usually the unique identifier)

    /// </summary>

    /// <param name="predicate">Criteria to match on</param>

    /// <returns>A single record that matches the specified criteria</returns>

    public T Single(Func<T, bool> predicate)

    {

        return _objectSet.Single<T>(predicate);

    }

 

    /// <summary>

    /// The first record matching the specified criteria

    /// </summary>

    /// <param name="predicate">Criteria to match on</param>

    /// <returns>A single record containing the first record matching the specified criteria</returns>

    public T First(Func<T, bool> predicate)

    {

        return _objectSet.First<T>(predicate);

    }

 

    /// <summary>

    /// Deletes the specified entitiy

    /// </summary>

    /// <param name="entity">Entity to delete</param>

    /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>

    public void Delete(T entity)

    {

        if (entity == null)

        {

            throw new ArgumentNullException("entity");

        }

 

        _objectSet.DeleteObject(entity);

    }

 

    /// <summary>

    /// Deletes records matching the specified criteria

    /// </summary>

    /// <param name="predicate">Criteria to match on</param>

    public void Delete(Func<T, bool> predicate)

    {

        IEnumerable<T> records = from x in _objectSet.Where<T>(predicate) select x;

 

        foreach (T record in records)

        {

            _objectSet.DeleteObject(record);

        }

    }

 

    /// <summary>

    /// Adds the specified entity

    /// </summary>

    /// <param name="entity">Entity to add</param>

    /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>

    public void Add(T entity)

    {

        if (entity == null)

        {

            throw new ArgumentNullException("entity");

        }

 

        _objectSet.AddObject(entity);

    }

 

    /// <summary>

    /// Attaches the specified entity

    /// </summary>

    /// <param name="entity">Entity to attach</param>

    public void Attach(T entity)

    {

        _objectSet.Attach(entity);

    }

 

    /// <summary>

    /// Saves all context changes

    /// </summary>

    public void SaveChanges()

    {

        _context.SaveChanges();

    }

 

    /// <summary>

    /// Saves all context changes with the specified SaveOptions

    /// </summary>

    /// <param name="options">Options for saving the context</param>

    public void SaveChanges(SaveOptions options)

    {

        _context.SaveChanges(options);

    }

 

    /// <summary>

    /// Releases all resources used by the WarrantManagement.DataExtract.Dal.ReportDataBase

    /// </summary>

    public void Dispose()

    {

        Dispose(true);

        GC.SuppressFinalize(this);

    }

 

    /// <summary>

    /// Releases all resources used by the WarrantManagement.DataExtract.Dal.ReportDataBase

    /// </summary>

    /// <param name="disposing">A boolean value indicating whether or not to dispose managed resources</param>

    protected virtual void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (_context != null)

            {

                _context.Dispose();

                _context = null;

            }

        }

    }

}

 

To use it, you need only instantiate the generic repository of whichever entity type you wish to query. For example, using Adventure Works, you could bind to a GridView on an ASP.NET web form, with the following:

 

using (IRepository<Employee> repository = new DataRepository<Employee>())

{

    this.GridView1.DataSource = from x in repository.Fetch()

                                select new

                                {

                                    x.MaritalStatus,

                                    x.Contact.FirstName,

                                    x.Contact.LastName,

                                    x.BirthDate

                                };

    this.GridView1.DataBind();

}

 

To change the table that you wish to query, simply change the type instantiated.

 

Conclusion

Hopefully, you have gotten a little insight into the power that the new Entity Framework has to offer. I really believe that Microsoft has made great progress in this release. For those that were turned off by eariler versions, I urge you to give Entity Framework another go with the 4.0 release.


Wednesday, August 12, 2009 #

When sending emails to users of your system, it’s important that clients be able to read your messages. Even with modern technology advancements, not all email clients support HTML –some users actually prefer text messages. For this reason, it is important that we deliver content that a standard email (non-HTML) client can read. One way of doing this is by delivering a multi-part MIME message with alternate body parts –one part being a standard email, and another being an HTML message. It is then up to the email client to display the richest part that it can render.

Starting with 2.0, the .NET Framework includes an AlternateView class, exactly for this purpose. Following is the code necessary to send a multi-part MIME message containing both standard and HTML parts:

static void SendMessage()
{
    SmtpClient client = new SmtpClient("alt1.gmail-smtp-in.l.google.com");
    MailMessage message = new MailMessage();
    AlternateView plainMessage = AlternateView.CreateAlternateViewFromString("This is a plain text message.", null, "text/plain");
    AlternateView htmlMessage = AlternateView.CreateAlternateViewFromString("This is an <b>HTML</b> message.", null, "text/html");

    // Basic message properties
    message.From = new MailAddress("me@myaddress.com");
    message.To.Add("me@gmail.com");
    message.Subject = "Alternate View Test";

    // Add the alternate views to the message
    message.AlternateViews.Add(plainMessage);
    message.AlternateViews.Add(htmlMessage);

    client.Send(message);
}


Saturday, July 25, 2009 #

C# 3.0 brought with it a plethora of great additions, such as LINQ, lambda expressions and anonymous types. With the inclusion of LINQ, Microsoft decided that it was often difficult to determine the return type from a LINQ expressions. As such, they opted to include the var keyword, which is used to implicitly define a type. The type is determined by the compiler at compile time, making it strongly typed, so it is not analogous to the Visual Basic variant type. While this has some value in aiding in building LINQ expressions, I often find the use of the var keyword to be unclear (in my opinion) when used to define variables. In C# 3.0, for example, the following code is completely legit:

static void Main()
{
    var myInt = 10;
}

The code above defines an integer named myInt. While this particular example may be clear, I have found other situations where the use of the var keyword has made code less readable.

static void Main()
{
    var myEmployee = new Employee();
}

Still not terribly unclear because the type is on the same line. But we’re starting to get unclear because my eyes start at the left to determine the type. But what if the type isn’t on the same line? What if it’s the return value of some method in another class?

static void Main()
{
    var myEmployee = new Employee();
    var i = myEmployee.GetSomething(); // Unclear
}

What does the type above return? We could argue that the name GetSomethig() isn’t explicit enough. That’s a valid argument, but are all methods inherently named explicitly enough to determine the type returned? Absolutely not. As a result, I find myself having to reach for the mouse to hover over the the method to see a tooltip that I can use to make that determination. It slows me down. Is it that difficult to explicitly declare the type of your variable ahead of time? It makes maintenance and readability a lot easier.


Wednesday, October 22, 2008 #

If you're trying to impersonate a Windows identity in an Excel Services UDF, make sure to configure the Excel Service access mode to delegation, rather than the Trusted Subsystem model (default).  This can be done with the following commands:

stsadm -o set-ecssecurity -accessmodel delegation -ssp sspname
stsadm -o execadmsvcjobs
iisreset

Failing to do so could result in hours of frustration! Specifically, if you always go down the error path in the following code, this is likely the problem:

if ((wi = Thread.CurrentPrincipal.Identity as WindowsIdentity) == null)
{
throw new InvalidOperationException("An error occurred during the Impersonation process");
}

Thursday, August 21, 2008 #

This next post might be rather obvious to most of you, but I figured I wasn't the only one that didn't know how to do this.  I was recently working with a new ASP.NET MVC project and got tired of typing out the fully qualified class names.  This seems like something that would be rather common, but a quick Google search didn't turn up anything useful.  I figured that there had to be a way to import a namespace, so intellisense to the rescue, I noticed that there was an <%Import %> directive.  Sure enough, that did the trick.

<%@ Import Namespace="SubSonic" %>

Wednesday, April 23, 2008 #

I was recently working on an application that was known for throwing random exceptions at various times for no apparent reason.  Frustrated, I wrote this snippet of code to ease the tension.  I just thought I'd share it with you.

Program.cs
using System; using System.Collections.Generic; namespace RandomConsoleTests { class RandomConsoleTests { static void Main(string[] args) { ThrowRandomException(); } public static void ThrowRandomException() { throw ExceptionFactory.CreateRandomException(); } } }

ExceptionFactory.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Configuration.Provider; using System.Data; using System.IO.IsolatedStorage; using System.Net.Mail; namespace RandomConsoleTests { public static class ExceptionFactory { public static Exception CreateRandomException() { Random rand = new Random(); switch (rand.Next(0, 20)) { case 0: return new ApplicationException(); case 1: return new ProviderException(); case 2: return new SettingsPropertyIsReadOnlyException(); case 3: return new SettingsPropertyNotFoundException(); case 4: return new SettingsPropertyWrongTypeException(); case 5: return new IsolatedStorageException(); case 6: return new SmtpException(); case 7: return new SystemException(); case 8: return new AccessViolationException(); case 9: return new AppDomainUnloadedException(); case 10: return new ArgumentException(); case 11: return new ArithmeticException(); case 12: return new ArrayTypeMismatchException(); case 13: return new BadImageFormatException(); case 14: return new CannotUnloadAppDomainException(); case 15: return new KeyNotFoundException(); case 16: return new WarningException(); case 17: return new TimeoutException(); case 18: return new OutOfMemoryException(); case 19: return new DataException(); case 20: return new InvalidOperationException(); default: return new Exception(); } } } }

Thursday, April 03, 2008 #

If you install the Commerce Server starter site on a port other than port 80, you will run into a couple of issues.  The problem is that Microsoft coded the site to drop the port number.  To correct the problem, open the App_Code\SiteContext.cs file and comment out the following line of code (it's on line 247, for me):

builder.Port = -1; // Removes the port setting from the site.
Add the following line of code in its place (note, update port numbers to match your sites configuration):

builder.Port = secure ? 8443 : 8080;
UPDATE:

The User\Login.aspx.cs file also needs to be updated.  Located the following line in the OnInit() method and change the -1 to match the port number for which SSL is configured to run on your site:

builder.Port = -1; // Change this to your sites SSL port

Hope that helps...

Saturday, January 12, 2008 #

It seems to me that one of the most underused features of the C# (or Visual Basic) language is the structure.  Developers are often lead to believe that use of classes yield performance benefits.  While this is often the case, structures have their own set of advantages that, when used in the right situation, will yield important, and sometimes substantial performance benefits.  This blog post is intended to help demystify some of the confusions between structures and classes.

In their simplest form, classes and structures in C# are very similar.  In fact, often times, you may simply replace the class keyword with the struct keyword, and your classes can instantly be converted into a struct:

public class Person
{
}

public struct Person
{
}

Indeed, from the standpoint of a text editor, these two entities are identical except for the class and struct keywords.  At the system level, however, these two entities behave very differently.  As most C# developers know, the biggest difference between the two entities is that the class is a reference type, whereas the struct is a value type.  A slightly more educated C# developer would also point out that the struct is stored in the stack, whereas the class is stored in the heap.  This is an important concept to understand because it is this reason that structures have the potential for increased performance in some situations, but also one of their biggest drawbacks, in other situations.

By being stored in the stack, the runtime (CLR) can create, read, update and remove value types very quickly, with minimal overhead.  It is important to note, however, that the stack is limited.  In fact, you should never create a value type with an instance size greater than 128 bits (16 bytes).

In contrast to value types, reference types store a pointer in the stack that points to an object found in the heap.  By storing reference types in the heap, the amount of memory is limited to the available physical RAM found in the computer that the code is executing on (there is, of course, the concept of swapping, which increases the theoretical limit of available memory; however, that goes beyond the scope of this article).  Following is a simple example of objects types stored in the heap (please excuse the artwork, I'm certainly not a designer):

Memory

From looking at this simple diagram, it should  be obvious that  accessing something from the stack can be faster than accessing something from the heap.  This is because the processor has direct access to something stored on the stack, whereas it has to do a lookup and then 'fetch" of anything found on the heap.  There is actually more to it, but for the sake of simplicity, I'll leave it at that.

Another important concept to realize is that, because they are stored in the stack, value types create a second copy of the value when they are copied.  That is, the stack will contain two or more instances of the value each time it is copied.  Reference types, on the other hand, are not copied.  Instead, only the pointer is copied.  In other words, when you copy a reference type, the object itself is not copied, only the pointer is copied.  This obviously has its benefits; especially for large objects.

So then, the important question is, when should you use a structure versus a class?  Following is a simple list of requirements that should help you decide when to use a structure.
  • Represents a single value
  • Will not be changed after its creation
  • Will not be cast to a reference type (for more information, read up on boxing and unboxing)
  • Has an instance size less than 128 bits (16 bytes)
If your entity does not meet those requirements, your best choice is going to be the use of a class.

For more information on the differences between classes and structures, be sure to check out Microsoft's page.

Update:

Rick Minerich has posted a terrific series of articles related to memory management. I highly recommend reading all three, but for those of you that would like to jump straight ahead to managing the size of the stack, please jump to part 3:

Part 1 – Basic Housekeeping
Part 2 – Improving Performance Through Stack Allocation
Part 3 – Increasing the Size of your Stack