Tuesday, January 31, 2012

Internet Explorer rendering modes

I have a hard time understanding all the different rendering modes inside IE. I never remember when what mode will be used.

Thanks to the following flowchart created by Henri Sivonen, I have a cheat sheet available.

He shared the flowchart in his great article: Activating Browser Modes with Doctype.

Monday, January 30, 2012

The Firefox fieldset bug… and a possible workaround

In an ASP.NET MVC application we are building, we have a long list of items inside a form. These items are wrapped inside one <fieldset>tag.
The problem is when we try to print this form inside Firefox only the forms part on the first page gets printed, there is no second page but instead one page with the form sliced.
Turns out that when printing a document, Firefox truncate <fieldset> to one page. This mean that a form with a <fieldset> that would take more than one page in print can not be printed correctly. This is apparently a known bug tracked on bugzilla since 2008 (see bug 471015).
I couldn’t find an ideal solution, in the end I replaced the fieldset by a div and styled it using some css to make it similar.
The original fieldset:
<fieldset>
 <legend>Products</legend>
</fieldset

The alternative:

<div class="fieldset">
   <span class="fieldset">Products</span>
</div>


div.fieldset
{
    border: 1pt solid #755418;  
    padding:10px;
}

span.fieldset
{
    color: #755418;
    font-size: 13px;
    font-weight: bold;
    display:inline-block;
    position:relative;
    top:-20px;
    background-color:#fff;    
}

Friday, January 27, 2012

ASP.NET MVC: AsyncController Timeout

For long running operations in ASP.NET MVC the AsyncController is your friend.  One thing that was not so obvious to me is that the AsyncController will not be running forever but has a timeout setting(I think it’s about 45 seconds by default, could not find the exact number). So if your long running operation takes more time, don’t forget to set the timeout of the async controller action in order for this to work.
You do this by setting the AsyncTimeoutAttribute  Action Filter on the action that you want to extend its timeout:
public class PrintController : AsyncController
{
 private readonly IReportService _reportService;
        
 public PrintController(IReportService reportService)
 {
  _reportService = reportService;
 }

 [AsyncTimeout(60000)] //6000 milliseconds= 1 minute
    public void PdfAsync(string reportName, ReportType reportType = ReportType.PDF)
    {
  AsyncManager.RegisterTask<byte[]>(RenderReport(reportName, ReportType.Excel), data => new { data = data, reportName = reportName, reportType = ReportType.Excel });
    }

 //Some extra code...
 //...
}


And if you don’t want that the AsyncController times out, you have the NoAsyncTimeoutAttribute Action Filter.
Don’t forget to do this(as I did)!

Thursday, January 26, 2012

ASP.NET MVC AsyncController Helper

The AsyncController is a really nice feature introduced in ASP.NET MVC 2. It allows you to process your actions  asynchronously increasing the throughput of your web server.
Although implementing it is not that hard, I’m not a big fan of the current syntax(The new async api in ASP.NET MVC 4 looks promising).
In the meanwhile I have written a small helper class to simplify the usage of the AsyncController.
public static class AsyncManagerExtensions
   {
       public static void RegisterTask<T>(this AsyncManager asyncManager, Task<T> task, Func<T, object> func)
       {
           asyncManager.OutstandingOperations.Increment();
           task.ContinueWith(task2 =>
           {
               object propertyObject = null;

               if (!task2.IsFaulted)
               {
                   //invoke the provided function with the
                   //result of running the task
                   propertyObject = func(task2.Result);
               }
               else
               {
                   propertyObject = func(default(T));
               }


               //use reflection to set asyncManager.Parameters
               //for the returned object's fields and properties
               var ty = propertyObject.GetType();

               foreach (var f in ty.GetFields())
               {
                   asyncManager.Parameters[f.Name] = f.GetValue(propertyObject);
               }

               foreach (var p in ty.GetProperties())
               {
                   var v = p.GetGetMethod().Invoke(propertyObject, null);
                   asyncManager.Parameters[p.Name] = v;
               }

               asyncManager.OutstandingOperations.Decrement();
           });
       }
   }

Using it is simple. I create a controller that inherits from AsyncController:

public class PrintController : AsyncController
{
    private readonly IReportService _reportService;
        
