web 2.0

Using PowerShell to Publish a NuGet Package

At my employer we have a local NuGet server to host all of our internal packages. Occasionally, I’ll be working on a project and realize that I need to tweak something in one of  my NuGet packages. Initially, I got into the habit of  opening up a second instance of Visual Studio, making the necessary changes and using the NuGet web interface to re-upload the package. I quickly realized that manually uploading the package was too time consuming. Therefore, I started looking for a way to automate the process instead. Eventually that led me to the PowerShell script you see below.

$nugetServer = "https://<your nuget server here>"
$apiKey = "<your api key here>"
$packageName = "<your package name here>"

$latestRelease = nuget list $packageName
$version = $latestRelease.split(" ")[1];

$versionTokens = $version.split(".")
$buildNumber = [System.Double]::Parse($versionTokens[$versionTokens.Count -1]) 
$versionTokens[$versionTokens.Count -1] = $buildNumber +1
$newVersion = [string]::join('.', $versionTokens)
echo $newVersion

get-childitem | where {$_.extension -eq ".nupkg"} | foreach ($_) {remove-item $_.fullname}
nuget pack -Version $newVersion
$package = get-childitem | where {$_.extension -eq ".nupkg"}
nuget push -Source $nugetServer $package $apiKey


The script needs a few variables defined in order for it to run. The first variable ($nugetServer) is the URL of the NuGet Server. The second variable ($apiKey) is your personal API key. You can get your API key by logging into your NuGet Server with a browser. After you log in, click on your username in the upper right hand corner. This will take you to your account page. On the bottom of the “My Account” page there is a box which you can click on to make your API key visible. Finally the last variable ($packageName) is the name of the package you are uploading. This can be easily acquired by looking at your project properties and copying the Assembly name from the Application tab.

Depending on how your machine is configured you may have the option to Run with PowerShell on your context menu. If not, you can take a look at this blog post in order to configure it manually. Alternatively you can use the following command instead.

powershell.exe "<path to the script>\publish.ps1"


If you have any problems running the script then please refer to the following TechNet article or send me a question and I’ll be glad to help.

Tags:

dotNet | Tech

jQuery + CSS3 Media Queries = Dynamic UX

I have been working on a project where I render an HTML table to display some information about a project. When the table is displayed on a wide monitor I can comfortably fit about 10-15 columns. However, when viewing the same page on a screen with less real-estate things get crowded. Most people would probably address this problem by creating a mobile version of the site. In many cases this is the proper solution if you really want to tailor the user experience for the device. However, in my case I just wanted to toggle the visibility of some of the columns in the table based on the screen size and I really did not want to get into the hassle of maintaining a separate mobile interface. Therefore I came up with a solution based on jQuery and CSS Media Queries. Below is a screenshot that shows how columns are being toggled on and off based on the width of the browser.

css_media_queries

So let me start this tutorial by showing you the markup that I used to generate the HTML table. If you are not a MVC/Razor developer then this part of the tutorial may not be useful to you. However I wanted to include this extra step because the Razor grid’s Html Helper has some limitations which I addressed with jQuery. 

@{ 
    var grid = new WebGrid( 
        canPage: true,
        rowsPerPage: Model.PagingInfo.PageSize,       
        ajaxUpdateContainerId: "container",
        ajaxUpdateCallback: "gridLoaded"
    );
    
    grid.Bind(Model.Data, rowCount: Model.PagingInfo.TotalItems, autoSortAndPage: false);    
       
    <div id="container">
        @grid.GetHtml(
            tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            htmlAttributes: new { id = "grid", page = Model.PagingInfo.PageNumber },
            columns: grid.Columns(
                grid.Column("Title", "Title"),
                grid.Column("StartDate", "Start"),
                grid.Column("EndDate", "End"),
                grid.Column("PercentComplete", "%"),

                grid.Column("Status", "Status", style: "xtra"),
                grid.Column("Notes", "Notes", style: "xtra"),
                grid.Column("MetaData", "MetaData", style: "xtra"),
                grid.Column("MoreMetaData1", "More MetaData", style: "xtra"),
                grid.Column("EvenMoreMetaData1", "Even More MetaData", style: "xtra")
            )
        )
    </div>     
}

As you can see, the razor grid allows you to specify styles for each column (TD), so I added the style class "xtra" to the fields that I want to hide when the screen with is 800 pixels or less. Unfortunately the (TH) columns can not be styled directly with the Html Helper. Therefore I needed a way to apply the “xtra” class to the headers that correspond with each column. This was very easy to do with jQuery:

$("#grid tbody tr:first td.xtra").each(function (index,td) {                
    $('#grid thead th').eq($(td).index()).addClass("xtra");                
});

 

The snippet above uses a selector to get at the first row of the table. It then loops through all of the columns in that row that have the "xtra" style applied to it. Then for each column it finds the corresponding header and adds the "xtra" style to it. This is important because if we did not apply the style to the headers then our CSS below would only hide the columns and not the headers.

Now let's move on to adding the CSS media queries to our style sheet. If you are unfamiliar with media queries then here is a quick definition that I found on the W3C site:

Media queries extend the functionality of media types by allowing more precise labeling of style sheets. A media query consists of a media type and zero or more expressions that check for the conditions of particular media features. Among the media features that can be used in media queries are ‘width’, ‘height’, and ‘color’. By using media queries, presentations can be tailored to a specific range of output devices without changing the content itself.

So in simple terms, we can have sections in our style sheet that only apply when the screen is a certain size. In my particular case I decided to hide the columns  with the “xtra” style applied to them whenever the screen width is less than 800 pixels:

@media screen and (max-width:800px) { 
  .webGrid .xtra { display: none;}  
  .webGrid .xtra > th { display: none;}    
}

Keep in mind that you can also do things like adjust fonts, remove background images and hide navigation panels. This can help make the user experience better when dealing with smaller screens. Although this trick is not a replacement for a well crafted mobile interface it certainly gives you a quick way to make your site look good on smaller screens.

Happy Coding!

INotifyPropertyChanged with Compile Time Checking

Update: An anonymous reader left a great tip! ".NET 4.5 gives you the new Caller Info attributes, which would remove the need to actually pass in the name of the property, if you're raising the notification from withing the property itself." For more details read this blog post.

Once you start doing WPF MVVM development you will quickly grow tired of implementing the INotifyPropertyChanged interface. So in order to preserve my sanity, I create a base class which implements the INotifyPropertyChanged interface. The first version of my class was defined as:

public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

This is about as basic as an implementation of INotifyPropertyChanged can get. To use it, you just implement the class and call RaisePropertyChanged. Here is an example:

public class MyViewModel : NotifyPropertyChangedBase
{
    private string _name;
    public string Name {
      get{ return _name; }
      set{ 
       _name = value;
       RaisePropertyChanged("Name");
      }
    }
}

After using this version of the code for a couple of days I quickly realized that using a lambda to get the property name would be less error prone than using a string. So in version 2 of the code, I added lambda support.

By the way, the ExtractPropertyName method you see below, was copied verbatim from the Prism project. Prism and MVVM Light Toolkit both take care of wrapping the INotifyPropertyChanged interface.  I personally do not use either framework because I feel that they are both too bloated for my purposes. After a bit of contemplation, I ended up building my own MVVM framework, which I have packaged up and placed on my private NuGet server. However, if you are new to .NET or MVVM then I would suggest starting with a framework first. In any case, here is the updated code:

protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
    var propertyName = ExtractPropertyName(propertyExpression);
    RaisePropertyChanged(propertyName);
}

protected string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression) {
    if (propertyExpression == null) {
        throw new ArgumentNullException("propertyExpression");
    }

    var memberExpression = propertyExpression.Body as MemberExpression;
    if (memberExpression == null) {
        throw new ArgumentException("The expression is not a member access expression.", "propertyExpression");
    }

    var property = memberExpression.Member as PropertyInfo;
    if (property == null) {
        throw new ArgumentException("The member access expression does not access a property.", "propertyExpression");
    }

    if (!property.DeclaringType.IsAssignableFrom(this.GetType())) {
        throw new ArgumentException("The referenced property belongs to a different type.", "propertyExpression");
    }

    var getMethod = property.GetGetMethod(true);
    if (getMethod == null) {
        // this shouldn't happen - the expression would reject the property before reaching this far
        throw new ArgumentException("The referenced property does not have a get method.", "propertyExpression");
    }

    if (getMethod.IsStatic) {
        throw new ArgumentException("The referenced property is a static property.", "propertyExpression");
    }

    return memberExpression.Member.Name;
}        

With the lambda version of RaisePropertyChanged in place, I can now get compile time checking. Compile time checking is great if you have fat fingers or if you do a lot of refactoring. Let’s take a look at our updated ViewModel:

public class MyViewModel : NotifyPropertyChangedBase
{
    private string _name;
    public string Name {
      get{ return _name; }
      set{ 
       _name = value;
       RaisePropertyChanged(() => Name);
      }
    }
}

I also added an overloaded version of the RaisePropertyChanged method so I could raise multiple properties using a single method call. This is useful when you have two of more related properties. 

protected virtual void RaisePropertyChanged(params string[] propertyNames) {
    foreach( var property in propertyNames ) {
        RaisePropertyChanged(property);
    }
} 

Unfortunately, I could not figure out how to make an overloaded method that takes multiple lambdas. Because the type that represents "T" needs to be different for each expression I struggled to find any syntactical sugar that would make it work. To clarify the problem, I made an overloaded version of the method that takes two lambda expressions. You will notice that T and X are different types. T may be an integer and X may be an observable collection. 

protected void RaisePropertyChanged<T,X>(Expression<Func<T>> one, Expression<Func<X>> two ) 
    RaisePropertyChanged(one);            
    RaisePropertyChanged(two);            
}

With this method you could use the following syntax. Of course, with my sample method above you are limited to two parameters only:

RaisePropertyChanged( () => CountryId, () => States );

If you have a solution for making an overloaded method with params and lambdas then please leave a comment.

Moving on...The classic example of two related properties are Country and State. When you change the value of the country drop down, you want the corresponding states or provinces to appear. Here is an example:

public class AddressViewModel : NotifyPropertyChangedBase
{
     private Address Model { get; private set; }
     
     public AddressViewModel( Address model )
     {
         Model = model;
     }

     public int Country
     {
         get { return Model.CountryId; }
         set
         {
             Model.CountryId = value;
             RaisePropertyChanged( () => CountryId);
             RaisePropertyChanged( () => States);
         }
     }

     public ObservableCollection<Country> Countries {
         ...
     }

     public ObservableCollection<State> States
     {
         ...
     } 

     public int StateId
     {
         ...
     }
}

To summarize, if you find yourself implementing INotifyPropertyChanged a lot then I would highly recommend moving that functionality into a base class. In addition, using the lambda version of the RaisePropertyChanged event can provide you with compile time checking which is always a great thing to have!

Tags: ,

MVVM | Tech | WPF

EF Code First - Tips and Tricks

These days I do all of my development work with EF code first. One of the cool things about EF is its ability to drop and recreate the database when the models change. This is great when you are trying to associate your source code with a particular revision of the database schema. However, dropping and recreating a database on a production or staging environment can have some serious repercussions. Therefore, I like to put some safeguards in place to make sure that this only happens under the right conditions. 

Please keep in mind that the newest version of EF has migration support! So you can alter the database instead of dropping and recreating it. However, if you use the DropRecreateDatabaseIfModelChanges feature of EF then you may find the following tip useful.

Safeguarding from an Accidental Drop/Recreate

In wrap the code that sets up the EF Context initializer with the following helper method which determines whether or not I am in development mode. For me, development mode means I have the debugger attached or I am working with a local SQL instance:

static bool InDevelopmentMode {
    get {    
        if (System.Diagnostics.Debugger.IsAttached) return true;
        if (Environment.UserName.ToUpper().Contains("<YOUR ID HERE>")) return true;    

        var connectionString = ConfigurationManager.ConnectionStrings["MyDbContext"].ConnectionString;
        var csb = new SqlConnectionStringBuilder(connectionString);
        return csb.DataSource.Equals("."); //shorthand for localhost                
    }
}

Now we can leverage the method to conditionally execute the DB initializer:

if (InDevelopmentMode) {
    Database.SetInitializer(new MyContextInitializer()); //Register the EF context initializer
} 

 

Disabling EF Migrations

As I mentioned earlier, the latest version of EF has migration support. By default, migrations will be enabled. If you want to disable it you can do the following:

Create a Migrations Configuration class

using System.Data.Entity.Migrations;

namespace MyApp.Domain.DataContext {
    public sealed class MyContextConfiguration : DbMigrationsConfiguration<MyContext> {
        public MyContextConfiguration() {
            AutomaticMigrationsEnabled = false;
        }
    }
}

