My Time As a Microsoft MVP

In the early 2000’s, I was working for a State agency in Pennsylvania in a .NET development role.  I’ve always been fascinated by programming on many levels: I really liked to learn the nuts and bolts of the framework, as well as the ability to create something – albeit digitally.  I tried to learn as much as I possibly could; I’d read tech books, read web sites, and post on forums.  I was pretty active specifically on the ASP.NET forums.

Sometime in 2007, I received an email from Microsoft in regards to the MVP program!  I was shocked when I got the email.  I spent a lot of time there, posting questions in hoping to gain insight and trying to provide answers to assist the technical community.  When the honor was confirmed, I was really appreciative of it; it was a great honor.

Fast forward 10 years later:

mvptenyears

I’ve been very blessed individual.  I’ve gotten to offer my time and skills to the community.  I’ve gotten to meet individuals at Code Camps or Give Camps.  I’ve gotten to write for DevProConnection Magazine, ASP Alliance, DotNetSlackers, DotNetJohn,  this blog, and other places.   I considered speaking for Pluralsight, but I’m not the greatest speaker.  Additionally, I’ve gotten to be involved in interesting projects over the years, as I shifted from government work to consulting work to product development.  I’ve gotten to help analyze and solve other people’s technical (and sometimes personal) problems.

Life really comes at you fast some times.  It doesn’t seem like long ago that our 3 children entered our world, but the facts remain the same (ages 11, 9, 7).  We adopted our beautiful daughter from China, and we are in the process of adopting our son (also from China).  My kids have been involved in school plays, baseball games, soccer practices and games, basketball games, holiday events, church activities, school events and more.  As my career progressed, my workload got bigger, my involvements became greater, and my stresses increased.  I burned out a few times along the way, my free time dwindled between work, an ever growing family, and general increased demands.

Ten years was my run as a Microsoft MVP.  I was informed that I will not be renewed.  Microsoft was great to me and gave me many opportunities during that ten years; I am forever grateful for that.

Advertisements

Customizing the EF Entity Templates

The nice thing about Entity Framework is that anytime you are using one of the entity template generation capabilities, they are pretty easily customizable. This, of course, means that you are NOT using the pure code-first API most likely (however, to an existing database defines a T4 template). In this blog post, we’re going to quickly update the T4 template to change the default rendering:

using System;
using System.Collections.Generic;
    
public partial class State_LKP
{
    public int StateID { get; set; }
    public string StateCode { get; set; }
    public string StateName { get; set; }
}

To add additional information that the application can later use for metadata purposes, such as the following:

using System;
using System.Collections.Generic;
    
public partial class State_LKP
{
    public const string StateID_Name = "StateID";
    public int StateID { get; set; }
    
    public const int StateCode_MAX_LENGTH = 10;		
    public const string StateCode_Name = "StateCode";
    public string StateCode { get; set; }
    
    public const int StateName_MAX_LENGTH = 50;
    public const string StateName_Name = "StateName";
    public string StateName { get; set; }
}

Notice that each column has a constant defining the name, as well as a constant defining it’s max length defined in the database (if a string).

To do this, we need to open up the .tt file that generates each of the entities. In my version, around line 66, we have the following snippet.

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    foreach (var edmProperty in simpleProperties)
    {
#>
    <#=codeStringGenerator.Property(edmProperty)#>
<#
    }
}

Notice that this snippet loops through each of the simple properties (the properties defined one for each column) and renders out a definition (note codeStringGenerator is a class defined in the T4 template that defines all of the markup. I didn’t choose to modify that here). To add the name constants and the max length constants, the updated samples were changed to the following code sample. Comments below indicate the changes made.

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    //edmProperty of type EdmProperty
    foreach (var edmProperty in simpleProperties)
    {
        //Check max length - if any max length, then write out a constant
	 if(edmProperty.MaxLength.HasValue)
                {
                        #>
 
                        public const int <#= edmProperty.Name #>_MAX_LENGTH = 
                            <#= edmProperty.MaxLength.Value #>;
 
                        <#
                }	


         public const string <#= edmProperty.Name #>_Name = 
               "<#= edmProperty.Name #>";

    <#=codeStringGenerator.Property(edmProperty)#>
    <#
    }
}

Here we add constants to the output of the properties and everything generates great. You may say it would be better to use attributes; that is possible as well, but for that I’d recommend editing the CodeStringGenerator class (in the T4 template) and update the Property method directly instead.

The T4 template is available here: http://pastebin.com/42NiuwDE

Discussing ASP.NET MVC Model Binding With Hidden Data

If you have taken over an MVC application, you may have come across a dilemma like the following. Notice that in a view, within a form, you’ll see a group of hidden fields mixed in with a form like the following.

Html.HiddenFor(i => i.ContactID)
Html.HiddenFor(i => i.ContactTypeID)
Html.HiddenFor(i => i.ContactDescription)
Html.HiddenFor(i => i.ContactTypeDescription)
Html.HiddenFor(i => i.OrganizationID)

Html.LabelFor(i => i.OrganizationName, new { @class = "control-label" }) Html.TextBoxFor(i => i.OrganizationName, new { @class = "form-control" })
@* and so on *@

My example had five hidden fields, but I’ve seen a lot more. These fields are not useful to the form per se; the user doesn’t enter them. However, the information is important to the records about to be updated in the database, and thus are included in the form as hidden fields for that reason. However, another reason is it acts as a quasi-ViewState mechanism that makes it very easy to replenish the following model:

public class ContactInfoModel
{
    public int? ContactID { get; set; }

    public int? ContactTypeID { get; set; }

    public string ContactDescription { get; set; }

    public string ContactTypeDescription { get; set; }

    public int? OrganizationID { get; set; }

    public string OrganizationName { get; set; }

    /* and so on */
}

[HttpPost]
public ActionResult Contact(ContactInfoModel model)
{
 ...
}

While OrganizationName and the other unlisted properties came from the form, the first five properties (and potentially more) are stored in the hidden field. The hidden field makes it nice and easy to replenish this model, and than allow the developer to use the parameters in the post action. MVC does a very nice job posting the values back to the server and populating these properties.

However, notice I said before, that this was a ViewState-like solution? It’s not quite within the model of ViewState because all of the parameters are embedded in the form in clear text. In most systems, the user is required to login before they can ever get to a page that contains this type of information. Either way, the users have the tools (IE developer tools, Firebug) to inspect and change the values in the hidden fields if they so desired. That is where the danger can lie.

Here’s the other side of the conundrum: if we don’t reload the parameters, what do we do? If we didn’t include the hidden fields, the first five parameters are not loaded from the client and thus the model is partially replenished. In most cases, these pieces of information might not be needed anyway (with the exception of OrganizationID in our scenario).

The application can certainly requery the information it needs, but then the information gets reloaded on every postback, which can get more expensive. The application could also use Session to store the information fields too.

I’m not saying “NEVER use hidden fields”, but I’m debating the value of a large number of hidden fields for replenishing the model. I probably fit within the category of storing any relative information in Session or requerying the information from the database, depending on how much information we are talking about. What is your thoughts or preference? Using hidden fields, session, database?

Using Interfaces for ASP.NET MVC Model Binding

Sometimes you may want to support view reuse, where a partial view displays a portion of the application in a reusable fashion. Suppose you had the following entity which has a bunch of properties.

public class Customer
{
   public int CustomerID { get; set; }

   public string FirstName { get; set; }

   public string LastName { get; set; }

   public string AccountNumber { get; set; }

   .
   .
}

Suppose you wanted to use a PartialView because it was an AJAX widget with a JavaScript initialization script, and defining a reusable control made it really easy to support this. MVC defines a strongly typed model reference, so does that mean we have to bind the model directly to Customer, or define a custom type for an editor template?

