Archives for : C#

A new job and moving to Austin!

I haven’t posted in a bit because I took some vacation, officiated my sister’s wedding and wanted a bit of a break.  Now, just as I wanted to get back to posting again on a regular basis I’ve taken an offer in Austin, TX.  Recently we’ve had a lot of family either move out to Texas or begin planning on doing so.  As such, we made our own plans to head out to Texas.  Given that the blog is now hosted on my Azure site that’s linked to my MSDN subscription, I’m not sure what is going to happen during the transition from my current MSDN subscription to my new one.  I do have a full back-up of all files and posts (except this one) so at a minimum I’ll need to move over to another host while I get my new MSDN subscription set up.  This can be problematic as sometimes the DNS takes a bit to transfer.  Basically what I’m saying is that over the next month the site might go down but it should only be for a few days at the most.  Once I get set up in my new position I’ll be back to posting regularly once a week.

Thanks to all of you.  See you soon!

Brian

Previous Post: MVC and Azure for the MVVM/WPF Dev, Part 1 – Getting Started

Up next in this series is covering the model, view and controller objects that were created in the tutorial, Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to an Azure Web Site.

Getting There

How does all the MVC views and view controller work? Well, let’s start with getting to the index view from the main page. The tutorial originally told you to replace the home with a call to the Cm controller it had you create. As I mentioned previously it seemed odd to call it Cm and so I called mine ContactsController. And rather then replacing the main link to the home page I added a new link. My “/Views/Shared/_Layout.cshtml” ends up looking like:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("ExperimentalProducts", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("Contact Manager", "Index", "Contacts")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

This makes it so I now have a “Contact Manager” link in my nav bar. We need to understand what is going on here. The @Html object is an MVC helper object to set up links and make your life easier when working with html. We’re creating a link that we want to perform some sort of action. In our case we want to go to the “ContactsController” and tell it we want it to perform an Index action. If you look at the third line in the navbar you can see that we have added a link that looks like:

<li>@Html.ActionLink("Contact Manager", "Index", "Contacts")</li>

The first parameter is the string to display for the link. The second parameter is the action we want to perform, in our case we want to display the index. The third parameter is the controller we want to call. Note that part of the name, Controller, is missing. I don’t know what would happen if you created a name without the Controller part appended.

MVC then takes care of wiring everything up so that when you click on the link we end up at “/Views/Contacts/Index.cshtml”.

The Model

The Contact model is straightforward and working with models is the same as if you were using models in MVVM. We’re using Entity Framework on the back-end and it all works almost the same as when I’ve used it in desktop applications. You’ll find the DbContext in “/Models/IdentityModels.cs”.

There are really only two differences from how I use the DbContext with desktop applications. The first is that when working with with desktop applications I tend to extend the DbContext to take a connection string. The auto-generated constructor is empty but will call base with connection string name “DefaultConnection”. I often like to expose this so I can allow my users to dynamically change the connection string dependent on the needs of the application. There may very well be the same need here but I don’t see the need in the near future. The second difference is that we’re obviously using a web.config instead of an app.config. I’m going to assume that you understand the differences between the web.config in the root of the project and an app.config. I will be covering “Views/Web.config” separately in a different post.

The Controller

Before I go into the views we need to take a look at the controller. But before we even do that we need to understand HTTP request methods. This is how the browser makes a request to the server. We’re primarily concerned with two methods, GET and POST. Generally GET is performed by clicking a link and POST is performed by submitting a form via a button at the bottom of the page. You don’t have to perform the request methods in this manner but it’s behavior users will expect.

It is important to take to heart, as a matter of convention, the purpose of GET and POST. GET should only be for getting data. POST, conversely, should be for making changes to data. This is incredibly important and stems from lessons learned in my java servlet/asp.net days. Like most conventions in software development, they are needed in order to make maintenance and the continued operation of an application (whether desktop or web) easier and with a minimal amount of defects.

[Authorize]
public class ContactsController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Contacts
    public ActionResult Index()
    {
        return View(db.Contacts.ToList());
    }

    // GET: Contacts/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // GET: Contacts/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Contacts/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ContactId,Name,Address,City,State,Zip,Email")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            db.Contacts.Add(contact);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(contact);
    }

    // GET: Contacts/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // POST: Contacts/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ContactId,Name,Address,City,State,Zip,Email")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            db.Entry(contact).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(contact);
    }

    // GET: Contacts/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // POST: Contacts/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Contact contact = db.Contacts.Find(id);
        db.Contacts.Remove(contact);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

If you’re comparing along with your own code from the tutorial you’ll see that there is one difference. I added a “[Authorize]” tag at the top of my class. This makes it so that the only way to enter this controller is if the user is authorized. You can take this attribute a step further and specify specific roles that may access the controller. There are a few things to take note of:

  1. Each method ties to an action, which in turn ties to a view
  2. Each method returns an ActionResult
  3. Each method defaults to a get request
  4. You must explicitly identify post requests with the attribute, “HttpPost”
  5. All post requests have the attribute, “ValidateAntiForgeryToken”

The first point, “Each method ties to an action” is incredibly important. Remember a view ties to an action in the controller. What started this was we were trying to get to the Index action for the link we added in “/Views/Shared/_Layout.cshtml”.

The Views

When doing MVVM development there tends to be a one to one relationship between the view model and the view. This isn’t neccasarily true of models as they tend to get used as needed but of view models and views it is.

Take a look at “/Views/Contacts/” and you’ll see that there are 5 views. Each view relates to an action that can be performed on the model. Index lists all instances of the model, and the rest are obvious. This is in stark contrast to how I tend to do MVVM dev. Here is how I would do this in MVVM:

ContactsListView that contains a data context of a ContactsListViewModel. The view model would have a list of contacts I would bind to the list in the view. There would be an empty panel in the view for another view that would be for editing of contacts. At the top of the grid would be a “Create New” button. Selecting a row in the list would set a “SelectedContact” in the view model that would cause the empty panel to populate with a ContactView.

ContactView that contains a data context of a ContactViewModel that would contain the Contact model. It would contain all details on the Contact and would allow you to create, delete and edit the contact.

In MVVM for this operation you end up with two views and two view models. There are a few more “fancy” ways to do this but the above implementation I could probably do in a trivial amount of time.

But here in MVC world we have 5 views and only one controller. Could we do it the same way as I would do it with MVVM? I don’t know, probably something to look at.

So in our ContactsController we have “public ActionResult Index()” and in our views we have Index.cshtml.

@model IEnumerable<ExperimentalProducts.Models.Contact>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.State)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Zip)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.State)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Zip)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ContactId }) |
            @Html.ActionLink("Details", "Details", new { id=item.ContactId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ContactId })
        </td>
    </tr>
}

