Enhancing strong typed views in ASP.NET MVC

I’ve added new constructs for replacing

< % Html.RenderPartial("~/Shared/LogOnUserControl.ascx", model); %>
 
with these
< % Html.RenderPartial().Shared.LogOnUserControl(model); %>
 
where model argument is strong typed of course. There are other overloads as well.

Notes:

  • due to IE7 formatting issues I am adding an extra space after < character
  • I can’t get rid of parenthesis after RenderPartial due to extension methods limitation (there are no extension properties)

For more details read my previous article Strong typing views in ASP.NET MVC. The new template is attached below.

StrongTypedViews.zip (2.60 kb)

Other related articles:

Strong typing routes in ASP.NET MVC

Strong typing routes in ASP.NET MVC

Let’s say you have Test action in Home controller like this:

public ActionResult Test(int id, int tubo)
{
return View("Index");
}

And you want to create a hyperlink to that action on your view. So, did you ever wonder why do you have to write code like:

< %= Html.ActionLink("Classic Action", "Test", "Home", new { tubo=8, id=77 }, null) %>

[Note: I had to insert a space after each less than character (<) becaue of formatting issues in IE7. For some reason the code disappeared when there was no space after <. Firefox didn't show any such issues. If you try running the code contained in the code snippets you'll have to remove those spaces.]

(I won’t even consider lambda version because it is awfully slow). This version has two problems:

  1. It isn’t strong typed by any mean.
  2. The anonymous class holding id and tubo values isn’t the best performer either.

To solve the second issue you might opt for RouteValueDictionary instead of anonymous class, like this:

< %= Html.ActionLink("Classic Action", "Test", "Home", 
new RouteValueDictionary {  { "tubo", 8 } ,{ "id", 77 } }, null) %>

This version is less readable but slightly better performer.

The bigger problem is the first one, which wasn’t possible to overcome, unless you wanted to get rid of performance (by using lambdas). Until now, that is. I created a solution that would provide best of both worlds: strong typing and performances.

< %= Html.LinkTestOnHome("TestLink", 8, 77)%>

Note the advantages:

  1. Parameters are strongly typed
  2. The most performing call (currently to ActionLink) is handled internally (with possibility to improve).

Sounds good? If yes, read futher.

Instructions

The generator comes in a form of DXCore/CodeRush plugin and there is a single requirement: you’ll need the best Visual Studio productivity tool CodeRush. Or even better, this plugin requires only DXCore, which is a free subset of CodeRush (untested scenario at this point though). In other words, this is a free lunch albeit you should really take a look at CodeRush and all of its super features. You won’t regret it.

Here are the steps to test it out:

1. Unzip the attached MvcStrongTyping0.1.zip file into [Program Files]\Developer Express Inc\DXCore for Visual Studio .NET\2.0\Bin\Plugins folder (on a 64 bit Windows it should look like C:\Program Files (x86)\Developer Express Inc\DXCore for Visual Studio .NET\2.0\Bin\Plugins).

2. Start an instance of Visual Studio 2008 and open (or create a new) ASP.NET MVC project.

3. Add a root folder named Helpers in the ASP.NET MVC project if it doesn’t exist yet.

4. Create a file named UrlExtensions.cs in Helpers folder.

5. Open the file and/or make it the active document.

6. WARNING: Any content in active document gets deleted and replaced by new one during this operation. Click DevExpress\Create MVC Routes menu entry.

route1
7. Include [Rootnamespace].Helpers (check out UrlExtensions class’ namespace) namespace to the web.config file in the <namespaces> node:

<system.web>
...
<pages>
...
<namespaces>
...
<add namespace="[YourRootNamespace].Helpers"/>
< /namespaces>
< /pages>
...
< /system.web >

That’s it. There should be a lot of code generated to UrlExtenstions.cs file and you are able now to use both new methods (or their overloads):

< %= Html.LinkTestOnHome("TestLink", 8, 77)%>
< %= Url.ActionTestOnHome(8, 77) %>

Generated code

For the Test action there should be this code (shortened) present:

...
namespace [YourRootNamespace].Helpers
{
public static class UrlExtensions
{
...
#region Fixed params action for Home.Test
public static string ActionTestOnHome(this UrlHelper helper, object routeValues) ...
public static string ActionTestOnHome(this UrlHelper helper, object routeValues, 
string protocol)...
#endregion
#region Fixed params links for Home.Test
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
object routeValues) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
object routeValues, object htmlAttributes) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
string protocol, string hostName, 
string fragment, object routeValues, object htmlAttributes) ...
#endregion
#region Variable params for action Home.Test
public static string ActionTestOnHome(this UrlHelper helper, int tubo)
public static string ActionTestOnHome(this UrlHelper helper, int tubo, 
RouteValueDictionary routeValues) ...
public static string ActionTestOnHome(this UrlHelper helper, int tubo, 
RouteValueDictionary routeValues, 
string protocol, string hostName) ...
#endregion
#region Variable params links for Home.Test
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, int tubo) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, int tubo, 
RouteValueDictionary routeValues) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, int tubo, 
RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, int tubo, 
string protocol, string hostName, string fragment, 
RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) ...
#endregion
#region Variable params for action Home.Test
public static string ActionTestOnHome(this UrlHelper helper, int tubo, int id) ...
public static string ActionTestOnHome(this UrlHelper helper, int tubo, int id, 
RouteValueDictionary routeValues) ...
public static string ActionTestOnHome(this UrlHelper helper, int tubo, int id, 
RouteValueDictionary routeValues, string protocol, string hostName) ...
#endregion
#region Variable params links for Home.Test
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
int tubo, int id) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
int tubo, int id, RouteValueDictionary routeValues) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
int tubo, int id, 
RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) ...
public static string LinkTestOnHome(this HtmlHelper helper, string linkText, 
int tubo, int id, 
string protocol, string hostName, string fragment, 
RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) ...
#endregion
}
}

That’s quite a lot of overloaded methods (and this is just an example for a single action!).
First note the name of the method that corresponds to the ActionOnController pair.
Next, there are basically two groups:
  • Fixed parameters – just strong typed links to the action (without any explicit action parameter)
  • Variable parameters – strong typed links with various combinations of action’s input parameters

Both groups are subdivided into two groups:

  • Actions – generates string representation of matching URL through UrlHelper.Action
  • Links – generates links through HtmlHelper.ActionLink method

Both internal calls might be optimized further and perhaps they will be in the future. At this point it is important that the methods work.

 

Implementation details

The magic of the autogenerated code comes from DXCore’s StructuralParser, which allowed me easy parsing of the project’s code (something that should be provided by Visual Studio from the beginning). And by easy I mean really easy and straightforward. I can’t praise it enough. On the other hand if it wasn’t for DXCore my plugin wouldn’t be even possible. At least not in time that I can allocate to this project.

So, all it took me was a couple of advices from Mark Miller (who is an incredibly helpful person btw) on where to start with parser and a bunch of basic operations of building a DXCore plugin. All in all it took me around 4 hours of my time. Thanks to my friend Miha for method naming suggestion. If it wasn’t for him the method names would be a lot worse. And thanks also to Whiletrue guys for their asp.net mvc performance presentation.

So, here it is. Let me know what do you think about it and don’t forget, this is an early, an experimental version of the plugin. All feedback is appreciated.

MvcStrongTyping0.1.zip (9.62 kb)

See also my previous article on strong typing the views.

Strong typing views in ASP.NET MVC

Did you ever wonder why do you have to write code like:

public ActionResult SomeAction() {   ... return View("SomeView", model); }


instead of this beauty:

public ActionResult SomeAction()
{    
...
  return Views.Home.SomeAction(model);
}

Note the advantages:

  1. Path to view is strong typed. No more “SomeView”.
  2. model argument is strong typed as well. No more passing a wrong typed only to discover the error at runtime.
  3. You can’t pass a non-performing argument anymore. This happens when you pass a view name and that view isn’t stored where MVC expects it to be: in a default folder (with the same name as controller under Views folder). Instead MVC will search for the view using various file-system locations and thus loosing valuable time. Lesson learned from Whiletrue's ASP.NET MVC presentation at SLODUG.

Sounds good? If yes, read further.

Instructions

There is a single requirment: you’ll need (my preferred) template based code generator CodeSmith.

1. Create a root folder named CodeSmith in your ASP.NET MVC project.

2. Unzip the attached CodeSmith template named StrongTypedViews.cst and put it into the folder mentioned above. Include it into the project. The project should look like this:

stv1

3. Right click on CodeSmith folder and add a CodeSmith Project item next to the StrongTypedViews.cst item. Name it CodeSmith.csp.

4. Right click on CodeSmith.csp and select Manage Outputs entry. You should see a modal window like this:

stv2

5. Click Add Output button (first enabled one from the left).

6. Type in StrongTypedViews.cst in the text field of the Template group (or click […] button next to it and select StrongTypedViews.cst). Name field should be auto populated with the same name.

7. In the File group select the radio button near text box and type in ..\Controllers\ControllerBase.cs (or do the same using […] button).

8. Finally, type in the root namespace of your project, MvcApplication4 in my case, into the RootNamespace property on the right side. The complete entry should look like this:

stv3

 

 

9. Click OK and another OK. At this point Visual Studio might warn you that a file has been modified outside the source editor. That’s fine as the previous steps did actually modify CodeSmith.csp file. Click Yes to reload it.

10. Generate the strong typed views by right clicking CodeSmith.csp and selecting Generate Outputs. You should see a new file names ControllerBase.cs under Controllers folder, like this:

stv4

 

 

11. One final step remains. Derive your controllers from auto generated ControllBase class and that’s it. You are now free to use strong typed views. You’ll find them by calling Views property and the with the same structure as it appears in the solution explorer.

stv5

i.e. if you want to return Index view you would use syntax like:

return Views.Home.Index();

or you can pass it a model, through an overload of the Index() method. Note that the model argument is strong typed (or object if the type isn’t specified in the aspx file). The syntax is same for both “full” and partial views (remember, they are strong typed and they know what to return) – no need to call either View or PartialView method.

12. If your views do change and they will you’ll have to recreate ControllerBase.cs class. This is really simple. Save all the view files and re-run Generate Outputs on the CodeSmith.csp project (as in step 10.). You can also set code generation on each build if you prefer.

That’s it.

Implementation details

Read this chapter if you are interested in inner working of this approach.

There are three distinct parts of the generated code.

ControllerBase class

You are required to derive your controllers from ControllerBase class for a simple reason – it provides Views property which is a gateway to all the views. The other (internal) feature of ControllerBase is to provide access to both View() and PartialView() methods to generated code (they are protected internal).

The Views property returns a new instance of ViewFolder auto generated class. Code is pretty much self-explanatory and looks like this:

public partial class ControllerBase: Controller
{
... 
  public new ViewResult View(string path, object model)
{
    return base.View(path, model);
}
  public new PartialViewResult PartialView(string path, object model)
{
    return base.PartialView(path, model);
}
  protected ViewsFolder Views
{ get { return new ViewsFolder(this); } }
...
}

 

ViewFolderBase class

This class is implemented within ControllerBase class and servers as a base class to the classes generated for each folder

public class ViewFolderBase
{
  protected readonly ControllerBase controllerBase;
  public ViewFolderBase(ControllerBase controllerBase)
{ this.controllerBase = controllerBase; }
}

Its main purpose is to “transport” the ControllerBase reference from one class to the another. This transportation is required because the reference to ControllerBase is required by the final class in the chain to call either View or PartialView method.

Classes generated for each folder under Views folder

Each such class (ViewFolderBase derived) is named by the folder it represents and a “Folder” suffix. It represents a single folder in the Views folder structure in the solution. These classes are declared within ControllerBase to reduce their scope. They have a two set of properties:

  • Views properties where there are two overloaded methods for each view in that folder. One overload is without arguments and the other contains a single strong typed model argument (which might be an object when the model is not typed in the view).

i.e. Error view from Shared folder. Note the strong typed model argument in the second overload. Note also the full path to the aspx file.

	public ViewResult Error()
	{ return controllerBase.View("~/Views/Shared/Error.aspx"); 
	
	public ViewResult Error(System.Web.Mvc.HandleErrorInfo model)
	{ return controllerBase.View("~/Views/Shared/Error.aspx", model); }	
	

  • Subfolder properties which represents subfolders of that particular folder. The purpose is to allow chaining.

i.e. ViewFolder’s (representing Views folder) subfolders section:

	public AccountFolder Account
	{ get { return new AccountFolder(controllerBase); } }
	
	public HomeFolder Home
	{ get { return new HomeFolder(controllerBase); } }
	
	public SharedFolder Shared
	{ get { return new SharedFolder(controllerBase); } }	
	

 

 

Template properties

Besides the RootNamespace property mentioned in the step 8 of the instructions there are other properties.

stv6

  • ViewsFolder: relative path to the Views folder in the solution
  • AdditionalNamespace: namespaces you want to place (using statement) in the generated ControllerBase.cs class. This is useful because model type is just copied from the declaration in the view files. So if you don’t use fully qualified types then you should put those namespaces in this property.
  • IncludeControllersNamespace: includes the namespace (a shortcut to the putting this namespace into AdditionalNamespaces)
  • IncludeModelsNamespace: includes the namespace (a shortcut to the putting this namespace into AdditionalNamespaces)
  • RootNamespace: the root namespace of your project. It will be used to compose a namespace where ControllerBase will reside (.Controllers suffix is automatically added).

Performance considerations

The generated code should perform very well. On the positive side it forces full path to the view files so the file is found at runtime in first attempt. On the negative side there is some overhead because the chaining creates few classes and passes a reference to ControllerBase instance to them. It shouldn’t be a huge overhead, or better, I didn’t even notice it in my simple performance tests (10.000 times calling each page using single core).

  • using View(“About”): ~658 requests/s
  • using View(“AboutX”): ~580requests/s   (it searches the Home folder first and Shared folder next where it finds AboutX.aspx)
  • using Views.Home.About(): ~658 requests/s

Tests were simple but I am pretty much confident in the results. Note the performance drop in the second case when MVC does file searching. All in all the overhead is pretty non existing. And it is non existing if you take into considerations all the benefits.

But if you want full performance without overhead there is a way. Instead of chaining used one might opt for method name composition which would result in:

return Views_Home_About();

 

for the About view. This way there wouldn’t be any overhead at all. I prefer my approach but that’s subjective.

Final words

Being a “strong typed” developer I find this approach a good one from every perspective. It should reduce errors if not improve performances as well. And all this for free – no manual typing required.

In the open source spirit of the ASP.NET MVC I am giving the template for free. Use it as you wish. Let me know if you have made improvements though – I’d be interested in seeing them and perhaps incorporating them.

Comming next: strong typed routes.

StrongTypedViews.zip (2.02 kb)

Slicker call to Dispose method

Do you ever get tired of code like this:

if (someObject != null)
{
someObject.Dispose();
}
or its shorter version
if (someObject != null)
someObject.Dispose();

Isn’t annoying to write those if (something != null) lines? Here is an extension method that does a better job:

public static class IDisposableExtensions
{
  public static void DisposeAlways(this IDisposable disposable)
{
    if (disposable != null)
disposable.Dispose();
}
}
No more ifs. Just write it like:
someObject.DisposeAlways();

DisposeAlways isn’t a perfect name though. Does anybody have a better suggestion? I can’t name it Dispose because it would conflict with existing method.

Partial Output Caching in ASP.NET MVC updated

Thanks to Miha Valenčič I’ve found this great article about Partial Output Caching in ASP.NET MVC. It actually explains how to do ActionResult caching in ASP.NET MVC. It was exactly what I was looking for. I had the same idea as in this blog post but didn’t know about SwitchWriter method nor I was aware of ActionFilterAttribute. IOW I had the idea but I didn’t know how to implement it. Which the mentioned blog post does.

The encoding

Problem

While this approach works I immediately stumbled on an encoding issue. The cached output is always encoded with UTF-16 encoding which might not be always a good thing. In fact IE7 protested immediately that one can’t switch between encodings (my original encoding is UTF-8) just like that. Hm.

So I went looking who is the culprit and soon found out that it is the temporary StringWriter created in the method below:

public override void OnActionExecuting(ActionExecutingContext filterContext) { _cacheKey = ComputeCacheKey(filterContext); string cachedOutput = (string)filterContext.HttpContext.Cache[_cacheKey]; if (cachedOutput != null) filterContext.Result = new ContentResult { Content = cachedOutput }; else { _originalWriter = (TextWriter)_switchWriterMethod.Invoke( HttpContext.Current.Response, new object[] { new HtmlTextWriter( new StringWriter()) }); } }


See, StringWriter uses UTF-16 and won’t allow any other encoding to be set. Easily that is.

Solution

Luckily the solution is an easy one. It involves a StringWriter derived class that accepts any encoding, such as this one (from Jon Skeet’s message):

public class StringWriterWithEncoding : StringWriter
{
Encoding encoding;
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get { return encoding; }
}
}

This new class should be used in creating that temporary writer, like this:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_cacheKey = ComputeCacheKey(filterContext);
string cachedOutput = (string)filterContext.HttpContext.Cache[_cacheKey];
if (cachedOutput != null)
filterContext.Result = new ContentResult { Content = cachedOutput };
else
{
StringWriter stringWriter = new StringWriterWithEncoding(filterContext.HttpContext.Response.ContentEncoding);
        HtmlTextWriter newWriter = new HtmlTextWriter(stringWriter);
_originalWriter = (TextWriter)_switchWriterMethod.Invoke(HttpContext.Current.Response, new object[] { newWriter });
}
}

And that’s it. New version of temporary writer will automatically use whatever encoding is set by HttpResponse.ContentEncoding.

The ContentType

Problem

The other problem involves ContentType not being cached. In my case I am testing with SyndicationFeed and ContentType has to be “application/rss+xml”. However it is ignored by the original caching mechanism where only response content is cached but not ContentType.

Solution

I’ll declare a new class that will store both content and content type.

class CacheContainer
{
public string Output;
public string ContentType;
public CacheContainer(string data, string contentType)
{
Output = data;
ContentType = contentType;
}
}

I’ll use this class to store cached content, like this:

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if (_originalWriter != null) // Must complete the caching
{
HtmlTextWriter cacheWriter = (HtmlTextWriter)_switchWriterMethod.Invoke(
HttpContext.Current.Response, new object[] { _originalWriter });
string textWritten = ((StringWriter)cacheWriter.InnerWriter).ToString();
filterContext.HttpContext.Response.Write(textWritten);
CacheContainer container = new CacheContainer(textWritten, filterContext.HttpContext.Response.ContentType);
        filterContext.HttpContext.Cache.Add(
_cacheKey, container, null, DateTime.Now.AddSeconds(_cacheDuration), 
Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
}

See, I am caching both Response.ContentType and its content now.

The last step is to use the cached ContentType, like this:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_cacheKey = ComputeCacheKey(filterContext);
CacheContainer cachedOutput = (CacheContainer)filterContext.HttpContext.Cache[_cacheKey];
    if (cachedOutput != null)
{
filterContext.HttpContext.Response.ContentType = cachedOutput.ContentType;
filterContext.Result = new ContentResult { Content = cachedOutput.Output };
}
else
{
StringWriter stringWriter = new StringWriterWithEncoding(filterContext.HttpContext.Response.ContentEncoding);
HtmlTextWriter newWriter = new HtmlTextWriter(stringWriter);
_originalWriter = (TextWriter)_switchWriterMethod.Invoke(HttpContext.Current.Response, new object[] { newWriter });
}
}

There you go.

ActionOutputCacheAttribute.cs (3.51 kb)

My first ASP.NET MVC pet project – Walls Talking

This week I’ve been extremely busy. Besides my usual work that pays for my living I worked on my first ASP.NET MVC project: Walls talking. I followed ASP.NET MVC development for long time but never had time to do something on my own.

And just a few days before ASP.NET MVC RTM release I’ve downloaded RC2 and in a couple of days (in spare time, mind you) I’ve put together Walls Talking, a graffiti collection site. Actually the idea for this project comes from my Saša and I merely coded the site that implements the idea. It features a form for uploading graffiti photos and its description, about page, a home page listing last 10 entries and a syndication feed. So far. The site is under construction of course and I’ll add features as long as my time permits me.

I can say that ASP.NET MVC is a truly a great platform for building web sites. It feels so slick and clean and much easier than regular ASP.NET bloated wizardry. I am missing a few features (i.e. construction of URL links outside of the Views, StreamActionResult that can be cached, etc.) so far, but hey, it is only at version 1.0. And there are relatively simple workarounds for those missing features that I created.

Entity Framework leaves the door open to a SQL Injection attack?

I couldn’t believe it when I read Julie Lerman’s post about EF and SQL Injection. She discovered that Entity Framework doesn’t use parameterized queries always!

I had to try it for myself on Northwind database:

var query = from c in entities.Customers
                        where c.ContactName == "Tubo"
                        select c;

produces this SQL statement (courtesy of SQL Profiler):

SELECT
[Extent1].[CustomerID] AS [CustomerID],
[Extent1].[CompanyName] AS [CompanyName],
[Extent1].[ContactName] AS [ContactName],
[Extent1].[ContactTitle] AS [ContactTitle],
[Extent1].[Address] AS [Address],
[Extent1].[City] AS [City],
[Extent1].[Region] AS [Region],
[Extent1].[PostalCode] AS [PostalCode],
[Extent1].[Country] AS [Country],
[Extent1].[Phone] AS [Phone],
[Extent1].[Fax] AS [Fax]
FROM [dbo].[Customers] AS [Extent1]
WHERE N'Tubo' = [Extent1].[ContactName]

See the Tubo condition expressed like a string? Speechless. Granted, if you specify a variable instead a string within the EF query then a parameter is used.

So I tried a classic SQL Injection attack, like this:

var query = from c in entities.Customers
                        where c.ContactName == "Tubo'; UPDATE [Northwind].Categories SET Description='SQL Injection' WHERE CategoryID=9; --'"
                        select c;

which produces this condition (select columns trimmed)

WHERE N'Tubo''; UPDATE [Northwind].Categories SET Description=''SQL Injection'' WHERE CategoryID=9; --''' = [Extent1].[ContactName]

Luckily the attack fails due to duplication of single quotes. So there is a protection against SQL attacks afterall.

However, I am not feeling safe with this approach. Attackers are smart and sooner or later they might find a way across string-replacement defense strategy.

But the real questions is: why leave the door open to a possible attack in first place? Why not always use parameters as there is no way around them? What good is to risk a SQL injection attack?

Update: A possible scenario where one could exploit this feature, granting there is a way around single-quote-replacement, is with add-ins. Imagine you have an add-in based application where each add-in is allowed to perform EF selects on database (enforced by your application). One could fake a select with all sort of T-SQL code nested within.

Calling WCF services from within Sql Server

It is possible to create a managed .net stored procedure for SQL Server that acts like a WCF client. SQL Server 2005 at least is required. But I won't talk about how to. I'd rather discuss an odd error you can encounter while performing this stunt.

On development machines one can encounter this odd error when WCF client is being initialized, after managed stored procedure is being invoked through T-SQL.

Msg 6522, Level 16, State 1, Procedure CalcAdd, Line 0 A .NET Framework error occurred during execution of user-defined routine or aggregate "CalcAdd": System.Configuration.ConfigurationErrorsException: The type 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior, Microsoft.VisualStudio.Diagnostics.ServiceModelSink, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' registered for extension 'Microsoft.VisualStudio.Diagnostics.ServiceModelSink.Behavior' could not be loaded. (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Config\machine.config line 192) System.Configuration.ConfigurationErrorsException: at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSection(String configKey, Boolean getLkg, Boolean checkPermission) at System.C...

Note that everything is configured properly and WCF client inside stored procedure should initialize just fine. The problem is somehow connected to machine.config file or better, to some initialization of types defined there.

After few google searches I've come across this post from MS' Jason Pang. Looks like the exception is linked to WCF debugging feature, usually installed on development machines - this debugging service has problems with WCF client running under SQL Server.

Workaround: (Temporary) disable WCF debugging by invoking this command line utility:

[Program Files]\Microsoft Visual Studio 9.0\Common7\IDE\vsdiag_regwcf.exe -u

Now the WCF client inside SQL Server runs just fine. After you've done you can re-enable WCF debugging services by calling same exe with different parameter:

[Program Files]\Microsoft Visual Studio 9.0\Common7\IDE\vsdiag_regwcf.exe -i

Note that administrator privileges are required to disable/enable it.

Using extension methods to make code less cluttered

Here is an example where an extension method is useful. Take this [LGP] code for example:

public EntityCollection<CustomersEntity> GetCustomers() { using (DataAccessAdapter da = new DataAccessAdapter("Data Source=[SERVER];Initial Catalog=Northwind;Integrated Security=True")) { LinqMetaData context = new LinqMetaData(da); var q = from c in context.Customers select c; EntityCollection<CustomersEntity> result = ((ILLBLGenProQuery)q).Execute<EntityCollection<CustomersEntity>>(); return result; } }

It is a simple LINQ to LLBLGenPro select against (we all love) Northwind database. Pay attention at result assignment. To have data returned as a native [LGP] EntityCollection you have to resort to ILLBLGenProQuery interface. You have to use ILLBLGenProQuery.Execute method on IQueryable<T> q. A cast is obviously required because IQueryable<T> doesn't know anything about ILLBLGenProQuery. While this code works it is not exactly elegant - I am referring to the later cast of course.

So, the idea is to have something like this instead:

EntityCollection<CustomersEntity> result = q.Execute<EntityCollection<CustomersEntity>>();

Possible? Sure, just add this static class with a single extension method and you are good to go:

public static class Tubular { public static TResult Execute<TResult>(this IQueryable q) where TResult : IEntityCollection2 { return ((ILLBLGenProQuery)q).Execute<TResult>(); } }

Or perhaps, we can further reduce the cluttering by introducing this extension method:

public static class Tubular { public static EntityCollection<TEntity> Execute<TEntity>(this IQueryable q) where TEntity : EntityBase2, IEntity2 { return ((ILLBLGenProQuery)q).Execute<EntityCollection<TEntity>>(); } }

to achieve this, even less cluttered, line:

EntityCollection<CustomersEntity> result = q.Execute<CustomersEntity>();

Isn't this or former de-cluttered line more readable and more elegant than the original?

Visual Studio, CodeRush and Silverlight 2

If your Visual Studio 2005 or 2008 freezes while creating a Silverlight project, or any other project then you might try switching off [CodeRush] add in. Yep, it causes Visual Studio to freeze when creating a shinny new Silverlight 2.0 application. I am sure that [DevEx] folks will fix the problem very soon but for the time being just start Visual Studio, go to Tools\Add-in Manager... and uncheck DevExpress Tools item (I guess that will be a hard step to [CodeRush] addicted people, but don't worry, it is only temporal). You can run Silverlight project wizard now and you can re-enable [CodeRush] once the project is created.

The workaround and the fact that [CodeRush] is the culprit has been found in this thread.