We actually can use interfaces by adding the following:

public interface IAccountEntity
{
   string AccountNumber { get; set; }
}

We can define this in a partial view:

@model IAccountEntity

@Html.TextBoxFor(i => i.AccountNumber)

   $(function() {
      /* Registration Script */
   });

And then use it in our EditCustomer view, as a partial with the existing model:

@Html.Partial("EditAccountNumber", Model)

Since Model (of type Customer) is also IAccountEntity, this translates just fine with MVC. It works just as well when you use hierarchies too. For instance, Customer implements IAccountEntity, but what if we had a CustomerModel class above Customer like:

CustomerModel
     Customer : IAccountEntity
        AccountNumber

If EditCustomer view looks like the following:

@model CustomerModel
.
.

<div class="form-group">
   <label class="col-md-2 control-label">First Name</label>
   <div class="col-md-10">
       @Html.TextBoxFor(Function(i) i.Customer.FirstName)
   </div>
</div>
<div class="form-group">
   <label class="col-md-2 control-label">Last Name</label>
   <div class="col-md-10">
       @Html.TextBoxFor(Function(i) i.Customer.LastName)
   </div>
</div>
<div class="form-group">
   <label class="col-md-2 control-label">AccountNumber</label>
   <div class="col-md-10">
       @Html.Partial("EditAccountNumber", Model)
   </div>
</div>

Notice how the model is passed in directly; this won’t work for our scenario, because the EditAccountNumber expects an IAccountEntity, and requires that the partial be passed in this way:

@Html.Partial("EditAccountNumber", Model.Customer)

However, that doesn’t work for our needs, if our controller has a post operation of the following:

[HttpPost]
ActionResult Edit(CustomerModel model)
{
    if (string.IsNullOrEmpty(model.AccountNumber))
    {
      //This will always be the case, why?  See below
    }
}

Welcome to one of the challenges of MVC model binding. In the previous form, the first/last name and account number would post back to the server something like:

Customer__FirstName: BOB
Customer__LastName: SMITH
AccountNumber: ABC123

What needs to happen is the “AccountNumber” key also needs to be Customer__AccountNumber for it to successfully bind back to the server. You can add AccountNumber as a parameter to the post method, or we can add another interface that supports our hierarchy, and add this interface to the CustomerModel:

//Interface definition
public interface IAccountNumberModel
{
    IAccountNumberEntity Customer { get; set; }
}

//Update to the model class
public class CustomerModel : IAccountNumberModel
{

   public Customer Customer { get; set; }

   IAccountNumberEntity IAccountNumberModel.Customer { get; set; }

}

Here IAccountNumberModel has the same property name as CustomerModel; that’s important to make sure the model binding name structure matches. Now we can pass in the CustomerModel to the EditAccountNumber view with these modifications:

//EditAccountNumber
@model IAccountNumberModel

@Html.TextBoxFor(i => i.Customer.AccountNumber)
.
.

//EditCustomer:
.
.
@Html.Partial("EditAccountNumber", Model)

Since CustomerModel implements IAccountNumberModel, and this matches the type of model on our partial view, everything binds correctly.

Some Considerations For MVC 6 Client Attributes

One of the new features coming is the addition of Tag Helpers, which are server-side attributes that get interpreted and translated into a client-side attributes. This transforms the previous approach we used to use of the following:

@Html.ActionLink("Text", "Action", "Controller")
@* OR *@
<a href="@Url.Action("Action", "Controller")">Text</a>

Both of the above examples translate to the same result; Html.ActionLink builds a link with a single HREF attribute. One of the changes available with tag helpers is to instead use new “asp” prefixed attributes to perform the rendering:

<a asp-controller="Controller" asp-action="Action">Text</a>

These attributes get translated to a href client-side attribute with the appropriately generated URL. There are a variety of tags available that support server-side attributes, outside of the hyperlink. For instance, the form and label tags also support attributes, as well as others that you can find more at the following resources:

There is lots of good content out there on the subject already. I wanted to discuss in this post the merits of tag helpers, and discuss some of the pros and cons. Whatever is discussed with tag helpers, it’s important to remember that you can always utilize the old way of developing the user interface. To my knowledge, that isn’t going away.

It is important to remember that tag helpers are server-side; they still run server-side code, and so you cannot use asp attributes at client time. The client-side interpreters do not know of these attributes, but the server does as in this post. So if you like to use jQuery or Kendo UI templating, tag helpers won’t really give you much, as you have to render the link anyway. Now, there are server-side tricks to rendering client content that can be utilized, which I have written about in the past on this blog, and so there are ways to leverage that depending on what you are doing.

You also have to be careful which attributes you use where, as certain attributes are supported for certain tags. I haven’t found a comprehensive list yet, other than the Mikesdotnetting post. So be careful as you use new attributes to account for that. Also, some properties define expressions to the field in the model that may contain additional information. For instance, the label may support a field to grab the display information. In this case, the attribute defines the name of the field to display information for, which corresponds to the property in the model. It will be interesting to see how Tag Helpers support deep nested models, and whether we need to render names like Customers[0].FirstName when working with lists. This is one area where the old tags make it a little more clear.

These are some preliminary ideas to think about; I’m sure I’ll be amending this post as I think of other considerations after publishing this post 🙂

Xamarin Forms Threading Fun

I’ve been trying out the async/await model in Xamarin Forms, and have had trouble getting it to work. It turns out there is great challenge in ensuring everything runs on the same thread. In this I learned a few lessons:

1) Make sure that once you start an operation asynchronously, make sure everything is also called in an async fashion. For instance, I had the following call hierarchy:

async LoginButton_Click
async HandleSignInCompleted(..);
async loginService.Login(..);
async HttpClient.PostAsync(..);

It’s important to make sure everything uses the async model, rather than calling the method directly. For instance, an async method can be called directly, or the results invoked directly with the .Result property on the Task. But don’t do it! Be consistent with the async/await setup.

2) Use ConfigureAwait(false)

The Task object has a ConfigureAwait method. I had success using it by applying it EVERYWHERE, on every async operation. In my above stack trace, this looked like:

async void LoginButton_Click //Since a button callback, can't define here
    async HandleSignInCompleted(..).ConfigureAwait(false);
       async loginService.Login(..).ConfigureAwait(false);
          async HttpClient.PostAsync(..).ConfigureAwait(false);

3) UI Synchronization

In my call stack, in the HandleSignInCompleted, there was a call to:

var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);

This failed with an Android error (tested on an Android device) stating that the view was modified on a different thread that the original, which makes sense since we are in the async thread. The solution to that was to wrap the call in a Device.BeginInvokeOnMainThread method call. This built up the UI for the Dashboard page in the main UI thread instead.

Device.BeginInvokeOnMainThread(() => {
var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);
});

Read more about BeginInvokeOnMainThread to understand the specifics, and why it may work in some situations and not others. So far that has been the tale of my adventures in asynchronous operations in Xamarin Forms. Hopefully this might help you as you use Xamarin Forms.

TEF Available As A Nuget Package

I’ve added TEF as a Nuget package available for download in two flavors now:

Install-Package TEF

TEF is a PCL library which allows you to define types for exporting into a dependency injection container. Since it’s PCL, it can work in Silverlight, Xamarin.iOS, Xamarin.Android, and more.

Install-Package TEF.NET

This is a .NET 4.5 version that provides .NET framework specific add-ons, such as parsing the assemblies in the app domain.

Authenticating over AD with the ADMembershipProvider

Want to authenticate against AD but don’t want to use LDAP directly? Would you like to use the AD membership provider, but don’t want tied into the membership API? No problem! That’s because you can programmably create the membership provider, provide some configuration options, and then made an API call to check the login status. The code is very simply the following:

var membershipProviderName = "Provider"; // Does not need to be in web.config
var connectionStringName = "SomeConnectionString";
var config = new NameValueCollection();

config.Add("connectionStringName", connectionStringName);

var provider = new ActiveDirectoryMembershipProvider();
provider.Initialize(providerName, config);

var isValidUser = provider.ValidateUser(user, password);

And that’s all it takes. The provider name is the name you would normally see in the configuration file; we’re defining it during initialization. Next, we need to create configuration options. Our implementation only supplies the connection string name defined in the connection strings setting. Define a connection string, with the name supplied above, that points to the LDAP store. Note that no membership API needs to exist in the

Next, we create and initialize the provider, and use the provider to validate the credentials. Is there an expense to building this up every time? I haven’t tested it out, but logically it seems that would be the case. Just plan it’s use accordingly.

Entity Framework Table Tricks

I’ve seen out on the web quite a few questions about how to do this or that with Entity Framework, so I’d thought I’d write up a solution to various ways to work with tables and to customize entities.

Sets

Suppose we have a context with a Customers table; by default, the Entity Framework code generator generates code that allows the consumer to do the following.

var ctx = new EFContext();
ctx.Customers.Where(i => ..);

The Customers property is a DBSet object that is responsible for “table management”, which is not quite right but a good quick way to understand it. The DBSet is the primary mechanism for generating queries against the table and adding new objects to the table. Entity Framework code generators create wrappers around this object, but also expose the following methods in two forms:

public System.Data.Entity.DbSet Set(Type type);
public System.Data.Entity.DbSet Set();

Referring to a table generically using the set method comes in handy when you want to simplify your data access code. To explain what I mean, let’s look at a small sample. We may want to use the repository pattern like this:

public interface IRepository
 where T: class
{

    IEnumerable GetAll();

}

public class CustomerRepository : IRepository
{
   public IEnumerable GetAll()
   {
      var ctx = new EFContext();
      return ctx.Customers.ToList();
   }
}

Note how we write the code in each and every repository; we have 1 now, but as the system grows, each repository has to write this same code over and over again. Sure, we can generate it automatically, but we can also do this:

public abstract class BaseRepository : IRepository
{
   public IEnumerable GetAll()
   {
      var ctx = new EFContext();
      return ctx.Set().ToList();
   }
}

public class CustomerRepository : BaseRepository
{

}

Notice the set method usage and how this one common method prevents us from having to write common code. Now we have one method shared across all repositories. We could also use the other override like so:

ctx.Set(typeof(Customer));

Although, it’s far less flexible than the generic form. A lot of the common options are not available out-of-the-box. One important use you can use it to add objects to the database, however.

var customer = new Customer { .. };
ctx.Set(typeof(Customer)).Add(customer);
ctx.Set().Add(customer);

ctx.SaveChanges();

SaveChanges then commits any changed made, raising errors for any validations or update exceptions.

Using Interfaces

Using interfaces can add in some nice flexibility. Suppose we have an interface like this:

public interface IAuditEntity
{
   public DateTime Entered { get; set; }

   public DateTime? Updated { get; set; }
}

Supposing that all of your entities implement this interface, you can simplify your repositories by creating common code:

public abstract class BaseRepository
{

   public IEnumerable GetUpdatedSince(DateTime check)
      where T: IAuditEntity
   {
      var ctx = new EFContext();
      return ctx.Set().Where(i => i.Updated != null && i.Updated.Value > check);
   }

}

While the example above is not the most useful, it illustrates what can be done to create common routines in entity framework. Since Updated matches the name of a field in the table being queried, Entity Framework resolves this correctly; if the name doesn’t match, an exception will be raised saying the property defined in the expression doesn’t exist in the table.

Functions

What floored me though is through a method, Entity Framework can bridge the gap and provide common code. For instance, suppose we had entities like this:

public class Customer
{
   public string Country { get; set; }
}

public class Employee
{
  public string PrimaryCountry { get; set; }
}