</table>

I glossed over “@” before but I need to address it here. In the cshtml @ indicates a start of a code block. This is very similar to using <?php and ?> in php and <% and %> in asp.net. For more information on the syntax read Introduction to ASP.NET Web Programming Using the Razor Syntax (C#).

So let’s walk through this code.

  • Line 01: Declare the type for the WebViewPage<TModel> (which is what this view page inherits) is of type IEnumerable<ExperimentalProducts.Models.Contact>.
    • This is the type that will be used for “Model” below.
  • Line 04: Set the ViewBag.Title to “Index”.
  • Lines 13 – 33: Display the columns for each of the properties on the model.
  • Line 15: Use the Html helper object to display the name for the Name property of our model.
    • These are lambda expressions and could just as easily be “x => x.Name”.
      • Try it yourself.  Change all of your “model => model.Property” to “x => x.Property” and you’ll see that the page still loads/works just fine.
    • By default it will use the property name but you can specify your own name in the model by adding the attribute, “[Display(Name = “First/Last Name”)]”. This would therefore display “First/Last Name” instead of just “Name”.
  • Lines 35 – 61: Iterate over each item in Model displaying the values.
    • Model gets set with the results from the Index method in the controller and is a property of WebViewPage<TModel>. Rather like data binding to a data context.
    • Type of Model is determined by the “@model” type set at the top of the page.
    • Where does “modelItem” come from? This is a lambda express we’re passing into the “DisplayFor” method so what it’s name is irrelevant. It’s just like using “x => item.Name”.
  • Line 56: Finally build the links passing in an anonymous object with the property “id”.
    • The property name is important as it must match the parameter on the action method that is being called in the controller.

And that’s it. Just like working in MVVM there is quite a bit you just have to assume is going to get wired up correctly.  The first time I looked over this cshtml I was utterly confused.  Why have @model at the top and then use model in the code?  But once you understand that these are just lambdas being passed into a method everything gets a bit less murky.

Up next I’ll cover the edit and create actions of the controller and the views so we’ll have a better understanding of what is happening in the back-end when everything gets wired up.

Thanks for reading,
Brian

MVC and Azure for the MVVM/WPF Dev, Part 1 – Getting Started

I’ve done extensive web development prior to my current position (where I primarily do desktop applications dev), but it’s been a while. In fact its been almost 5 years since I’ve gotten my hands deep into CSS, javascript and ASP.NET. And 5 years is an eternity in this business. So where are things in the ASP.NET world now-a-days? Well, the big buzz is MVC. This post and any that follow on MVC are about me learning MVC as I go. While I feel I can confidently claim to be an MVVM expert, I know very little about MVC.

There will be bits in this series where I specifically target MVVM/WPF/XAML developers and how to transition knowledge and experience from those domains into MVC but that doesn’t mean that this wouldn’t be a descent guide for those learning MVC.  I’m just learning MVC and I hope to pass on some of that knowledge.

You probably know what MVC is but bear with me as I go into a brief explanation. MVVM is a platform-specific implementation of the application framework design pattern MVC. That’s a mouthful. Where as MVVM is Model-View-ViewModel, MVC is Model-View-Controller. Rather than coming up with another name for MVC in ASP.NET, Microsoft apparently decided to keep it easy and just use MVC. (If your curious you can google around for MVP (Model-View-Presenter), which is the WinForms version of MVC. It doesn’t have anything to do with this, just another version of MVC.)

So it’s all pretty simple, your controller sits in the middle of your view and your model, just like a view model. But as we all know the devil is in the details.

Okay, so how do we get started?

First, if you haven’t already, you need to create an Azure account. I mean, why go to all this trouble if you can’t show off the world what you’ve done? If you have an MSDN license you can create an Azure account, and at least at the time of this post, you get 10 free websites per region. The free sites will use the azurewebsites.net URL (for instance, I created my project with the name “ExperimentalProducts” and thus have the site at experimentalproducts.azurewebsites.net). I’m sure there are a bunch of restrictions. Confirm anything I say about Azure features with the Azure site and team and don’t consider me an authority in this regard. I may be wrong or things may have changed by the time you get around to reading this post. There is a lot more you get with your MSDN subscription for Azure but that is outside of the scope of this post.

After you have an Azure account I’d recommend you start with the tutorial, Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to an Azure Web Site. I followed the tutorial as far as the section on OAuth and OpenID and then switched to the tutorial Code! MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on (C#).

Okay, got all that done? No? Well, if you want to continue to read feel free but it probably won’t make a lot of sense without having your own code available.

If you’ve done the above steps you should be at the same place I am. The problem with some tutorials is that they don’t tell you the consequences of the action. They give a step-by-step process to do exactly what they say they will. This is great but you can do the two above tutorials and not understand anything about MVC. So I want to look at the solution and the state it’s in to try and explain the project and what it is that Microsoft and you created. Again, as mentioned above, I’m doing this so I can have a better understanding of what is happening and hopefully you’ll walk away with a better understanding as well.

As we’re going through this (and as mentioned earlier) I named my project “ExperimentalProducts”. As such a few of the names may be different. I also didn’t name my Contacts Controller “CmController” like the tutorial suggested. I named it “ContactsController”. This seemed more in-line with standard naming conventions.

Here is the project as it should be after the tutorials:

MVC Project

Expand out the references and let’s see what we have.

Libraries other than standard ASP.NET in the project:

Antlr3

WebGrease

These two libraries are used for bundling and minification of css and javascript files. In order to minimize traffic the project will bundle and compress css and javascript. To see how it is used look at /App_Start/BundleConfig.cs in the project.

EntityFramework

Entity Framework is Microsoft’s data access library. Allows you to easily create models and then map them back to the database in a “Code First” approach. You can also do a “Database First” approach where you create the tables in the database and have Entity Framework generate your models for you.

Owin

Microsoft’s implementation of the “Open Web Interface for .NET”. See the article, What is OWIN, and what is it doing in my ASP.NET MVC project? for more information.

Included css and javascript libraries in the project to make everything easier:

bootstrap.css

bootstrap is a css library for making your website work cleanly and easily with mobile browsers. If you shrink down your browser to what a user with a smart phone would see with the default build you will see that everything collapses nice and neat so it will look good on a smart phone.

jQuery

jQuery is the de facto javascript library for doing javascript development.

Modernizr

Modernizr is a javascript library that will determine what features (like css gradients) are available in the user’s browser. This way you can test in your css or javascript if a feature is available.

That’s it for now. Just wanted to cover setting up the projects and what was added. Next week I’ll get more in-depth on what the models, views and controllers are doing, how they parallel MVVM and how they’re different.

Thanks for reading,
Brian

Live Filter Design Pattern in XAML

GetTheCode

I decided I should start titling my posts with XAML instead of WPF as they are applicable regardless of whether you are developing in Windows 7 with WPF or Windows 8. I’m going to take the BreadCrumb design pattern sample and extend it to include the Live Filter design pattern.

The premise behind the Live Filter design pattern is pretty simple, show the user everything and then allow them to filter the results, immediately showing how the filter affects the results. As noted in the BreadCrumb post dense trees can easily become overwhelming to users. Providing a simple, easy to use live filter makes the experience significantly better.LiveFilter

In the above image you can see there we have a search text box with two filter parameters. As the user types into the search box the results are immediately filtered.

<Grid Grid.Row="0" Grid.ColumnSpan="3" Margin="5">
    <xctk:WatermarkTextBox Margin="2" Watermark="Search" Text="{Binding SearchValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
    <Button Margin="5 0 5 0" Width="16" Height="16" HorizontalAlignment="Right" FontFamily="Segoe UI Symbol" Opacity=".75" ToolTip="Clear" Command="{Binding ClearCommand}">
        <TextBlock Margin="0 -3.5 0 0" Foreground="#FF63A3B2">👽</TextBlock>
    </Button>
</Grid>
<StackPanel Grid.Row="1" Grid.ColumnSpan="3" Margin="5" Orientation="Horizontal">
    <CheckBox Margin="5" IsChecked="{Binding SearchProperty2, Mode=TwoWay}" Content="Include Property 2 In Search" />
    <CheckBox Margin="5" IsChecked="{Binding SearchProperty3, Mode=TwoWay}" Content="Include Property 3 In Search" />
</StackPanel>

Above is the XAML for the search controls. Most of it is standard MVVM binding. The problem with standard MVVM binding is that for textbox it only updates the underlying view model property on lost focus. That doesn’t help us as we want to update the results in real-time. To fix this the UpdateSourceTrigger is set to PropertyChanged. This way as soon as the user types a letter the property is changed and we can perform a search. (I’m actually using the nuget package for the Extended WPF Toolkit to provide a watermark textbox but it works like a regular textbox).

<TreeView Grid.Row="2" Grid.RowSpan="2" Margin="5" 
        ItemsSource="{Binding ChildNodes}"
        VirtualizingStackPanel.IsVirtualizing="True"
        VirtualizingStackPanel.VirtualizationMode="Recycling"
        SelectedItemChanged="TreeView_SelectedItemChanged">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="Visibility" Value="{Binding Visibility, Mode=TwoWay}" />
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <StackPanel>
                <TextBlock Text="{Binding Property1}" FontSize="18" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

The first important part is the TreeViewItemContainerStyle. The nodes implement the properties IsExpanded and Visibility. This is extremely important. We don’t want to have to deal with the ItemContainerGenerator. This can be a major pain the rear and will make the code extremely sluggish. If we’re going to go with binding the nodes in the tree let’s take full advantage of it. The other important part is setting up the VirtualizingStackPanel values. The search is really rather trivial and usually works extremely fast. The slow part is updating the UI. We leave that to the masters at Microsoft by binding everything and letting them figure out how to render it. But we can help things out a bit. By setting up the VirtualizingStackPanel the control doesn’t have to render all the children in the tree. Now use this with some caution. Because the nodes will only be updated as the user drags the scroll bar you can get some choppy and sluggish operations as the control updates.

string searchValue;
public string SearchValue
{
    get { return searchValue; }
    set
    {
        if (SetProperty(ref searchValue, value))
        {
            PerformSearch();
        }
    }
}

bool searchProperty2 = false;
public bool SearchProperty2
{
    get { return searchProperty2; }
    set 
    {
        if (SetProperty(ref searchProperty2, value))
        {
            PerformSearch();
        }
    }
}

bool searchProperty3 = false;
public bool SearchProperty3
{
    get { return searchProperty3; }
    set 
    { 
        if(SetProperty(ref searchProperty3, value))
        {
            PerformSearch();
        }
    }
}

These are the properties in the view model. We’re using BindableBase from Prism for the view model. Thus SetProperty returns a true if there was a change. We need to minimize extraneous calls to PerformSearch as much as possible.

private static object lockObj = new object();
private CancellationTokenSource CancellationTokenSource { get; set; }
private void PerformSearch()
{
    //if we're doing a search then we probably have some new search term
    clearCommand.RaiseCanExecuteChanged();

    lock (lockObj)
    {
        if (CancellationTokenSource != null)
            CancellationTokenSource.Cancel();

        CancellationTokenSource = new CancellationTokenSource();

        resultCount = 0;
    }

    Task.Run(() =>
    {
        DateTime now = DateTime.Now;
        try
        {
            if (string.IsNullOrEmpty(SearchValue))
            {
                ClearAllNodes(ChildNodes, Visibility.Visible, CancellationTokenSource.Token);
                return;
            }
            else
            {
                ClearAllNodes(ChildNodes, Visibility.Collapsed, CancellationTokenSource.Token);
            }

            var options = new ParallelOptions { CancellationToken = CancellationTokenSource.Token };
            try
            {
                Parallel.ForEach(ChildNodes, options, (childNode) =>
                {
                    PerformSearch(childNode, options);
                });
            }
            catch (OperationCanceledException)
            {
                //Noop
            }
        }
        finally
        {
            LastSearchTookInMilliseconds = (DateTime.Now - now).Milliseconds;
            OnPropertyChanged(() => ResultCount);
        }
    }, CancellationTokenSource.Token);
}

private void PerformSearch(RandomValueNode childNode, ParallelOptions options)
{
    if (options.CancellationToken.IsCancellationRequested)
        return;

    if (childNode.Property1.StartsWith(SearchValue) ||
        (SearchProperty2 && childNode.Property2.StartsWith(SearchValue)) ||
        (SearchProperty3 && childNode.Property3.StartsWith(SearchValue)))
    {
        Interlocked.Increment(ref resultCount);
        childNode.IsExpanded = true;
        childNode.Visibility = Visibility.Visible;
    }
    foreach (RandomValueNode node in childNode.Children)
    {
        if (options.CancellationToken.IsCancellationRequested)
            break;

        PerformSearch(node, options);
    }
}

And finally we do the search. To make this as responsive as possible we need to cancel the search each time as quickly as possible. Thus I’m using a CancellationToken in the Task.Run and the Parallel.ForEach to do the search. Remember that it is only effective to spin off threads from the thread pool if you can give them enough work. In my case there will only be ten nodes but I give each of those plenty to do. I’m passing the options into the PerformSearch so that we kill the search as quick as possible. As the code recurses I want to kill everything. It may seem like overkill to check for options.CancellationToken.IsCancellationRequested at the top of the method and in the foreach, and it may very well be.

So this pattern is pretty straightforward, simply update live results as the user changes the filter parameters. The key here is taking into account the result set size and to stop any existing search quickly, really try and take advantage of all that the TPL provides. As you can see in the image at the top I can iterate over 700,000 nodes pretty quickly and the UI is still pretty responsive. Of course that is really more because of the Task.Run and using VirtualizingStackPanel.

There is, of course, another way to do this. If you find that things are moving much too sluggish the other alternative is to show a minimal amount of results (like when doing a Google search and it begins to suggest terms). Then in the background have a thread that starts to update the results.

I would encourage you to get the code from the “GET THE CODE” button at the top.

Thanks for reading,
Brian

GetTheCode

I’ve been getting quite a few hits lately on my post, Binding a Dependency Property of a View to its ViewModel. After reviewing it I realized that, while the post isn’t too bad, it doesn’t read as smooth as I would like (though it does have some pretty pictures with arrows and boxes and stuff, oh my!). The code samples seem a bit lacking in describing the overall complexity of what needed to be done.

I know I always prefer to have actual code that demonstrates a concept and so I decided to take the sample code, which was incomplete, from my post Composite and Memento Design Patterns – A Real World Example and put together a complete solution.

two tabs

What you see here are the two tabs of the solution.  The first tab is simply a single instance of the control.  It works completely stand-alone and has it’s own View, ViewModel and Model.  The second tab is four instances of the control but there is a lot going on here with the binding on the controls to make everything work.

The  single instance has nothing bound to it other than it’s own view model.  The xaml for the control looks like:

<UserControl x:Class="CompositeMementoSample.Views.FileGroupView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:utility="clr-namespace:CompositeMementoSample.Infrastructure"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <utility:ViewModeToVisibilityConverter x:Key="modeToVisConv"/>
        <utility:InverseViewModeToVisibilityConverter x:Key="invModeToVisConv"/>
    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Label Grid.ColumnSpan="2" Grid.Row="0" Margin="5" Foreground="Orange" HorizontalAlignment="Center" FontSize="15"
                   Content="{Binding Title, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
                   Visibility="{Binding ViewMode, Converter={StaticResource invModeToVisConv}}" />
        <ListView Grid.Row="1" MinWidth="150" ItemsSource="{Binding CompositeList}" />
        <StackPanel Grid.Row="2" Orientation="Horizontal">
            <Button Command="{Binding AddFilesCommand}">Add Files</Button>
            <Button Command="{Binding SaveXmlCommand}" Visibility="{Binding ViewMode, Converter={StaticResource modeToVisConv}}">Save XML</Button>
            <Button Command="{Binding LoadXmlCommand}" Visibility="{Binding ViewMode, Converter={StaticResource modeToVisConv}}">Load XML</Button>
        </StackPanel>
    </Grid>
</UserControl>

The ViewModeToVisibilityConverter and the InverseViewModeToVisibilityConverter just show/hide controls based on what mode we’re in. The default is “Full” but when we want to use the control within other controls we assume that we want “Compact”. In compact mode we may not want to enable all features of the control and so we hide/show what we need to. Here, we want to only show a title when it’s part of another control but we only want to allow them to load and save the xml file that contains the list of files if it is a standalone control.

What is critical here is how the properties are exposed.

public partial class FileGroupView : UserControl
{
	public ViewMode ViewMode
	{
		get { return (ViewMode)GetValue(ViewModeProperty); }
		set { SetValue(ViewModeProperty, value); }
	}

	public static readonly DependencyProperty ViewModeProperty =
		DependencyProperty.Register("ViewMode", typeof(ViewMode), typeof(FileGroupView), new FrameworkPropertyMetadata(ViewMode.Full));

	public string Title
	{
		get { return (string)GetValue(TitleProperty); }
		set { SetValue(TitleProperty, value); }
	}

	public static readonly DependencyProperty TitleProperty =
		DependencyProperty.Register("Title", typeof(string), typeof(FileGroupView), new PropertyMetadata(null));

	public FileGroupModel ActiveFileGroup
	{
		get { return (FileGroupModel)GetValue(ActiveFileGroupProperty); }
		set { SetValue(ActiveFileGroupProperty, value); }
	}

	public static readonly DependencyProperty ActiveFileGroupProperty =
		DependencyProperty.Register("ActiveFileGroup", typeof(FileGroupModel), typeof(FileGroupView), new FrameworkPropertyMetadata(null, OnActiveFileGroupChanged));

	private static void OnActiveFileGroupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		((FileGroupViewModel)((FileGroupView)d).DataContext).ActiveFileGroup = (FileGroupModel)e.NewValue;
	}

	public FileGroupView()
	{
		OpenSaveDialogInterface dialogInterface = new OpenSaveDialogInterface();
		this.DataContext = new FileGroupViewModel(dialogInterface, dialogInterface);
		InitializeComponent();

		string propertyInViewModel = "ViewMode";
		var bindingViewMode = new Binding(propertyInViewModel) { Mode = BindingMode.TwoWay };
		this.SetBinding(ViewModeProperty, bindingViewMode);

		propertyInViewModel = "ActiveFileGroup";
		var bindingActiveFileGroup = new Binding(propertyInViewModel) { Mode = BindingMode.TwoWay };
		this.SetBinding(ActiveFileGroupProperty, bindingActiveFileGroup);
	}
}

The important bits here are the “this.SetBinding” which is setting up the binding between our dependency properties (which is what this is all about) and the view model.

Now that we’ve done all this, lets look at the xaml for the view that houses all four of these controls.

<UserControl x:Class="CompositeMementoSample.Views.MultiFileGroupView"
		 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
		 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		 xmlns:views="clr-namespace:CompositeMementoSample.Views"
		 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
		 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
		 mc:Ignorable="d" 
		 d:DesignHeight="300" d:DesignWidth="300">
<Grid>
	<Grid.RowDefinitions>
		<RowDefinition />
		<RowDefinition />
		<RowDefinition Height="40" />
	</Grid.RowDefinitions>
	<Grid.ColumnDefinitions>
		<ColumnDefinition />
		<ColumnDefinition />
	</Grid.ColumnDefinitions>
	<views:FileGroupView Grid.Row="0" Grid.Column="0" 
		ViewMode="Compact" 
		Title="File Group 1"
		ActiveFileGroup="{Binding DataContext.FileGroup1, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
	<views:FileGroupView Grid.Row="0" Grid.Column="1" 
		ViewMode="Compact" 
		Title="File Group 2"
		ActiveFileGroup="{Binding DataContext.FileGroup2, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
	<views:FileGroupView Grid.Row="1" Grid.Column="0" 
		ViewMode="Compact"
		Title="File Group 3"
		ActiveFileGroup="{Binding DataContext.FileGroup3, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
	<views:FileGroupView Grid.Row="1" Grid.Column="1"
		ViewMode="Compact"
		Title="File Group 4"
		ActiveFileGroup="{Binding DataContext.FileGroup4, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
	<StackPanel Grid.ColumnSpan="2" Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
		<Button Margin="7" Command="{Binding SaveXmlCommand}">Save XML</Button>
		<Button Margin="7" Command="{Binding LoadXmlCommand}">Load XML</Button>
	</StackPanel>
</Grid>
</UserControl>

The binding to the file group is a bit tricky because you have to explicitly call out the property on the data context or else it won’t see it.

And that’s it. Most of the solution is really the MVVM parts: views, view models and support pieces. Hopefully you grab the solution from the “GET THE CODE” button at the top of the post as that is probably the best way to understand what is going on here.

Thanks for reading,
Brian

Capitalization Conventions in .NET

In the middle of a code review the other day one of the engineers turned to me and asked, “Why are all your method parameters capitalized?”
“Hmmm, well,” I told him, “that’s the Microsoft convention.”
“No, it’s not.” he replied.
And he was right.

If you are so inspired and go back to read my code in past posts it may not be obvious as I often use snippets and auto-generated code but it’s there.  This is probably even worse as it introduces an inconsistency where some of my parameters are PascalCased and others are camelCased.

Style and capitalization conventions are something we programmers often tread lightly on. Does the open curly brace go on the line with the method definition or the next line? Should closing curly brace go be lined up with the method definition or with the last line of code? We take style and conventions almost like gospel and it’s hard to let it go so we try not to point out something that we disagree with. That is why there should be some reference that all programmers can refer to either compiled by your lead architect or by some industry standard.  That way when someone suggests something is wrong with our style there can be common guideline rather than taking it personally. I know it may not seem like it but this is really critical when working in other programmers’ code. It goes to code readability and therefore ease of maintenance.

I’m not sure how or why but in the last few years I started PascalCasing my method parameters. If you check the capitalization conventions you find every public facing identifier uses PascalCasing except parameters, which uses camelCasing.

But there is more there than I realized. So for my own reference I decided to write a post about it. This is all available at the link above but presented here as a summary

  1. PascalCasing, as defined by Microsoft, has the first letter upper cased.
  2. camelCasing, as defined by Microsoft, has the first letter lower cased.
  3. All identifiers except parameter names use PascalCasing, this includes acronyms. (HtmlTag, XmlWriter)
  4. The only exception is two-letter acronyms.
    1. For PascalCasing upper case both. (IOStream)
    2. For camelCasing lower case both. (ioStream)
  5. Never use an underscore in an identifier.

Where things really get into the weeds, and I’m sure I’ve violated this quite a bit is the use of compound terms.

  1. Treat most compound terms as single words for purposes of capitalization. (Endpoint, metadata)
    1. There are all sorts of exceptions to this so check the reference. (LogOff, SignIn, fileName)
  2. Treat a closed-form compound term as a single word. (Keyboard, crosstown)
    1. There are exceptions to this so check the reference. (UserName)

That last one especially kills me. Username is a closed-form compound term (based on both the latest Merriam-Webster and Random House Dictionary), meaning that it is treated as a single word. But according to Microsoft, for capitalization purposes, User and Name should both be capitalized.

Notable Common Terms that violate the rules or are special just because Microsoft says so (from the reference):

Pascal Camel Not
BitFlag bitFlag Bitflag
Callback callback CallBack
Canceled canceled Cancelled
DoNot doNot Don’t
Email email EMail
Endpoint endpoint EndPoint
FileName fileName Filename
Gridline gridline GridLine
Hashtable hashtable HashTable
Id id ID
Indexes indexes Indices
LogOff logOff LogOut
LogOn logOn LogIn
Metadata metadata MetaData, metaData
Multipanel multipanel MultiPanel
Multiview multiview MultiView
Namespace namespace NameSpace
Ok ok OK
Pi pi PI
Placeholder placeholder PlaceHolder
SignIn signIn SignOn
SignOut signOut SignOff
UserName userName Username
WhiteSpace whiteSpace Whitespace
Writable writable Writeable

There are a few oddities here I wanted to point out.

  1. UserName, I mentioned earlier. It’s a closed-form compound word that is not treated as a single word.
  2. LogOn. I can almost understand using LogOff instead of LogOut as LogOff is a recognized compound word. But “Log On” and “Log In” are both recognized compound words. The only reason I can think to prefer LogOn to “LogIn” is to be consistant with LogOff.
    1. This also applies to SignIn/SignOut
  3. Indexes. Both indexes and indices are recognized plural forms of index. Maybe just for consistancy?
  4. The two letter words. I point that out because I see this a lot: Ok, ok, not OK, Id, id, not ID, Pi, pi, not PI.

Well, that’s it for now. Hopefully we can all now code to the same conventions when working in .NET.

Thanks for reading,
Brian

BreadCrumb Design Pattern in WPF

GetTheCode

This continues my series on ways you’ve probably used design patterns in real-life and may not have even known it.

I’m going to go even further outside of the standard software design patterns into UI design patterns. Specifically, I wanted to address the bread crumb, a UI design pattern that concerns navigation. In web development the bread crumb is a standard control that has become almost necessary to help the user keep track of where they are. Unlike in an application where users tend to stay in one general area, web sites and web applications often have users moving through multiple pages and it’s easy to get lost. I’m sure you are all familiar with the bread crumb in web development.

Dell Bread Crumb

Above you can see a bread crumb control from Dell’s website. Because there is depth to navigation in most websites the bread crumb helps provide a path for users to return to where they started.

The BreadCrumb in WPF

But how does this apply to desktop application development? As I mentioned above desktop applications tend to be very focused in a single area. There are, however, two primary areas I’ve witnessed where users get lost. The first is in standard business applications where the application has a high number of forms that users have to navigate through. Getting user information, family information, contact information, alternate contact information, etc… it’s easy for users to get lost in their path trying to gather information on clients/customers. The other is in deeply nested trees.

I wanted to present to you a basic bread crumb control. The solution/code provided is a bit of an ugly hybrid in terms of MVVM and code-behind but will get across the basic steps you need to take. Also by providing a working solution in WPF hopefully I’ve done a lot of the work for you.

BreadCrumbSampleImage
The image above is from the sample provided that demonstrates where a bread crumb control is especially useful. When dealing with trees it’s easy to get lost. By providing a bread crumb control you make it easier for your users to navigate through the tree.

Let’s start with the interface the control uses, IParent:

public interface IParent
{
    IParent Parent { get; }
}

Pretty simple. The node that I bind the tree to implements the IParent interface. This way my BreadCrumb control can be a bit more multi-purpose.

Next is looking at BreadCrumbs.xaml:

<UserControl x:Class="BreadCrumbs.Views.BreadCrumbs"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <!--http://stackoverflow.com/questions/780426/link-button-in-wpf-->
        <Style TargetType="Button"
               BasedOn="{StaticResource ResourceKey={x:Type Button}}">
            <Setter Property="Width" Value="Auto"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <ContentPresenter Content="{TemplateBinding Content}" 
                                  ContentTemplate="{TemplateBinding  ContentTemplate}"
                                  VerticalAlignment="Center">
                            <ContentPresenter.Resources>
                                <Style TargetType="{x:Type TextBlock}">
                                    <Setter Property="TextDecorations" Value="Underline" />
                                </Style>
                            </ContentPresenter.Resources>
                        </ContentPresenter>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="FontSize" Value="20" />
            <Setter Property="Cursor" Value="Hand" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Foreground" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>
    <WrapPanel x:Name="pnlContent" />
</UserControl>

The main thing that is interesting here is the style that targets button. In general, we try and present a look and feel that users expect. That’s not a hard and fast rule and I’m certainly open for change in this area, but a generality. By styling the buttons to look like a link we provide a navigational interface users expect.

And now for BreadCrumbs.xaml.cs:

public partial class BreadCrumbs : UserControl
{
	public IParent SelectedItem
	{
		get { return (IParent)GetValue(SelectedItemProperty); }
		set { SetValue(SelectedItemProperty, value); }
	}

	// Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
	public static readonly DependencyProperty SelectedItemProperty =
		DependencyProperty.Register("SelectedItem", typeof(IParent), typeof(BreadCrumbs), new PropertyMetadata(null, OnSelectedItemChanged));

	private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		((BreadCrumbs)d).BuildPath(e.NewValue as IParent);
	}
	
	public BreadCrumbs()
	{
		InitializeComponent();
	}

	private void BuildPath(IParent Node)
	{
		pnlContent.Children.Clear();
		while (Node != null)
		{
			Button b = new Button();
			b.Content = Node.ToString();
			b.Click += b_Click;
			b.Tag = Node;
			pnlContent.Children.Insert(0, b);
			Node = Node.Parent;
			//if we have more parents then we want a seperator
			if (Node != null)
			{
				Label seperator = new Label();
				seperator.Content = ">>";
				pnlContent.Children.Insert(0, seperator);
			}
		}
	}

	void b_Click(object sender, RoutedEventArgs e)
	{
		IParent selectedItem = ((Button)sender).Tag as IParent;
		SelectedItem = selectedItem;
	}
}

