May 2010 - Posts
Hands-on Labs for Microsoft Enterprise Library 5.0 and Unity 2.0
Enterprise Library 5.0
is out there for over
a month. With
every release of
Enterprise Library,
The Patterns &
Practices team is always
launching a set of hands-on labs which can help you to
get started with Enterprise Library and to understand how
you can work with it in order to implement cross cutting
concerns in your applications. You can download the labs
from here.
Enjoy!
VS2008 No Item Templates
While trying to add a new web form item to a project at
a customer, I got the following error:
After pressing the OK button I got an empty Add New Item menu:
A little scary screen…
So I went to the Event Viewer as suggested in the error message and
looked at the event in the Application log which was:
So I closed all the VS2008 instances I had currently running and
tried to regenerate the templates by running the
devenv.exe /installvstemplates.
That didn’t work for me and I didn’t want to reinstall VS2008 or to
use the repair installation.
I tried another way which was to reset the VS setting by using the
devenv /resetsettings command and it worked.
I hope it will help you if you’ll get stuck with this error.
Building a Simple Logging Http Module with Logging Application Block
I wanted to
check how
to use the
fluent
configuration
API for the
Logging Application Block in Enterprise Library 5.
So I thought to myself why not implement it with an http module
and provide two examples in one post.
Using the Fluent Configuration API with Logging Application Block
I wrote a post about the fluent configuration in Enterprise Library 5
in the past. Here is how I configured the Enterprise Library container
in order to use the Logging Application Block in a simple flat file scenario:
private void ConfigureEnterpriseLibraryContainer()
{ var builder = new ConfigurationSourceBuilder();
builder.ConfigureInstrumentation().EnableLogging();
builder.ConfigureLogging().WithOptions
.LogToCategoryNamed("General") .WithOptions
.SetAsDefaultCategory()
.SendTo
.FlatFile("Log File") .FormatWith(new FormatterBuilder()
.TextFormatterNamed("Textformatter")) .ToFile("file.log");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current =
EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
}
Pay attention that in order to use this API you need to add
references to the following dlls:
- Microsoft.Practices.EnterpriseLibrary.Common
- Microsoft.Practices.EnterpriseLibrary.Logging
- Microsoft.Practices.ServiceLocation
- System.Configuration
Now that we have the configuration placed in memory we can
use it in our code.
Building the Http Module
In order to build an Http module we only need to implement
the IHttpModule interface. The following is a simple
LoggingHttpModule which log details when a web request start
and when web request end:
using System;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
namespace HttpModules
{ public class LoggingHttpModule : IHttpModule
{ #region Members
private LogWriter _writer;
#endregion
#region IHttpModule Members
public void Dispose()
{ if (_writer != null)
{ _writer.Dispose();
}
}
public void Init(HttpApplication context)
{ CreateLogWriter();
context.BeginRequest += new EventHandler(context_BeginRequest);
context.EndRequest += new EventHandler(context_EndRequest);
}
private void CreateLogWriter()
{ ConfigureEnterpriseLibraryContainer();
_writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
}
private void ConfigureEnterpriseLibraryContainer()
{ var builder = new ConfigurationSourceBuilder();
builder.ConfigureInstrumentation().EnableLogging();
builder.ConfigureLogging().WithOptions
.LogToCategoryNamed("General") .WithOptions
.SetAsDefaultCategory()
.SendTo
.FlatFile("Log File") .FormatWith(new FormatterBuilder()
.TextFormatterNamed("Textformatter")) .ToFile("file.log");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current =
EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
}
void context_BeginRequest(object sender, EventArgs e)
{ _writer.Write(new LogEntry
{ Message = "BeginRequest"
});
}
void context_EndRequest(object sender, EventArgs e)
{ _writer.Write(new LogEntry
{ Message = "EndRequest"
});
}
#endregion
}
}
Using The Module
In order to use the module all we need to do is to add a reference
to the class library that holds the LoggingHttpModule. Then we need
to register the module in the web.config file in the httpModules
element like:
<httpModules>
<add name="LoggingHttpModlue" type="HttpModules.LoggingHttpModule, HttpModules"/>
</httpModules>
That is it. Now the module will be executed whenever a request
start or end.
Summary
Using the fluent configuration API of Enterprise Library 5 can
make it easy to configure cross cutting concerns like logging
without a configuration file. The API is simple and very easy
to apply. In this post I showed how to combine the Logging
Application Block within an Http module with the fluent
configuration API.
CodeProject
Annoying Build Error while Implementing the IControllerFactory Interface
Today I wanted
to check
something
in the MVC
framework in
regard to the
implementing the
IControllerFactory interface. I couldn’t guessed that it will take me
ten minutes to figure out an annoying build error which I will
explain here how to resolve it.
The Scenario
You want to implement the IControllerFactory interface but not in
the MVC framework generated web application. The implementation
would exists in another class library. I set a reference for the
System.Web.Mvc dll and also to the System.Web dll (which holds the
System.Web.Routing.RequestContext which is needed for the
CreateController method.
The Problem
I finished to implement the interface and compiled the solution.
A very strange “does not implement interface member
'System.Web.Mvc.IControllerFactory.CreateController(
System.Web.Routing.RequestContext, string)” error message is
jumping at me from the Error List View. Since I know that I
finished to implement all the methods in the interface this error is
very interesting and annoying.
I searched the web for indications about this error and found
some references without any solution such as this post.
The solution
I tried to figure out what was missing. So I guessed that I wasn’t
referencing another assembly which causes the inappropriate error.
My first guess was the System.Web.Routing dll. I referenced it
and the build succeeded without any errors.
Summary
Sometimes more informative errors can help you to find the
problems you face. In this case the error wasn’t helpful and
lead me to think that something in my implementation was
wrong. I hope that this post will help you if you get stuck
with this error.
How to Manage ObjectContext Per Request in ASP.NET
We started a new
project at work.
One of my guidelines
was to manage the
lifetime of the Entity
Framework’s ObjectContext
as context per request.
Since I got some questions in the area I decided to explain how you
can achieve that.
Why to Use an ObjectContext Per Request?
In a previous post I wrote about this subject. The main issue
is that the context should be a short living object. Since
this is the case but we want to gain all the advantages of
using the context (which include lazy loading, change tracking and
more), I prefer to use a context per request in web applications.
How to Manage ObjectContext Per Request in ASP.NET?
When we want to use an ObjectContext per request in web applications
we need to find a centralized place which will hold the context during
the request. For our rescue comes the HttpContext class. The
HttpContext lives during the request and is dispose after it so its our
perfect candidate. We can use the Items collection that it holds in order
to keep the instance of our ObjectContext. One drawback of this is
that we need a dependency on System.Web library in order to use this class.
So how can we do that? we will create an helper class that will retrieve
the context when we need it. In the helper class we will use lazy loading
in order to create the context only when we need it. Here is a simple
example of how to do that:
public static class ContextHelper<T> where T : ObjectContext, new()
{ #region Consts
private const string ObjectContextKey = "ObjectContext";
#endregion
#region Methods
public static T GetCurrentContext()
{ HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{ string contextTypeKey = ObjectContextKey + typeof(T).Name;
if (httpContext.Items[contextTypeKey] == null)
{ httpContext.Items.Add(contextTypeKey, new T());
}
return httpContext.Items[contextTypeKey] as T;
}
throw new ApplicationException("There is no Http Context available"); }
#endregion
}
Summary
Lets wrap up, in web application my suggestion is to use an
ObjectContext per request. This will help us to have a short living
ObjectContext and to use its capabilities for change tracking and
other mechanisms. There are other solutions such as a static
context (don’t do that!) or context per business transaction but
as I wrote I prefer context per request.
CodeProject
Using Stub Entities in Entity Framework Screencasts
Today I recorded my first
two screencasts (one in
English and one in Hebrew)
about how to use
stub entities in Entity
Framework in order to
produce better performance
by reducing database round trips.
The link to the English version can be found here.
The link to the Hebrew version can be found here.
You can also download the screencasts in the details tab if you
like.
Enjoy!
How to Retrieve Stored Procedure Output Parameters in Entity Framework
One question that
raises from time to
time in EF forums
is how you can
retrieve stored
procedure output
parameters in EF
Function Import.
This post will show you how to do that.
The Stored Procedure
In the example I’m going to use the following stored procedure:
CREATE PROCEDURE dbo.SchoolBudgetForDateRange
@StartDate DATETIME,
@EndDate DATETIME,
@Sum money output
AS
SET NOCOUNT ON;
SELECT @Sum = SUM(Department.Budget)
FROM Department
WHERE StartDate BETWEEN @StartDate AND @EndDate
The stored procedure returns the school budget for a given date.
By of course the stored procedure could return that calculation
without using an output parameter.
Retrieving Stored Procedure Output Parameter
After creating a Function Import (which is explained here) we can
use the SchoolBudgetforDateRange method with the context we have.
In order to get an output parameter you need to supply an ObjectParameter
to the stored procedure call which holds the parameter name and type.
After the execution of the stored procedure you can retrieve the
parameter using the Value property of the ObjectParameter.
The following code shows how to that exactly what I wrote:
static void Main(string[] args)
{ using (SchoolEntities context = new SchoolEntities())
{ var outputParameter = new ObjectParameter("sum", typeof(decimal)); context.SchoolBudgetForDateRange(new DateTime(2007, 1, 1),
new DateTime(2008, 1, 1),
outputParameter);
Console.WriteLine(outputParameter.Value);
}
}
Summary
Once you need to retrieve output parameters from EF Function Imports,
you need to supply an ObjectParameter to hold the output. In the post
I showed how to do that.
CodeProject
How to Add Silverlight Installation to IE8 Installation Package using IEAK8
During the last
weeks I’m helping
Microsoft customers
to create custom
installation packages
to Internet Explorer 8.
In this post I’ll explain
how to add Silverlight
installation to the
generated installation
package of IE8.
Using IEAK8
In order to create custom installation packages for Internet Explorer 8
you first need to download the Internet Explorer Administration Kit 8
or IEAK8. You can download the tool from here.
How to Add Custom Component?
When running IEAK8 we can add custom components such as Silverlight
installation to the generated installation package.
How to do that?
During the IEAK8 Wizard you use the Custom Component step and add
your custom components:
Press the Add button in order to open the Add a Custom Component step.
In the opened Add a Custom Component window you browse for the location
of the custom component installation. You need to fill the Name of the
component and then choose when the component will be installed
(Before or after the IE installation occurs).
You can use the “Only install if Internet Explorer is installed successfully”
checkbox in order to enable the installation of the component if
IE installation succeeded or not.
One other thing to notice in the supplied figure is the /q parameter.
This parameter will enable silent installation on the Silverlight installation.
Pressing the Add button at the bottom of the window will add the Silverlight
component to your to the list of components which will be installed by the
custom IE8 installation.
Pay attention that the custom components will be installed only in the full
generated version of the installation packages and not as
part of configuration installations (brand installation).
Summary
It is very simple and intuitive to add custom components to
IE8 installation
packages using the
IEAK8 tool.
CodeProject
Book Review – Clean Code – A Handbook of Agile Software Craftsmanship
Today I finished
reading
Robert C. Martin’s
wonderful book -
Clean Code –
A Handbook
of Agile Software
Craftsmanship.
The book is all about
writing quality code.
It is full of examples
of good and bad code and
a lot of suggestions for how
to write a better code base.
Even so the examples were
written in Java language
I encourage .Net developers to read this book only to learn the concepts
that are presented by the author which are universal for every language.
Since in my early days I was a Java developer then for me it was easy
to read the book and enjoy it.
What you will Gain?
The book will help you to diagnose bad code (or code smell) and to clean it
up. The book has three parts that every one of them is built on top of its
previous part. In the first part you will learn the principles, patterns and
practices of how to write a clean and quality code. The second part includes
three case studies which instruct and show how to create clean code. These
examples show how to take a working framework like JUnit for example and
even in it to clean the code. In the last part you are given a knowledge base
of heuristics and “smells” which can guide you when you develop.
Summary
I really enjoyed reading Clean Code book. It is written in a very
comprehensive way one layer on top of the other. I encourage you to read
this book not only because I think that quality code is super important but for
the sake of you being a professional in what you are doing. I rate the book
with five stars.
Wireless Notebook Presenter Mouse 8000
A few months ago I bought
a new mouse. I needed
a mouse that could also
act as a presenter tool
in order to assist me in
my presentations that I
am delivering from time to
time. So I talked to some
people and asked for their
recommendations.
I also searched for details
about presenter tools in the internet and in the end I found the
Wireless Notebook Presenter Mouse 8000 very suiting for my
needs.
The Wireless Notebook Presenter
Mouse 8000 is more then just a
mouse. It’s integrated with slide
presenter, laser pointer, and media
remote control. At the back of the
mouse we have buttons that
help us to control power point
presentations. Those buttons are
disabled by default and can be
enabled by clicking a button on
the mouse’s front.
Using the product helped me to
stop coming back to the podium
in order to press buttons during my presentations and also since this
is a mouse I could use it in my demos and of course in other
occasions which doesn’t include presentations (such as working
at the office).
So if you are looking for a slide presenter which can act as a mouse
the Wireless Notebook Presenter Mouse 8000 can suit your needs.
For further details about it go to this link.
SQL For .Net Developers – Entity Framework 4 Slide Deck
Yesterday’s evening I delivered a session at Microsoft Raanana about
Entity Framework 4.0 & LINQ as a part of Microsoft’s
SQL For .Net Developers series of sessions. I want to thank all the
attendees who came to the session. I really enjoyed to talk about
Entity Framework and the audience was very cooperative with a lot
of really good questions.
I also want to thank Tzvia from Microsoft for the opportunity to be
the one who opens this series of sessions.
As I promised, I uploaded the session slide deck and demos to my
Skydrive and you can download it from here. Pay attention that in the
demos main directory there is a backup file of the database I used in
my demos.
Since we had a full house in all the sessions (about 200 people registered
to every one of the sessions), there is another series of sessions like this
one scheduled in the near future. I’ll update in my blog when the dates
will be published. If you didn’t attend this session and you wanted to
attend it you’ll have another opportunity to participate in the next session.
Enjoy!