We couldn’t create an interface with the name Country, because Employee doesn’t have a matching property. We could change the name, but for the sake of the example, let’s keep them different. Since property name mismatches cause errors, we can surprisingly use functions. An architect had shown me this and I was floored, simply because properties don’t work. But by doing:

public interface ICountry
{
   public string CountryExpression();
}

public class Customer : ICountry
{
   public string Country { get; set; }

   public string CountryExpression()
   {
      return this.Country;
   }
}

public class Employee
{
  public string PrimaryCountry { get; set; }


   public string CountryExpression()
   {
      return this.PrimaryCountry;
   }
}

And then doing the following in the query will work:

public IEnumerable GetByCountry(string country)
 where T: ICountry
{
  var ctx = new EFContext();
  return ctx.Set().Where(i => i.CountryExpression() == country);
}

An architect showed me this trick, and I was floored that it worked since properties don’t. Hopefully this post illustrated some tricks to using entity framework and reduce the overall coding needed.

ASP.NET MVC Dynamic Reference Data Loading

MVC, like any other language, is a tool that has plenty of capabilities when rendering client markup; one method call can render pages of client markup. Using a server-side approach can simplify some of the rendering of content needed. As a for instance, here is one common situation I often use a server-side approach to rendering content within an application. An application may have a Kendo DropDownList, which is highly dependent on a list of some data in JSON format. The initialization script looks like the following:

$("DropDownList").kendoDropDownList({
   dataSource [{ .. }],
   dataTextField: "Text",
   dataValueField: "Value"
});

Typically, the data source is some lookup data source; in most applications, lookup data typically contains a key and value. The dataTextField and dataValueField properties map to values within these It’s helpful to have lookup data that’s standardized, because it’s easy to create a helper function that does the following:

@Helper LookupData(IList data)
{
   return NewtonSoft.JSON.JsonConvert.SerializeObject(data);
}

This helper converts data to JSON, which is used in the script below.

$("DropDownList").kendoDropDownList({
   dataSource @LookupData(Model.CustomerTypes),
   dataTextField: "Text",
   dataValueField: "Value"
});

Here we take a collection of reference items and use that to convert it to JSON. Really, that approach may not be that useful, but where you can find use is if you have a common reference table loader object. Using this, the helper function can automatically retrieve a common dataset based on a given type of reference data:

@Helper LookupData(Type referenceType)
{
    var container = Framework.Container; // this is a singleton reference to the dependency injection container
    var referenceData = container.GetInstance(); //A utility class to load common reference data

    return JSONConvert.DeserializeObject(referenceData.GetValues(referenceType));
}

The reference data uses an IReferenceTableManager class to perform the work. Behind the scenes, this could be anything, including Entity Framework. Below is one possible solution:

public class ReferenceValue
{
    public int ID { get; set; }

    public string Text { get; set; }
}

public interface IReferenceTableManager { 
   IEnumerable GetValues(Type type);
}

public class EFReferenceTableManager : IReferenceTableManager {
  public IEnumerable GetValues(Type type)
  {
     var ctx = new EntityFrameworkContextInstance();

     //From a given type, there are multiple ways to get the data from the DB; I am not
     //aware of a way to query by type (at least easily). There may be a better way to do this,
     // but for the time being, the two possible ways to do query referenced data dynamically
     //by generics are: using reflection or, using a long if statement and type checking like:
     if (type.Equals(typeof(Countries))) {
       return ctx.Set().ToList();
     }
     else if (type.Equals(typeof(States))) {
       return ctx.Set().ToList();
     }
     .
     .
  }

}

Not the best implementation; I’m sure there is something better out there, but you get the idea as to how this dependency can now be implemented dynamically. However, the question most will have is whether this is scope creep on behalf of the view (as to whether this is a responsibility of the controller). It’s also possible to have the lookup helper examine a given model and extract the data from there too. There are multiple ways to solve this problem.