The first interesting thing is the dependency property SelectedItem. When this gets used in the parent control we need a dependency property to bind the selected against. In this parent control we use Mode=TwoWay so that not only do we get the item when it is selected from the tree but we can also set the selected item in the parent control by setting our own dependency property.

The BuildPath method is pretty straight forward. We know we have an IParent node and we already have the style set up on the xaml to make all our buttons look like links. We just have to iterate over the node and any parents. And since we’re using a wrap panel all the buttons will show on the control. We also set the SelectedItem when the button is clicked. This allows us to update the SelectedItem in the parent control so that the navigation via the bread crumbs allow users to move backward through the tree.

There is certainly future expansion that can be done here as there may need to be some limit on the wrap panel or you may want to show only n number of nodes back.

Hopefully you get some use out of this. The complete source code is in sample provided. If you have any questions or problems let me know.

Thanks for reading,
Brian

Bind a ComboBox to an enum while using Display attribute

I found a lot of different tutorials on binding a ComboBox to an enum but none of them worked. In every case the ComboBox would not stay selected to the value I chose, instead always reverting back to the previous selected value. Couple that with the fact that I wanted to use the Display attribute and, well, all hell broke loose.

So here I am with a brief write-up on my solution.

Let’s start with our model. In this case we’ll be designing a shirt. We’ll only be defining a shirt type but maybe in the future I might do something else with the sample. You’ll need to make sure you add the “System.ComponentModel.DataAnnotations” reference to your project if it’s not already there. That is where the Display attribute is.

public enum ShirtType
{
    [Display(Name="Dress Shirt")]
    DressShirt,
    [Display(Name="T-Shirt")]
    TShirt,
    CampShirt,
    Polo,
    Jersey
}

public class Shirt : INotifyPropertyChanged
{
    ShirtType type = ShirtType.DressShirt;
    public ShirtType Type
    {
        get { return type; }
        set { SetProperty(ref type, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (object.Equals(storage, value)) 
            return false;

        storage = value;
        OnPropertyChanged(propertyName);

        return true;
    }

    protected void OnPropertyChanged(string propertyName)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

The shirt model is unremarkable. Since this is just a basic sample I’ve implemented INotifyPropertyChanged instead of using the BindableBase from Prism. What is interesting is the use of the DisplayAttribute on the enum values. The Display attribute allows you to define a name and optional resource for localization. There are some other properties but those are the two we care about. Next we’ll use a converter to change this attribute into a value for the ComboBox.

public class EnumToDisplayAttribConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!value.GetType().IsEnum)
        {
            throw new ArgumentException("Value must be an Enumeration type");
        }

        var fieldInfo = value.GetType().GetField(value.ToString());
        var array = fieldInfo.GetCustomAttributes(false);

        foreach (var attrib in array)
        {
            if (attrib is DisplayAttribute)
            {
                DisplayAttribute displayAttrib = attrib as DisplayAttribute;

                //if there is no resource assume we don't care about localization
                if (displayAttrib.ResourceType == null)
                    return displayAttrib.Name;

                // per http://stackoverflow.com/questions/5015830/get-the-value-of-displayname-attribute
                ResourceManager resourceManager = new ResourceManager(displayAttrib.ResourceType.FullName, displayAttrib.ResourceType.Assembly);
                var entry =
                    resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
                      .OfType<DictionaryEntry>()
                      .FirstOrDefault(p => p.Key.ToString() == displayAttrib.Name);

                var key = entry.Value.ToString();
                return key;
            }
        }

        //if we get here than there was no attrib, just pretty up the output by spacing on case
        // per http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array
        string name = Enum.GetName(value.GetType(), value);
        return Regex.Replace(name, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Now this is where the magic happens. The converter takes in the enum bound to the row in the ComboBox and converts it to a string. If a custom DisplayAttribute can be found and it has a resource then it attempts to get the value for localization. Otherwise it just uses the value straight up. If there is no DisplayAttribute then it tries to be smart and converts a Pascal Cased enum to have spaces.

Okay, now we’ve got the enums, we’ve got the converter, now how do we wire it up? We’re going to bind to an ObjectDataProvider in the XAML.

<Window x:Class="BindingToEnum.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib" 
        xmlns:local="clr-namespace:BindingToEnum"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:Shirt />
    </Window.DataContext>
    <Window.Resources>
        <local:EnumToDisplayAttribConverter x:Key="enumToDisplayAttribConverter" />
        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="dataFromShirtType">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:ShirtType" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <ComboBox Grid.Row="0" MinWidth="100" HorizontalAlignment="Left" 
                            FontSize="20"
                            ItemsSource="{Binding Source={StaticResource dataFromShirtType}}"
                            SelectedItem="{Binding Type}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding ., Converter={StaticResource enumToDisplayAttribConverter}}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</Window>

So lets look at the important bits of this:

Line 04: We have to add the sys namespace.
Line 05: Our local namespace.
Line 11: The converter we’re going to use.
Line 12: The ObjectDataProvider. This will get the values of the enum to be used later.
Line 14: The actual type of the enum we’re retrieving.
Line 24: We bind the ItemsSource of the ComboBox to the key of the ObjectDataProvider defined on line 12.
Line 25: We bind the Selected Item to the “Type” property of our model.
Line 26: We want to define a custom data template so we can use our converter.
Line 28: We bind the text of the text block to “.”. This just means use the data context we’re bound to. Since each row in a ComboBox will be bound to an enum, this just means we’re using the enum for the row.
And finally use the converter we defined at line 11.

Of all of this, probably the biggest take-away is binding the TextBlock.Text to “.”. This way the enum will be passed off to our converter. Attached is the code.

Thanks for reading.
Brian

Monitor Design Pattern with Semaphore

This continues my series on ways you’ve probably used design patterns in real-life and may not have even known it. The previous post was on the Locking, Double-Checked Locking, Lazy and Proxy Design Patterns.

In the last post we began to look at design patterns outside of the standard creational, structural and behavioral, venturing into concurrency design patterns. The concurrency design patterns are so critical because of the rise of multi-core processors and easy to use threading libraries.

In the last write-up I used the concept of a context switch to show the benefits using double-checked locking. The problem with this concept is that there may not be a context switch but may actually be two threads that are working in the same piece of code at the same time. Context switching was necessary when we had single core processors that gave the appearance of doing multi-threading but everything was still operating sequentially. Of course we still have context switching. We usually only have 4 or 8 cores so to support hundreds of threads we’ll still need context switching.

But now we run into the very real problem of multiple threads attempting to access what may be limited resources at the same time. As we saw in the last post we can lock around specific code to limit the access to the code across threads. The monitor design pattern consists of an object, the monitor, that handles controlling when threads can access code blocks. Locking in .NET is the the easiest form of the monitor design pattern in that lock(lockobj) ends up just being syntactic sugar wrapping a Monitor object. In being the easiest form, however, it is also the simplest in that it doesn’t provide a lot of flexibility.

There are a lot of different types of monitors as shown in the reference above but I wanted to talk about one specific type, the Semaphore. The premise of the Semaphore is pretty straight forward, limit to a specific number the amount of threads that have access to a block of code. It’s like lock but you can control the number of threads. In .NET we have two different types of semaphores, Semaphore and SemaphoreSlim. I suspect, in general, you will want a SemaphoreSlim as it is lightweight and fast. But it’s intended to be used only where wait times for the resources will be short. But how short is short? Well, that’s something you will have to investigate on your own as there is no guidance from Microsoft other than “short”. For more information on the differences between Semaphore and SemaphoreSlim please read the Microsoft article addressing it.

Using a SemaphoreSlim is incredibly easy. Here is a sample I’ve incorporated into my TPLSamples.

SemaphoreSlim pool = new SemaphoreSlim(2);  //limit the access to just two threads
List<Task> tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
	Task t = Task.Run(() =>
	{
		UpdateLog("Starting thread " + Thread.CurrentThread.ManagedThreadId);
		pool.Wait();  //wait until we can get access to the resources
		string result = new WebClient().DownloadString("http://msdn.microsoft.com");
		UpdateLog("Thread " + Thread.CurrentThread.ManagedThreadId + ": Length = " + result.Length);
		pool.Release();  //and finally release the semaphore
	});
	tasks.Add(t);
}

Task.WaitAll(tasks.ToArray());

This results in the output:

Starting Semaphore Slim Sample
Starting thread 9
Starting thread 10
Starting thread 14
Starting thread 15
Starting thread 13
Thread 10: Length = 25146
Thread 9: Length = 25152
Thread 14: Length = 25152
Thread 15: Length = 25146
Thread 13: Length = 25146
Completed Semaphore Slim Sample
Semaphore Slim Sample ran in 00:00:02.0143689

It’s not obvious by this output that we’re limiting the download to just two threads at a time but we are. Now we may not be able to use such a contrived example and may need to actually use this in production code. In that case you’ll want to do this asyncronously with async/await.

SemaphoreSlim pool = new SemaphoreSlim(2); //limit the access to just two threads
List<Task> tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
	Task t = Task.Run(async () =>
	{
		UpdateLog("Starting thread " + Thread.CurrentThread.ManagedThreadId);
		await pool.WaitAsync();  //wait until we can get access to the resources
		string result = await new HttpClient().GetStringAsync("http://msdn.microsoft.com");
		UpdateLog("Thread " + Thread.CurrentThread.ManagedThreadId + ": Length = " + result.Length);
		pool.Release();  //and finally release the semaphore
	});
	tasks.Add(t);
}

Task.WaitAll(tasks.ToArray());

This results in the output:

Starting Semaphore Slim Async Sample
Starting thread 9
Starting thread 15
Starting thread 14
Starting thread 13
Starting thread 17
Thread 19: Length = 25143
Thread 19: Length = 25149
Thread 21: Length = 25149
Thread 21: Length = 25143
Thread 21: Length = 25143
Completed Semaphore Slim Async Sample
Semaphore Slim Async Sample ran in 00:00:02.1258904

Wait a minute! How can the thread ids when we have the web page be different than what the thread started? The framework tries to help you out by maintaining a SynchronizationContext. Covering the SyncronizationContext is outside of the scope of a article on using Semaphore but I would highly recommend reading the article It’s All About the SynchronizationContext where they cover the problems with using Task.Run and losing the current SyncronizationContext. See, if we have a SyncronizationContext then awaiting isn’t a big deal, the framework will use the current SyncronizationContext. When we use Task.Run to spin off a new task that current SyncronizationContext is lost and we no longer return to the same thread when we use await.

For us, in using a SemaphoreSlim, we don’t care. Losing the SyncronizationContext can be a big deal, however, especially in UI where you need the main thread.

So that’s really it, using a SemaphoreSlim to demonstrate the Monitor design pattern. I’ve updated my TPL Sampler to include these two samples.

Thanks for reading,
Brian

This continues my series on ways you’ve probably used design patterns in real-life and may not have even known it. The previous post was on the Iterator Design Pattern.

The original book on software design patterns, Design Patterns: Elements of Reusable Object-Oriented Software discussed three types of design patterns, creational, structural and behavioral. As time has continued we’ve found a need for further patterns to cover other targeted areas. One of those areas is concurrency patterns that specifically addresses patterns for multi-threaded software development.

With the ease of the TPL and async/await integrated into .NET, multi-threaded software development should be the standard. Microsoft has gone to great pains to make multi-threaded development ridiculously easy. In fact it actually causes some hesitancy when I consider doing development in any other languages. I had been hoping when Swift was released that Apple had the forethought to improve the horrendous multi-threading model in Objective-C but they did not. In defence of Objective-C however, it’s not any worse than most other languages.

This brings us to the double-checked locking design pattern that is a part of the concurrency patterns. Consider the following code:

public class Singleton
{
	private Singleton() { /* Some long task to initialize */ }