Bootstrap it!

For web apps this would add this code to the Global.asax.cs and in WPF apps you would do this in App.xaml.cs...

new DbMigrator(new MSRContextConfiguration()); //migrations are disabled   

 

Happy Coding!

Tags:

dotNet | Tech

Using Self Referencing Tables With Entity Framework

Since EF was released I have been a fan. However, every once in a while I’ll run into a table design situation that I am not sure how to handle with EF. This week, I needed to setup a self-referencing table in order to store some hierarchical data. A self referencing table is a table where the primary key on the table is also defined as a foreign key. Sounds a little confusing right?

Let’s clarify the solution with an example. Let’s say I am building an application where I have a list of categories and subcategories. One of my top level categories is “Programming Languages” and under programming languages I have to subcategories which are “C#” and “Java”. In order to store this data I can use a single table with the following structure:

The actual data would look like this:

image

Just to clarify, a top level category will have a null value for the ParentId field. For all child categories the ParentId field is used as to represent its parent’s primary key value. As a programmer you may want to think about the ParentId field as a pointer. To complete the example lets take a look at the SQL used to create the table.

CREATE TABLE [dbo].[Categories] (
    [CategoryId] [int] IDENTITY(1,1) NOT NULL,    
    [Name] [nvarchar](255) NOT NULL,    
    [ParentId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
    [CategoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Categories]  WITH CHECK ADD  CONSTRAINT [Category_Parent] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Categories] ([CategoryId])
GO

ALTER TABLE [dbo].[Categories] CHECK CONSTRAINT [Category_Parent]
GO

Upon examining the SQL, you should have noticed that the CategoryId is the primary key on the table and the ParentId field is a foreign key which points back to the CategoryId field. Since we have a key referencing a another key on the same table we can classify this this as a self-referencing table. Now that we fully understand what a self-referencing table is, we can move forward to the Entity Framework code. To get started we first need to create a simple C# object to represent the Category table. Of course, keep in mind that if you are using EF Code first you do not need to create the table or database ahead of time. I only showed the table first because I wanted to better illustrate what a self referencing table is.

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
}

So far the Category class is very simple. However, we really want to add a few more properties in order to make this class useful. For example, if you are a child category you really want to be able to use dot notation to get the name of the parent category (e.g. subCategory.Parent.Name). Using EF, we will create a virtual property named Parent. By making the property virtual we are letting EF know that when this property is accessed we want to load some data. Based on your configuration settings and the code you use to retrieve your data (whether or not you used DbSet.Include), EF will lazy load or eager load this data.

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public virtual Category Parent { get; set; }
}

Finally, we also want a property called Children so we can use dot notation to enumerate over the child categories. Once again, here is the modified class:

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Children { get; set; }
}

The final step is to let EF know how these properties are related to one another. This can be done using EF's fluent API. If you are new to EF and are unaware of the fluent API then you may want to read this article first.

public class CommodityCategoryMap : EntityTypeConfiguration<Category> {
    public CommodityCategoryMap() {
        HasKey(x => x.CategoryId);

        Property(x => x.CategoryId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(x => x.Name)
            .IsRequired()
            .HasMaxLength(255);

        HasOptional(x => x.Parent)
            .WithMany(x => x.Children)
            .HasForeignKey(x => x.ParentId)
            .WillCascadeOnDelete(false);
    }
}

Hopefully you paid careful attention to the last section of code where we state the a Category has an optional Parent property. In database speak, this simply means that the ParentID field is nullable. The code also states that if a Category object can have zero or many children. In order to specify that a record is a child, we  leverage the ParentId field to hold the primary key value of the parent record. As I mentioned earlier, if you are a programmer its easier to think of the ParentId field as a pointer. Finally, I disabled the cascade on delete option. This step is optional and probably based on your own personal preferences. If you enable cascade on delete and you delete a category that has 100 children then you will effectively remove 101 records. For whatever reason this scares me a little bit. Perhaps, my short career as a DBA caused me to not trust people with large volume delete statements. However, you may decide differently depending on your circumstances.

Hopefully, this short EF tutorial will help you if you are working through a scenario where you need to capture and manipulate hierarchical data. If you have any questions please leave a comment.

Tags:

dotNet | SQL | Tech