Sean's Blog

My Development Blog

  Home  |   Contact  |   Syndication    |   Login
  17 Posts | 0 Stories | 96 Comments | 0 Trackbacks

News

Twitter












Archives

.NET Development

Thursday, December 13, 2012 #

Although I've been a Mac user for a couple of years, I recently switched over fulltime to a Mac as my primary development machine at work. There are a lot of things I can get away with on a personal machine that I can't on a work machine (e.g., walking away from my laptop with the screen unlocked).

I was shocked how long it took for me to piece all of the little bits from various Google searches to create a simple keyboard shortcut that allows users to quickly lock their screen, so I thought I would compile it in one [hopefully] simple post.

The following shell command will return the current user to the login screen.

/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

There may be easier/better ways, but I decided to place this command in an Automator script, so launch Finder and open the Automator application.


Automator
Choose the Service type at the launch screen:

Automator Launch Screen
Toward the top-center of the window, look for the drown down box next to Service receives and select no input from the drop down list.


Empty Automator Dialog

Under Actions -> Utilities, drag the Run Shell Script task to the right pane.

Paste the following command into task window: /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

Completed Task
Save the script as Lock Screen and quit Automator.

Back in Finder, go to Applications -> System Preferences -> Keyboard and select the Keyboard Shortcuts tab after the application launches.


Keyboard
On the left-hand side, select Services

Scroll to the General category from the right pane and select the Lock Screen service to select a keyboard shortcut.

Simply click the add shortcut button to assign a shortcut. I went with Command + Shift + L, but do whatever makes most sense to you.


Keyboard Shortcut

And that's it! Hope this helps somebody.

Sunday, March 4, 2012 #

For those of you that missed it, Rob Conery offered a challenge a couple nights ago to build an API for Tekpub. In response to this, a few different developers took the opportunity to propose their solution to the requirements. One of those developers, John Sheehan, offered his solution entitled, Don’t build the best REST API, build the best HTTP API and tweeted that the title might be a bit linkbaitish. I understood the point he was trying to make and I think he did a fine job. Building an API should be about building the best API for the job. If you're following an architectural pattern like REST for the sake of following an architectural pattern, I suggest you stop and consider what it is you want your end results to be. For this, I can't argue with John because I agree with him. Having said that, I felt John missed an opportunity to demonstrate HATEOAS principles in a simple post that could have cleared some confusion among newcomers to REST that don't understand what hypermedia really is. John disagreed with me --it's ok, I don't hate him for it. The purpose of his post was to demonstrate how one could build the best API based on Rob specific requirements.

The purpose of this post is to pick up on what I feel is an otherwise great post. Credit goes entirely to John for the original API and JSON results returned from his proposed API.

Wikipedia says, "Hypermedia is a computer-based information retrieval system that enables a user to gain or provide access to texts, audio and video recordings, photographs and computer graphics related to a particular subject." I feel that's rather confusing and not very informative. I'd rather say, "Hypermedia is the embedding of links within responses, which will indicate to a consumer the available resources and state transitions", but even that's confusing. Let's try to explain this with some actual data.

Below is a JSON snip (including a tiny bit of API documentation) from John's blog:

// Request
GET /api/productions/PRCS

// Response
Content-Type: text/json
{
    "id" : "PRRD",
    "name" : "RavenDB",
    "author" : "Oren Eini",
    "last_updated" : 1356976799,
    "episode_count" : 5,
    "channels" : [ "Databases" ],
    "episodes" : [
        {
            "id" : "EP100",
            "title" : "Why You Should Care About RavenDB",
            "duration" : 1200,
            "release_date" : 1356976799
        },
        {
            "id" : "EP101",
            "title" : "Understanding Document Names",
            "duration" : 300,
            "release_date" : 1356976799
        },
        ... truncated ...
    ]
}

As was previously stated, I believe this is a good start, but I wanted to show what this result could have looked like if we added some hypermedia bits to it.

The first thing that should jump out to you if you wanted to consume this data is it requires some working knowledge of the API in order to get additional details about the data. For example, what if you wanted to get an episode document by its unique identifier? You could go to the documentation and hope somebody remembered to add details about where to perform this action. Maybe you'd get lucky and find that information, but what if it moves in the future? The point is, you shouldn't have to worry about these details. The API should be robust and flexible enough to allow consumers to follow "links", much the same as hyperlinks, to the detail it is requesting rather than relying on hard-coded strings to URIs where the resources should be.

Following is an update to the JSON that includes some potential hypermedia bits:

// Request
GET /api/productions/PRCS

// Response
Content-Type: text/json
{
    "id" : "PRRD",
    "author" : {
        "name": "RavenDB",
        "url": "/api/authors/Oren%20Eini"
    },
    "last_updated" : 1356976799,
    "episode_count" : 5,
    "channels" : [ { "url": "/api/channels/Databases" } ],
    "episodes" : [
        {
            "id" : { "url": "/api/episodes/EP100" },
            "title" : "Why You Should Care About RavenDB",
            "duration" : 1200,
            "release_date" : 1356976799
        },
        {
            "id" : { "url": "/api/episodes/EP101" },
            "title" : "Understanding Document Names",
            "duration" : 300,
            "release_date" : 1356976799
        },
        ... truncated ...
    ]
}

And's pretty much it (I made bold the parts I updated)! As you can see, the data provides a URI from which to locate additional details about specific resource types. If those URIs change, the API developer(s) can simply update the URIs with their new location and any consumers can be blissfully unaware of any updates (from a programmatic perspective) because the data explains where to find the additional details.

Often times, without much effort, application developers can improve the future-proof-ness of their API by following simple guidelines. My intent of this post was to demonstrate that with little effort, we are able to add hypermedia bits to a JSON result and extend a simple Web API to do just that. Hopefully, somebody finds it useful.

Tuesday, September 13, 2011 #

If you've ever needed to convert a Nullable<T> type to 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); }

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.


Sunday, December 6, 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 3, 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" %>