	private static Singleton _instance = null;
	public static Singleton Instance
	{
		get
		{
			if (_instance == null)
				_instance = new Singleton();
			return _instance;
		}
	}
}

The problem with this code is that you run the potential for multiple instances of Singleton to be running around when you only wanted one. Here is the scenario:

Thread 1, line 10: Since this is the first access _instance is null.
CONTEXT SWITCH
Thread 2, line 10: Hmm, _instance is null.
CONTEXT SWITCH
Thread 1, line 11: Well, since _instance is null we have to create a new instance.
Thread 1, line 12: return the _instance we just created.
CONTEXT SWITCH
Thread 2, line 11: Well, since _instance is null we have to create a new instance.
Thread 2, line 12: return the _instance we just created.

Here is a perfect scenario to utilize locking. Locking is a pattern that allows a thread exclusive access to a segment of code without having to worry about other threads entering the block of code.

public class Singleton
{
	private Singleton() { /* Some long task to initialize */ }

	private static object lockObj = new object();
	private static Singleton _instance = null;
	public static Singleton Instance
	{
		get
		{
			lock (lockObj)
			{
				if (_instance == null)
					_instance = new Singleton();
			}
			return _instance;
		}
	}
}

We can see that the lock will block the constructor until the current thread is done. Here is the scenario:
Thread 1, line 11: No ones here so let’s go into the lock.
Thread 1, line 13: Since this is the first access _instance is null.
CONTEXT SWITCH
Thread 2, line 11: Hmm, some other thread is here already, I’ll have to wait.
CONTEXT SWITCH
Thread 1, line 14: Well, since _instance is null we have to create a new instance.
Thread 1, line 15: Done with the lock.
CONTEXT SWITCH
Thread 2, line 11: Whoever was here is done, let’s get going.
Thread 2, line 13: _instance has a value.
CONTEXT SWITCH
Thread 1, line 16: return _instance.
CONTEXT SWITCH
Thread 2, line 16: return _instance.

Now there are some problems with locking, most notably dead locking. This occurs when there is a lock on thread 1 but thread 2 is waiting for thread 1 to finish. Neither can continue and your application locks up. Additionally, by utilizing locks you turn a small piece of code into a bottleneck and eliminate a lot of the benefits of multi-threading. If threads can only enter the lock one at a time to see if _instance is null, what are we really gaining here?

This is where the double-checked locking pattern comes in handy. Why go into the lock if you don’t need to?

public class Singleton
{
	private Singleton() { /* Some long task to initialize */ }

