How to add active directory (AD) security to WCF services with attribute?

If you are using WCF web services with active directory (AD) you may want to have a more atomic authorization process than setting the security by IIS. You may want to allow for specific method some group when some other may only have access to others.

The first step is to create a custom attribute. This example show you how to add a single role but you could modify this code to allow multiple roles.

public class SecureOperationAttribute : Attribute, IOperationBehavior
{
	public string Role { get; set; } 
	public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters){}
	public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)	{	}
	public void Validate(OperationDescription operationDescription)	{}
	public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
	{

		dispatchOperation.Invoker = new SecureOperationInvoker(Role, dispatchOperation);
	}
}

Once the attribute is set you need to create the invoker.

public class SecureOperationInvoker : IOperationInvoker
{
	private readonly IOperationInvoker _baseInvoker;
	private readonly string _operationName;
	private readonly string _role;

	public SecureOperationInvoker(string  role, DispatchOperation operation)
	{
		_role = role;
		_baseInvoker = operation.Invoker;
		_operationName = operation.Name;
	}

	public object Invoke(object instance, object[] inputs, out object[] outputs)
	{
		if (!UserIsInRole(_role))
		{
			throw new FaultException(string.Format("Authentification fail. The operation '{0}' requires the role '{1}'.", _operationName, _role),									new FaultCode("Authentification"));
		}
		return _baseInvoker.Invoke(instance, inputs, out outputs);
	}

	public object[] AllocateInputs()
	{
		return _baseInvoker.AllocateInputs();
	}

	public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
	{
		return _baseInvoker.InvokeBegin(instance, inputs, callback, state);
	}

	public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
	{
		return _baseInvoker.InvokeEnd(instance, out outputs, result);
	}

	public bool IsSynchronous
	{
		get
		{
			return _baseInvoker.IsSynchronous;
		}
	}
	
	public bool UserIsInRole(string role)
    {
        var winPrinc = new WindowsPrincipal(OperationContext.Current.ServiceSecurityContext.WindowsIdentity);
        return winPrinc.IsInRole(role);
    }
}

Of course, this example a small representation of what should have been done in a real system. In fact, the UserIsInRole shouldn’t be hardcoded to use WindowsPrincipal. It should be injected to be able to test without having to use WindowsPrincipal. Also, the role variable may in fact not be exactly the name of the active directory (AD) group, so you may need to inject also a mechanism to translate the role used by the attribute to the AD group.

Here is how to use the attribute over your WCF contract.

[ServiceContract]
public interface IMyEntityXYZ
{
	[OperationContract]
	[SecureOperation(Role = "Admin")]
	void Action(DTOXYZ[] xyz);
}

What I like is that you can set the security on the contract. It’s simple for the maintenance cause the operation signature contains who has access the the method defined. It’s also easy to test if you are using injection to create a stub method for the validation of the role.

Having a menu at the top of the screen with inner anchor

If you want to have a menu that will change what is selected depending of where you are on the screen, this can be done. First, you need to define your menu. Second, you need to have anchor inside your webpage. This is done by setting id to some element of your page. The example below has set id to 3 links. We could have set the id to H1 tag also.

<ul id="top-menu">
  <li class="active">
    <a href="#">Home</a>
  </li>
  <li>
    <a href="#header1">Header 1</a>
  </li>
  <li>
    <a href="#header2">Header 2</a>
  </li>
  <li>
    <a href="#header3">Header 3</a>
  </li>
</ul>

<a id="header1">This is my header 1</a>
<p>Text here ...</p>
<a id="header2">This is my header 2</a>
<p>Text here ...</p>
<a id="header3">This is my header 3</a>
<p>Text here ...</p>
​

The next step is to write some Javascript code that will use the scroll position to know what is the active anchor. The Javascript will also verify if a link is clicked.

var lastId,
    topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({ 
      scrollTop: offsetTop
  }, 300);
  e.preventDefault();
});

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;
   
   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   
   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href=#"+id+"]").parent().addClass("active");
   }                   
});​

Finally, the last step is to set the CSS to have a fixed menu that will stay at the top of the screen.

body {
    height: 6000px;
}

#top-menu {
    position: fixed;
    z-index: 1;
    background: white;
    left: 0;
    right: 0;
    top: 0;
}

#top-menu li {
    float: left;
}

#top-menu a {
    display: block;
    padding: 5px 25px 7px 25px;
    -webkit-transition: 1s all ease;
    -moz-transition: 1s all ease;
    transition: 1s all ease;
    border-top: 3px solid white;
    color: #666;
    text-decoration: none;
}

#top-menu a:hover {
    color: #000;
}

#top-menu li.active a {
    border-top: 3px solid #333;
    color: #333;
    font-weight: bold;
}

#header1{
    position: absolute;
    top: 400px;
}

#header2{
    position: absolute;
    top: 800px;
}

#header3{
    position: absolute;
    top: 1200px;
}
​

Here is an example, the code is pretty the same as here. I have adapted the code here for this blog. The credit goes to the person who has posted it on JsFiddle.

If you want to have an existing website that use that technic, you can go see http://letsmake.github.com/bettertogether/ which use this type of menu and effect.

Entity Framework and conversion of a datetime2

Have you ever got a conversion error when saving an entity with Entity Framework? Even with Entity Framework 5.0, you may receive the following error message that the value is out of rage.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.

This is the case if you have a date time set to 0001-01-01 because it’s out of range for SQL Server (even with Sql Server 2008 R2). In fact, SQL Server date can have a date only after the year 1753.

datelogo

The solution to this problem is to set a property date or to make nullable this field in the database and into your entity. This way, you could set to null if the date is not set. Otherwise, you can use instead of 0001-01-01 another date has a “not set date” which is over 1753-01-01.

