Sean's Blog

My Development Blog

  Home  |   Contact  |   Syndication    |   Login
  16 Posts | 0 Stories | 93 Comments | 0 Trackbacks

News

Twitter












Archives

.NET Development

Tuesday, September 13, 2011 #

If you've ever needed to convert a Nullable<T> type to a its default, non-nullable value when its nullable value is null, here's a handy extension method to help you out.

public static T NullableToValue<T>(this T? value) where T : struct { return value ?? default(T); }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Tuesday, April 26, 2011 #

I attended MIX11 a couple of weeks ago and had the opportunity to meet up with Glen Block at one of the open source festival booths where he was demoing MEF (Managed Extensibility Framework). During his demonstration, he showed a very cool (in my opinion) feature of MEF that allows you to export a concrete class that may or may not implement some predefined interface. This is done through the magic of the C# 4.0 dynamic keyword, which allows the compiler to bypass static type checking during compilation.

Take the following code as an example:

[Export("Message")] public class MessagePart { public MessagePart() { Message = "I can haz dynamic"; } public string Message { get; set; } }

Notice the above code does not implement any particular interface. How would we import it and pass it as a parameter to, for example, another classes constructor? As previously mentioned, through the magic of the C# 4.0 dynamic feature

[Export] public class MainViewModel { [ImportingConstructor] public MainViewModel([Import("Message")] dynamic messagePart) { Message = messagePart.Message; } public string Message { get; set; } }

And that’s it! Notice the messagePart parameter is dynamic. MEF still imports the concrete type that exports the contract (in this case with the name Message). As with all dynamic types in C#, the static type checking is done at runtime.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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?

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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);
}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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");
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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" %>
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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(); } } } }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati