Archive

Archive for April, 2011

What’s new in Visual Studio 2010 SP1

April 27, 2011 Leave a comment

I had a great time presenting to the Charlotte Enterprise Developers Guild last night. Here is a link to the slides and samples.

Thank you to everyone who showed up!

Using Behaviors and Triggers in Xaml

April 23, 2011 Leave a comment

I had a great time presenting to the WNC .NET Developers Guild last night. Here is a link to the slides and source code.

Hope you enjoy and thank you to those who came out!

What’s New In Visual Studio 2010 SP1

April 13, 2011 Leave a comment

I will be doing a presentation on Tuesday, April 26 at the Charlotte Enterprise Developers Guild. Here is a summary of the presentation:

What’s new in Visual Studio 2010 SP1 and making it work for you. If you didn’t know, Visual Studio SP1 was released the beginning of March and it is packed with a lot of good stuff. We will take a look at some of the new features and bug fixes. Also, we will review the extensibility model that Visual Studio 2010 provides and briefly look at some of the more popular extensions available. If you are a Silverlight or web developer, you will want to learn how you can now use IIS Express 7.5 instead of the Cassini as your debugging host. If you have very large Entity Framework models, you will want to look at the improvements SP1 did to reduce the wait time to load the designer. We will also cover authoring your own snippets to continue to make you more efficient and effect in your work place. We all use Visual Studio, let’s see how we can leverage what’s there and get the most out of the best development environment on the market!

Looking forward to it!

Categories: English Tags: ,

Using Behaviors and Triggers in Xaml

April 13, 2011 Leave a comment

I will be doing a presentation on Thursday, April 21 at the WNC .NET Developers Guild. Here is a summary of the presentation:

We will review what Behaviors and Triggers are all about. We will then discover how we can use them and see how they can enable us as developers. We will also discuss how Behaviors and Triggers allow us to develop following the Model-View-ViewModel (MVVM) pattern. Finally, we will dive into code and examine some common behaviors and triggers that we can use in our line of business applications.

Looking forward to it!

Is your DomainService slow on the first call but not afterwards?

April 7, 2011 1 comment

For the past three years, I have been working on a line of business application targeted to manage and run cities and towns. As you can imagine this has a very large data model and it continues to grow. One of the challenges of using Silverlight and Entity Framework over WCF RIA Services is that as the model grows the application seems to get slower and slower for the initial data request of a Domain Context. There are some very cool tricks that you can do to pre-compile your views so that your initial data request is no slower than any other request.

I am going to show you a couple approaches that are available to you right now and review each of them with pros and cons to each.

The first approach comes from a MSDN article How to: Pre-Generate Views to Improve Query Performance and does a great job at walking you through the steps required to get this accomplished. I am not going to go into the steps required for this approach but I believe that this approach involves too much ceremony and configuration in order for it to be the best choice. Here are some of my thoughts as to why I don’t like this approach:

  • I don’t like the requirement of needing to have a pre-build event. As you have more .edmx files this entry area becomes very cumbersome.
  • I don’t like that I need to change the default behavior of the .edmx model Metadata Artifact Processing to Copy to Output Directory. As more and more .edmx files are needed it is very easy to forget this step.
  • Because you have your model being copied to the output directory, you need to bring in the .csdl, .ssdl, and .msl files from the output directory and add each of them as an Embedded Resource. Once you do this you will also need to change your connection string as indicated in the article accordingly.

Even though this isn’t my favorite approach, it works and does a great job of pre-compiling your views.

If you have already read the first article, you will notice that it points to another option, How to use T4 template for View Generation. This approach uses T4 templates to provide the pre-compiled views. The T4 templates are available for download from the link provided. This method has none of the negative points that I mentioned in the first article. You have to be sure that when you bring in the T4 template that you name it the same as your model, e.g. .Views.tt. You must also be sure that the file that is generated is included as part of your project. I like this approach many times over the previous approach since it doesn’t involve as much ceremony and configuration to get it working. NOTE: If you have updated your Entity Framework model and DomainService, you need to be sure to remember to right-click your .Views.tt file and choose “Run Custom Tool” to make sure that your pre-compiled views are up to date.

You are now armed with enough information to go and pre-compile your views and make your application run quickly again. I spent quite a bit of time researching and looking for good blog posts on this and want to list a couple of them for you here so that you can gain some understanding when and where you will actually see some dividends from all of your efforts based on the size of your model.

The following is a table of links that have the name of the post and a description of what it is about:

Link Description
Isolating Performance with Precompiled/Pre-generated Views in the Entity Framework 4 This post goes into great detail analyzing sample data and providing benchmarks on performance.
Solving the “No logical space left to create more user strings” Error and Improving performance of Pre-generated Views in Visual Studio .NET 4 Entity Framework Discusses potential issues with the pre-compilation process and shows a way to improve on performance along with providing a tool (MakeRes.exe) to get this accomplished.
Connection Strings MSDN article explaining Entity Framework connection strings. I used this when I was working on the first implementation. I also dynamically create my connection strings instead of using the web.config file so this was useful.
EDM Generator (EdmGen.exe) MSDN article explaining the use of the EdmGen.exe tool.
How to: Use EdmGen.exe to Generate the Model and Mapping Files MSDN article walking you through an actual generation of the .csdl, .ssdl, and .msl files.

I recommend that if you are planning on pre-compiling your views, you should also consider using the MakeRes.exe tool and use the dictionary based solution instead of the default views that are generated for you.

That is all there is to it. You will be happy to know that you will not have to make any changes from your client code as all this happens on the server.

I hope this helps out and thanks for reading…

Getting something better than “Server not found.” from WCF in Silverlight

April 6, 2011 3 comments

When developing applications in Silverlight it is inevitable that you will need to perform a request back to the server for data or processing. The common practice is to use Windows Communication Foundation (WCF). I find that WCF usually handles all of my needs and it works well when everything is happy and just right. However, if anything is not in its correct place, we can have tons of problems. Worse yet, we get your all time favorite message back in Silverlight stating:

“Server not found.”

Basically, WCF is telling us to go screw ourselves but in a much more politically correct way. Well there are several ways to attack this problem but I want to show you what I have come to love and use for all my projects involving WCF and Silverlight.

To give us some background, please review the following MSDN reference concerning Creating and Handling Faults in Silverlight. This article explains why we get our beloved message from WCF and what we can do about it. I think this is a must read for anybody wanting to understand what is going on and how they can go about fixing it themselves. I don’t think this is be the best solution but I do think it is a great reference. The reason for looking for something else is that I would like a solution that is a little easier to use and has less configuration required. I tend to follow this pattern because I have clients that want elegant solutions but they want it to be the least disruptive to their development process as possible.

Let’s move to the next blog post that I find very instrumental in dealing with exceptions in WCF. Oleg Sych wrote an excellent article, Simplifying WCF: Using Exceptions as Faults, back in 2008 that I believe is still very pertinent for us today. His solutions is very similar to the MSDN article that we already looked at but I believe it is more comprehensive and provides a good code base with which to use if you wanted to take his approach. I like what I read here but I still wanted something a little less intrusive from the perspective of ceremony and configuration.

This leads us to our last blog post. Here we find Jeroen Bernsen’s entry WCF ExceptionHandling in Silverlight. Like the other two articles, this post tries to solve the problem of dealing with exceptions thrown in WCF and how to get them back to the client in a friendly and easy way. If you read his post, you will see that you only need to create few objects to get our solution working and there is no need to modify your weg.config like in the other solutions. This is the reason why I like this solution the best.

I am going to provide the code below but you can also just follow along Jeroen’s post if you like.

The following class tells WCF to send fault messages with a 200 instead of a 500 response code. This change enables Silverlight to read the body of the message.

public class WcfSilverlightFaultBehavior : IDispatchMessageInspector
{
	public void BeforeSendReply(ref Message reply, object correlationState)
	{
		if (reply.IsFault)
		{
			HttpResponseMessageProperty property = new HttpResponseMessageProperty();

			// Here the response code is changed to 200.
			property.StatusCode = System.Net.HttpStatusCode.OK;

			reply.Properties[HttpResponseMessageProperty.Name] = property;
		}
	}

	public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
	{
		// Do nothing to the incoming message.
		return null;
	}
};

Next we have a sealed class that basically creates our attribute for using the previous class.

public sealed class WcfSilverlightFaultBehaviorAttribute : WcfBehaviorAttributeBase
{
	public WcfSilverlightFaultBehaviorAttribute()
		: base(typeof(WcfSilverlightFaultBehavior))
	{
	}
};

As you can see this is our attribute definition. We are deriving from a base class which we will review shortly.

The next class implements the IErrorHandler and allows us to handle WCF exceptions and package them in a way that we can still read on the client side.

public class WcfErrorBehavior : IErrorHandler
{

	void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
	{
		try
		{
			// Add code here to build faultreason for client based on exception
			FaultReason faultReason = new FaultReason(error.Message);
			ExceptionDetail exceptionDetail = new ExceptionDetail(error);

			// For security reasons you can also decide to not give the ExceptionDetail back
			// to the client or change the message, etc
			FaultException faultException =
				new FaultException(exceptionDetail, faultReason,
					FaultCode.CreateSenderFaultCode(new FaultCode("0")));

			MessageFault messageFault = faultException.CreateMessageFault();
			fault = Message.CreateMessage(version, messageFault, faultException.Action);
		}
		catch
		{
			// Todo log error
		}
	}

	///
	/// Handle all WCF Exceptions
	///
	bool IErrorHandler.HandleError(Exception ex)
	{
		try
		{
			// Add logging of exception here!
			Debug.WriteLine(ex.ToString());
		}
		catch
		{
			// Todo log error
		}

		// return true means we handled the error.
		return true;
	}

};

IErrorHandler has to methods that we must implement: ProvideFault and HandleError. You can read more on this interface here.

HandleError is just a boolean method that indicates whether or not a Fault message has already been generated (true) or for WCF to do its normal processing (false).

ProvideFault is a void method that allows us to package the fault exactly how we want to. This is very nice and gives us all the flexibility we need to customize or change how we wish to package our faults.

Next we have a sealed class that basically creates our attribute for using the previous class.

public sealed class WcfErrorBehaviorAttribute : WcfBehaviorAttributeBase
{
	public WcfErrorBehaviorAttribute()
		: base(typeof(WcfErrorBehavior))
	{
	}
};

As you can see this is our attribute definition. We are deriving from a base class which we will now review.

public abstract class WcfBehaviorAttributeBase : Attribute, IServiceBehavior
{
	private Type _behaviorType;

	///
	/// Constructor
	///
	/// <param name="typeBehavior" />IDispatchMessageInspector, IErrorHandler of IParameterInspector
	public WcfBehaviorAttributeBase(Type typeBehavior)
	{
		_behaviorType = typeBehavior;
	}

	void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription,
		System.ServiceModel.ServiceHostBase serviceHostBase,
		System.Collections.ObjectModel.Collection endpoints,
		System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
	{
	}

	void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription,
		System.ServiceModel.ServiceHostBase serviceHostBase)
	{
		object behavior;
		try
		{
			behavior = Activator.CreateInstance(_behaviorType);
		}
		catch (MissingMethodException e)
		{
			throw new ArgumentException("The Type specified in the BehaviorAttribute " +
				"constructor must have a public empty constructor.", e);
		}
		catch (InvalidCastException e)
		{
			throw new ArgumentException("The Type specified in the BehaviorAttribute " +
				"constructor must implement IDispatchMessageInspector, IParamaterInspector of IErrorHandler", e);
		}

		foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
		{
			if (behavior is IParameterInspector)
			{
				foreach (EndpointDispatcher epDisp in channelDispatcher.Endpoints)
				{
					foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations)
						op.ParameterInspectors.Add((IParameterInspector)behavior);
				}
			}
			else if (behavior is IErrorHandler)
			{
				channelDispatcher.ErrorHandlers.Add((IErrorHandler)behavior);
			}
			else if (behavior is IDispatchMessageInspector)
			{
				foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
				{
					endpointDispatcher.DispatchRuntime.MessageInspectors.Add((IDispatchMessageInspector)behavior);
				}
			}
		}

	}

	void IServiceBehavior.Validate(ServiceDescription serviceDescription,
		System.ServiceModel.ServiceHostBase serviceHostBase)
	{
	}

};

As you can see in the code, this class derives from Attribute so that we can use it as an Attribute and also implements the IServiceBehavior interface. By implementing the IServiceBehavior interface, we no longer need to do any ceremony in the weg.config file. We have a single Type variable that allow us to be flexible from our classes that derive from us. As long as they pass in the type of behavior we handle the rest in the base class. IServiceBehavior has three methods: AddBindingParameters, ApplyDispatchBehavior, and Validate. You can read more on this interface here.

AddBindingParameter is used to pass to a binding element the custom information for the service so that it can support the service correctly.

ApplyDispatchBehavior is used to change run-time property values or insert custom extension objects.

Validate is used to examine the description and validate that the service can execute properly.

The method that we are interested in is the ApplyDispatchBehavior. First we try to create an instance of the underlying type that was passed in the constructor. Next we iterate over all of the ChannelDispatchers. Based on what type of behavior object we have, we determine what needs to happen in the current iteration of the ChannelDispatcher.

All of these classes will live on the server side and will need to be accessible from your WCF service.

Here is what you need to do to mark up your service:

[WcfErrorBehavior()]
[WcfSilverlightFaultBehavior()]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class TestService : ITestService
{
	public WcfErrorBehaviorAttribute()
		: base(typeof(WcfErrorBehavior))
	{
		public int DoSomething()
		{
			...
		}
	}
};

Congratulations, you are done! You can now have all of those nasty exceptions from WCF finally show up in your Silverlight client. Here is a sample screen shot of an exception thrown due to bad username and password to SQL Server before we apply the attributes:

Now with our attributes applied:

This makes all the difference! Hope this helps and again I want to stress that the credit of this blog goes to the articles that we previously mentioned.

Entity Framework, LINQ, and WCF RIA Services ordering tip

I thought I would share the following scenario with the hope that you can learn from my mistakes and do better. I have a screen that loads an account record. Based on that account, a hierarchical tree is loaded with supporting information in the bottom portion of the screen. The following is a screen shot of the screen with some really bizarre ordering in the tree:

If we look at the query that was used to load the hierarchy, we see the following:

[Query()]
public IQueryable ReturnBillsAndReturnsByOrganizationId(int organizationId)
{
	return this.ObjectContext.Organization.Where((c) => c.OrganizationId == organizationId)
	    .OrderBy(x => x.SubsystemName)
	    .OrderBy(x => x.BillType)
	    .OrderByDescending(x => x.FiscalYear)
	    .OrderByDescending(x => x.FiscalPeriod);
}

What I am trying to do is sort the tree in the following order:
Subsystem Name (ASC), BillType (ASC), Fiscal Year (DESC), Fiscal Period (DESC). Perhaps on first glance the syntax looks correct but if we refer to the documentation we learn some important pieces of information:

MSDN Queryable.OrderBy

MSDN Queryable.ThenBy

If we review the documentation, we will see that anytime we call OrderBy or OrderByDescending we get an IOrderedQueryable object. This means that every time we call OrderBy or OrderByDescending we are re-creating the IOrderedQueryable object. Clearly, this is not what we want to do.

If we review the documentation for ThenBy, we see that it requires a parameter of type IOrderedQueryable as the type of object to perform the operation. It then returns a now fully sorted object type of IOrderedQueryable. This is exactly what we are looking for. This works for both the ThenBy and ThenByDescending operations.

Thus it is necessary that our query looks like this:

[Query()]
public IQueryable ReturnBillsAndReturnsByOrganizationId(int organizationId)
{
	return this.ObjectContext.Organization.Where((c) => c.OrganizationId == organizationId)
		.OrderBy(x => x.SubsystemName)
		.ThenBy(x => x.BillType)
		.ThenByDescending(x => x.FiscalYear)
		.ThenByDescending(x => x.FiscalPeriod);
}

Finally, with this change, our tree is now in the correct order and all is good with the universe:

It is very easy to assume that the logic of the syntax for the ordering is correct when trying to force it to work like T-SQL. This isn’t always the case and we must be careful or our results will be entirely not what we are looking for.

Hope this helps….