	private static object lockObj = new object();
	private static Singleton _instance = null;
	public static Singleton Instance
	{
		get
		{
			if (_instance == null)  //first check
			{
				lock (lockObj)
				{
					if (_instance == null)  //second check
						_instance = new Singleton();
				}
			}
			return _instance;
		}
	}
}

We just check to see if the value is null and if it isn’t we don’t even have to consider locking. Here is the scenario:
Thread 1, line 11: Since this is the first access _instance is null.
Thread 1, line 13: No ones here so let’s go into the lock.
CONTEXT SWITCH
Thread 2, line 11: Hmm, _instance is null.
Thread 2, line 13: Hmm, some other thread is here already, I’ll have to wait.
CONTEXT SWITCH
Thread 1, line 16: Well, since _instance is null we have to create a new instance.
Thread 1, line 17: Done with the lock.
CONTEXT SWITCH
Thread 3, line 11: _instance has a value.
Thread 3, line 19: return _instance.
CONTEXT SWITCH
Thread 2, line 11: Whoever was here is done, let’s get going.
Thread 2, line 15: _instance has a value.
CONTEXT SWITCH
Thread 1, line 19: return _instance.
CONTEXT SWITCH
Thread 2, line 19: return _instance.

This scenario presents the best of both worlds (which is why it’s a pattern), it allows you to safely construct your singleton while still minimizing locking. But as I’m sure you know, in .NET we can do better. As I mentioned earlier Microsoft has gone to some pretty great pains to make multi-threading easier for us. One of those ways is by using Lazy<T>.

public class Singleton
{
	private Singleton() { /* Some long task to initialize */ }
	private static readonly Lazy<Singleton> _lazyInstance = new Lazy<Singleton>(() => new Singleton());
	public static Singleton Instance
	{
		get { return _lazyInstance.Value; }
	}
}

All this is doing is taking out the need for double-checked locking by doing it for you. That’s it. Now, this is the most basic use of Lazy<T>. If you read the reference you have a lot of control in terms of what happens when exceptions are thrown in the constructor as well as other aspects so if you take fully take advantage of it you’ll see there is a lot more it can do.

And all that was done to get you here. Lazy initialization is part of the creational patterns from GoF. But it’s implementation is done using the Proxy design pattern. Lazy<T> uses the proxy design pattern for controlling access to the value of the instance. At it’s most generalized definition, the proxy design pattern “is a class functioning as an interface to something else.” It’s definition is incredibly broad. In addition to Lazy, Facade, Flyweight and Adapter patterns could all also be called types of proxy patterns, though that is only in the loosest sense of the definition. Generally proxy is considered applicable where there is a heavy expense or long load time to initializing or constructing an object.

Imagine if you are working with images. Most of the time you are looking at the meta-data about the image, size, date created, etc… This is so you can sort them, organize them, move them around. Sure, occasionally you want to open the image but this is an expensive task that could eat a lot of memory. To handle this scenario you create a “meta-image” object (or proxy). This provides for all the information about the image without having to load it into memory. Then, when the code needs the image, the “meta-image” object could provide for the ability to retrieve the real image and thus you have your proxy design pattern.

Thanks for reading,
Brian