    public PrintController(IReportService reportService)
    {
        _reportService = reportService;
    }
}


I add a method that returns the Task I want to execute and and the Action Controller method that will be called by the View(in this case through /Print/Pdf) . In this Action Controller method I call the RegisterTask<T> extension method and pass 2 properties:

  • The method that needs to be executed 
  • An expression that takes the output of the task and maps it to the parameters of the Completed method(based on the parameter name).
public void PdfAsync(string reportName)
{
 AsyncManager.RegisterTask<byte[]>(RenderReport(reportName)), renderReportResult=> new { data = renderReportResult, reportName = reportName });
}

private Task<byte[]> RenderReport(string reportName)
{
 return  Task.Factory.StartNew(()=>_reportService.RenderReport(reportName));
}

public ActionResult PdfCompleted(byte[] data, string reportName)
{
 var fileName = reportName + ".pdf";
 var fileContentResult = File(data, "application/pdf", fileName);
 Response.AppendHeader("Content-Disposition", string.Format("inline; filename={0}", fileName));
 return fileContentResult;
}

Tuesday, January 24, 2012

TFS: Change MS Project Field mapping

One of the nice features of TFS is it’s integration with MS Project. However I always forget how to update the Field Mapping between MS Project and TFS.

So as a quick reminder:

1. Download the MS Project field mapping file from TFS:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>tfsfieldmapping download /collection:”http://serverName:8080/tfs/collectionname” /teamproject:”teamprojectname” /mappingfile:”c:\fieldmapping.xml”

2. Update and save fieldmapping.xml

3. Upload the MS Project field mapping file to TFS:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE>tfsfieldmapping upload /collection:”http://serverName:8080/tfs/collectionname” /teamproject:”teamprojectname” /mappingfile:”c:\fieldmapping.xml”

Monday, January 23, 2012

Visug: Future of the Web–Slides and Demos

Last Thursday I gave a session at the VISUG(Belgian Visual Studio User Group) together with Kevin DeRuddere about the Future of the web.

The slides are available here:

And the demos can be downloaded here.

Friday, January 20, 2012

App_Offline.htm

One of the little known features in ASP.NET is the "App_Offline.htm" feature. It  provides a super convenient way to bring down an ASP.NET application while you make changes to it.

appoffline

To make this feature work, you have to place the app_offline.htm file in the root of the application. When ASP.NET sees it, it will shut-down the app-domain for the application (and not restart it for requests) and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application.

Once you remove the app_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and life will continue along as normal.

One remark: there are some gotcha’s when using this in ASP.NET MVC context. More information about this here: http://blog.kurtschindler.net/post/app_offlinehtm-gotchas-with-aspnet-mvc

Thursday, January 19, 2012

31 days of SSIS

I’m far from an expert in SQL Server Integration Services.

So the 31 days of SSIS series from Jason Strate were really helpful to me.

Now he has packed all this information in one, easy-to-read ebook.

A must read for every SSIS developer!

Wednesday, January 18, 2012

Auto-Start ASP.NET(MVC) applications in IIS 7.5

If your web application has to execute some pre-initialization work, the “Application_Start” event handler within the Global.asax file of an application is the logical place. However as a consequence the unfortunate first customer that accesses the application has to wait while this logic finishes before processing the request (which can lead to a long delay for them).
ASP.NET 4  and IIS 7.5 introduce a new feature called “auto-start” that better addresses this scenario. The auto-start feature provides a controlled approach for starting up an application worker process, initializing an ASP.NET application, and then accepting HTTP requests.
First configure the IIS “application pool” worker process that the application runs within to automatically startup when the web-server first loads. Open up the IIS 7.5 applicationHost.config file (C:\Windows\System32\inetsrv\config\applicationHost.config) and add a startMode=”AlwaysRunning” attribute to the appropriate <applicationPools> entry:
<applicationPools> 
 <add name="MyAppWorkerProcess" managedRuntimeVersion="v4.0" startMode="AlwaysRunning" />
</applicationPools> 


A single IIS application pool worker process can host multiple ASP.NET applications. You can specify which applications you want to have automatically start when the worker process loads by adding a serviceAutoStartEnabled="true" attribute on their <application> configuration entry:


<sites>
 <site name="MySite" id="1"> 
  <application path="/" serviceAutoStartEnabled="true" serviceAutoStartProvider="PreWarmMyCache" />
 </site> 
</sites>
<serviceAutoStartProviders> 
 <add name="PreWarmMyCache" type="PreWarmCache, MyAssembly" />
</serviceAutoStartProviders> 


The serviceAutoProvider="PreWarmMyCache" attribute above references a provider entry within the config file that enables you to configure a custom class that can be used to encapsulate any "warming up" logic for the application.


public class PreWarmCache : System.Web.Hosting.IProcessHostPreloadClient 
{
 public void Preload(string[] parameters) 
 { 
 // Perform initialization and cache loading logic here... 
 } 
} 

More information and all the details in Scott Guthrie’s post: http://weblogs.asp.net/scottgu/archive/2009/09/15/auto-start-asp-net-applications-vs-2010-and-net-4-0-series.aspx

Tuesday, January 17, 2012

WCF IsRequired Attribute

For a customer we are developing some WCF webservices. Our message contracts are defined by using  DataContract and DataMember attributes on top of our classes and their properties.
The DataMember attribute has some extra properties that allows us to add some extra rules. For example if a property should always be available, we use (IsRequired=true); to indicate this. These rules are checked when a message is received or send.
[DataContract]
public class TestClass
{
        [DataMember(IsRequired = true)]
        public string RequiredValue { get; set; }
}


However during our test we noticed that it doesn’t work.


What’s confusing here is that a DataMember has (EmitDefaultValue=true) set by default. An string property’s value starts as String.Empty.


Turn this off by using (EmitDefaultValue=false). Now, a property’s value is null, letting (IsRequired=true) do its validation work as desired.


[DataContract]
public class TestClass
{
        [DataMember(IsRequired = true, EmitDefaultValue=false)]
        public string RequiredValue { get; set; }
}


Although it’s still not what we expected. If we add a not-required property(e.g. NotRequiredValue) that refers to a class(e.g. ChildClass) that has a required property(e.g. RequiredValue) the validation fails saying that the RequiredValue is missing. Anyone who has a solution?


[DataContract]
public class TestClass
{
        [DataMember(IsRequired = true)]
        public string RequiredValue { get; set; }
  
  [DataMember(IsRequired = false)]
  public ChildClass NotRequiredValue { get;set; }
}

[DataContract]
public class ChildClass
{
        [DataMember(IsRequired = true)]
        public string RequiredValue { get; set; }
}

Monday, January 16, 2012

VISUG: Future of the Web

This Thursday I’m giving a session at the VISUG(Belgian Visual Studio User Group) together with Kevin DeRuddere about the Future of the web:

In this full evening on the future of the web, Visug offers you an evening with 2 sessions on HTML5, CSS3 and JavaScript.

Session 1: Everything you need to know to get you started with HTML5 (Kevin DeRudder)
HTML5, HTML5, HTML5 everything is HTML5. Should we really implement it in our web apps. Well yes, why not?
In this quick overview you will get some interesting points to get you started. We will have a look at some of the new tags, forms, canvas and what the future will bring.
Level 200

Session 2: JavaScript OMG! : An introduction to the unusual and unexpected features of JavaScript(Bart Wullems).
This session is an introduction to the weird side of JavaScript, and it definitely has a weird side! .NET developers will find a lot of intriguing "features" when they begin to write code in the world's most widely used language. Join us to learn about all the gotchas to watch out for and discover some of the great functionality that JavaScript has to offer…

On: Thursday, January 19, 2012

Location: Combell offices, Gent

Subscribe here: http://www.visug.be/Eventdetails/tabid/95/EventId/50/Default.aspx

Friday, January 13, 2012

OWASP Top 10 for .NET Developers

I loved reading this series by Troy Hunt. In the meanwhile I learned a lot about application security and risks involved.

If you have never heard of OWASP before a short introduction:

OWASP, the Open Web Application Security Project, is a non-profit charitable organisation established with the express purpose of promoting secure web application design. OWASP has produced some excellent material over the years, not least of which is The Ten Most Critical Web Application Security Risks – or “Top 10” for short.
The Top 10 is a fantastic resource for the purpose of identification and awareness of common security risks.

Oh, by the way, the current the Top 10 Security Risks for 2010 are

To make it even better Troy decided to turn this piece of art into an e-book. So just go and download these 255 pages of .NET web development security goodness.

And thank you, Troy Hunt!

OWASP Top 10 for .NET developers eBook

Thursday, January 12, 2012

Microsoft Team Foundation Server 2010 MOSS Configuration Tool

Configuring your MOSS environment to enable Team Foundation Server integration can be a daunting task.

Microsoft tried to simplify this task by releasing the TFS 2010 MOSS Configuration Tool.

Microsoft Team Foundation Server 2010 MOSS Configuration Tool

You can use this tool to configure an existing installation of Microsoft Office SharePoint Server 2007 or Microsoft SharePoint Server 2010 for use with Microsoft Visual Studio Team Foundation Server 2010. The tool automates the configuration of the following features with certain default values, which are explained in the configuration instructions that are included with the tool. The tool will skip configuring a feature if it is already enabled and configured.

The configuration tool is designed to configure relatively simple deployments of Office SharePoint Server 2007 or SharePoint Server 2010. The tool uses default settings to configure the features. You should not use this tool if any of the following is true:

  • your deployment requires the use of specific ports or protocols
  • your deployment utilizes multiple application-tier servers for the server farm
  • you want to configure your deployment with settings other than the default ones used by the tool

I was able to get the tool working on my local test environment, but on our tightly secured company environment, I had one error after the other.

Anyone who had more success with this tool?

Wednesday, January 11, 2012

Official Oracle support for Entity Framework v4

Although Oracle support for Entity Framework was available through some 3th party components, Oracle has finally released it’s (free!) version of ODP.NET that supports Entity Framework for use in production environments.

This is great news for many developers! Unfortunately features like Code First and DbContext can not be used with this release.

ODAC 11.2 Release 4 Production Released with Entity Framework and LINQ Support
ODAC 11.2 Release 4 (11.2.0.3) has arrived for Entity Framework and LINQ developers! It includes 32-bit and x64 versions with the option of using an automated installer or xcopy deployment.
The release incorporates Oracle Database client 11.2.0.3, which can access Oracle Database 9.2 and higher. Oracle supports Entity Framework and LINQ with Microsoft Visual Studio 2010 and .NET Framework 4, including Entity Framework 4.1 and 4.2. Code First is not supported in this release.

Tuesday, January 10, 2012

TFS 2010: What to install where?

With all the updates, fixes and service packs it’s hard to keep up with what component you have to install where.

To help us Grant Holiday provided an installation overview.

A short summary:

Server side:

Client side:

Monday, January 9, 2012

Generate a help page from a Word document: chmProcessor

In my ongoing quest to find a good tool to create our help files for a web application we are building, I stumbled over the following tool: chmProcessor

“chmProcessor is a tool that allows generating a help project and a compiled HTML help (CHM file) from a MS Word or HTML 4 file. If the file is a word document, the section titles must use the “Title 1”, “Title 2”, etc styles that offers by default Word. If the file is a HTML 4 file, the titles must use the <H1>, <H2>, etc. tags.

From this original file, each section of the document is split to different HTML files. Each of these files will be a topic page at the help. From the original document, you can generate:

· A Microsoft Help Workshop project.

· A compiled HTML help (CHM file).

· A web site like this.

· An Adobe PDF file.

· A Microsoft XPS file.

· A Java Help JAR file.”

Main Window

More information here: http://chmprocessor.sourceforge.net/

And the download is available here: http://sourceforge.net/projects/chmprocessor/

Friday, January 6, 2012

TFS: Securing Work Item Definition updates

Recently I got the following question from a customer:

“Can you prevent a user from updating a project's work item definition or its project template?”

This is not so easy to achieve as there is not a specific permission that controls this feature. By default members of the "Project Collection Administrators" and "Project Administrators" group have hard-coded admin permissions. Even if you remove the "Edit Project-Level Information" permissions, they have the ability to give that permission to themselves again.

The only way to prevent users from modifying the work item definitions, is to keep them out of the Project Admin groups.  If you still  want to  make these people administrators, I recommend to create a new administrators group and give them the same permissions, except for the following set:

  • Manage process template(Project Collection level)
  • Manage work item link types(Project Collection level)
  • Edit project-level information(Project level)

Thursday, January 5, 2012

CleanUp HTML tool

On a recent project, we got our documentation in a Word document. Very useful until we had to integrate this documentation inside a web application. You can save a word document as an html page but the end result is ‘less than optimal’.

There comes the CleanUp HTML tool to the rescue!

image

Cleanup HTML is online tool based on Tidy to clean up HTML code from excessive tags. Microsoft Word and other Microsoft Office products are known from generating cluttered HTML code and big files when you try to save as web page. This online tool is able to strip all unnecessary <font>, empty tags, non-breaking spaces and Microsoft Word Styles and output properly structured clean code.

Wednesday, January 4, 2012

Visual Studio 11 Developer Preview Training Kit: December Update

Last week Microsoft released an update to the Visual Studio 11 Developer Preview Training Kit.

The Training Kit is available in two different offline packages and is also available to browse online at MSDN. You can download the kit as a single package (37.2mb download), or you can download the Web Installer (2.5mb download) to browse the available content and download only the labs that you need.

Below is the list of hands-on labs that are included in the Training Kit.

Visual Studio Development Environment

  • A Lap Around the Visual Studio 11 Development Environment
  • What's New in Visual Studio 11 for C++ Developers (new)

Languages

  • Asynchronous Programming in the .NET Framework 4.5

Web

  • What's New in ASP.NET and Web Development in VS 11
  • What's New in Web Forms in ASP.NET 4.5
  • What's New in ASP.NET MVC 4 (new)
  • Using Page Inspector in Visual Studio 11 (new)
  • Build RESTful APIs with WCF Web API

.NET Framework

  • Using Portable Class Libraries (new)

Application Lifecycle Management

  • Building the Right Software: Generating Storyboards and Collecting Stakeholder Feedback with Visual Studio 11
  • Agile Project Management in Team Foundation Server 11
  • Making Developers More Productive with Team Foundation Server 11
  • Diagnosing Issues in Production with IntelliTrace and Visual Studio 11
  • Exploratory Testing and Other Enhancements in Microsoft Test Manager 11
  • Unit Testing with Visual Studio 11: MSTest, NUnit, xUnit.net, and Code Clone

Windows Metro-style apps

Tuesday, January 3, 2012

Community TFS Build Extensions: December release

Just before the year ending, a new version of the Community TFS Build Extensions is released. This release contains 100 Activities / Actions for Team Foundation Build 2010 and Team Foundation Build 11.

New in this release is the Community TFS Build Manager. It is intended to ease the management of builds in medium to large Team Foundation Server environments, though it does provide a few features which all users may find useful.


Current Feature Set

  • View and sort Builds and Build Definitions across multiple Build Controllers and Team Projects
  • Bulk operations on Build Definitions
    • Change Build Templates
    • Queue
    • Enable
    • Disable
    • Delete
    • Set Retention Policies
  • Clone Build Definitions (includes workspace mapping translation)
  • Create a DGML image of your Builds and Controllers
  • Bulk operations on Builds
    • Delete
    • Open Drop Folders
    • Retain Indefinitely
The Community TFS Build Manager is now available on the Visual Studio Extensions Gallery
A blog post by Jakob Ehn describing the features of the Community TFS Build Manager can be found here

Monday, January 2, 2012

TFS 2010 Build: TF215087 error

If you ever tried to build some custom activities in TFS 2010 Build you’ve probably run into the following  error message:

TF215097: An error occurred while initializing a build for build definition \TeamProject\MyBuildDefinition: Cannot create unknown type '{clr-namespace:[namespace];assembly=[assembly]}Activity

This means that the TFS build service couldn’t create an  instance of the customer workflow activity that is referenced inside your build process template.

So here is a short checklist with some possible reasons:

  • You have checked in the modified version of the XAML workflow.
  • Your custom activity has the the BuildActivityAttribute. 
  • Your custom activity is public.
  • You have configured your build controller with the path in source control where the custom activities are located .
  • Verify that all dependencies for the custom activity assembly/assemblies have been checked into the same location as the assembly.
  • The reference to the custom activity assembly in the XAML workflow is correct.