How can I run an update on specific properties for detached objects?

In some scenario you will want to update a specific property but not others. This can be for security reason or for performance reason. In either case, the goal is to update only specific property of your entity. In Entity Framework, this can be done by specifying to the database context (dbcontext) the property status. Each property does have a IsModified property that can be set to true or false.

context.Entry(yourObject).Property(u => u.YourProperty).IsModified = true;

Of course, if your object is from view, this one is not known by Entity Framework’s database context and will require to attach it first.

using (var entities = new MyDbContext())
{
    var entity = new YourEntity {Id = id, Name="Test"};
    entities.YourEntities.Attach(entity);
    entities.Entry(entity).Property(e => e.Name).IsModified = true;
    entities.SaveChanges();
}

This will save YourEntity entity but only change the Name property. This is quite useful in scenario where you do not want the user to hack a web form to add properties that you doesn’t want to be read by Entity Framework.

By specifying which property that is modified, you tell Entity Framework to generate the SQL with only the “Set” for them. For example:

UPDATE YourEntity
SET Name = "Test"
WHERE Id = 123;

Finally, you may want to close the automatic validation if you are using the validation mechanism. This can be done by setting the ValidateOnSaveEnabled to false.

entities.Configuration.ValidateOnSaveEnabled = false;

The reason is that since not all the object is loaded, you may have some validation on field that should be required that isn’t at this time. To temporary disable the validation, use ValidateOnSaveEnabled. Of course, set it back to true once the save changes is done. You can find an example on my blog concerning the ValidateOnSaveEnabled.

Asp.Net MVC and the ViewData’s TemplateInfo

The TemplateInfo contains an interesting method which is HtmlFieldPrefix property. This property gives the same information than the method GetFullHtmlFieldName(string.Empty).

What is interesting is that from an editor template you can know the property name which is sometime primordial if you want to build your editor or display template. This is required to be able to bind with the ModelBinder back the information to the server once the user will submit the page back to the server.

For example, if you have a special editor template for a string, you can add on your property (usually over the property of your view model or model) the UIHint to make a link between the property and the template. Then, in the template you could create your control.

@model string

@{
    var controlPropertyName = ViewData.TemplateInfo.HtmlFieldPrefix
    <input id="@controlPropertyName" name="@controlPropertyName" value="...">
    <input id="...............
}

The short snippet above show you what from a single property, you could have multiple input with different names and the one that will be bound will be the one that came from the ViewData.TemplateInfo.

Having several input may be something required in scenarios of multiple list of elements that needs to be selected for example. Let say that you have a textbox which can be loaded from a list of value. The template will contain the input with the property name to be bound later to the view model (or model) and others input are there only to select a possible value (via Javascript).

How to rename complex type to not having the prefix of the class name

Entity Framework has a standard with the naming of column. This is also the case with complex type which will be added to every tables where complex type are used by entities. By default, Entity Framework will concatenate the name of the complex type with an underscore and the name of the property.

If you prefer not having complex type name, you can simply specify the column name you desire.

    modelBuilder
         .ComplexType<Audit>()
         .Property(type => type.CreatedBy)
         .HasColumnName("CreatedBy");

In the database instead of having a field with “Audit_CreatedBy” you will have only “CreatedBy”. This may be useful in some situation, but by experience it’s easier to do the mapping between complex type when you keep the prefix. It’s up to you, and your coding/database standard, to figure out if it’s appropriate or not.

Using Service Trace Viewer Tool to debug WCF service

Microsoft provides a free tool to test your WCF service. This tool let you see a lot of thing that you can define at which level you want to see.

The first step to configure the tool is to go inside your service project and open the configuration file.

You should add into the Configuration tag the code below:

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing" 
                    propagateActivity="true">
            <listeners>
               <add name="sdt" 
                    type="System.Diagnostics.XmlWriterTraceListener" 
                    initializeData= "yourFileName.log" />
            </listeners>
         </source>
    </sources>
</system.diagnostics>

Your file can contain any extension. The tools be default will search for few ones but you can at the end select All and see every extensions.

fileExtension

You can also specify to log only error instead of information. ActivityTracing will trace every activity which can be heavy on the log file.

To use this tool, open a developer console and type : SvcTracerViewer.

svctracer

A windows application will start and will let you select your tracing file and apply several filters.

svctracerTool

From here you should be able to get what’s wrong with your WCF without having to attach any process to a remove WCF service.

How to use Microsoft Data Service OData with Unity

If you want to use Unity with a Microsoft Data Service, you need to setup your ioc container once and the perfect time to do it is in the startup. OData service doesn’t have global.asax, neither does it have a ServiceHostFactory where you could setup your container.

With Microsoft Data Service (OData) you want to setup your Unity container with the method CreateDataSource which is available since you must inherit from DataService.

public class MyDataService : DataService<MyContext>
{
    public UnityContainer Container { get; set; }

    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        config.UseVerboseErrors = true;
    }
    protected override ODataDbContext CreateDataSource()
    {
        Container = new UnityContainer();
        Bootstrapper.Initialise(Container);
        return new MyDataSourceContext(Container.Resolve<IMyInterface>());
    }
}

As you can see, you just need to define your UnityContainer as a property to your class (or you could use an attribute) and then initialize it inside CreateDataSource method. Not only you can initialize your container here, but you can override the one defined in DataSerivce to use yours (MyDataSourceContext) which use unity for its parameters.

So, if you have a context for test and for your Data Service, then you could simply put any of the two in the class signature : public class MyDataService : DataService, and defined the real context to use later in the override method. The main advantage is that you can inject with Unity (or any ioc container you use) classes to you context.