Using MEF in MVC 3

After travelling for a year I was interest to see if MEF would work with MVC, and after some digging around I found it can.

***UPDATED****

First you need to make sure your Visual Studio will accept MVC 3 this can be downloaded from Microsoft at http://www.asp.net/mvc/mvc3

With any MEF you'll need a Composition Factory which in this case I'll place in the MEF directory, but it can be in a different project if required.

public class CompositionContainerFactory
    {
        public CompositionContainer CreateContainer()
        {
            var path = HostingEnvironment.MapPath("~/bin");

            if (path == null) throw new Exception("Unable to find the path");

            var catalog = new DirectoryCatalog(path);

            return new CompositionContainer(catalog);
        }
    }

Now comes the interesting part, in MVC 3 Microsoft introduced the IDependencyResolver, which gets the services when needed.

So implementing the IDependencyResolver with MEF was a little trickier 

public class MEFDependencyResolver : IDependencyResolver
    {
        private readonly CompositionContainer _container;

        public MEFDependencyResolver(CompositionContainer container)
        {
            if (container == null) throw new ArgumentNullException("container");

            _container = container;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType == null) throw new ArgumentNullException("serviceType");

            var name = AttributedModelServices.GetContractName(serviceType);

            return Enumerable.Any(_container.Catalog.Parts.SelectMany(part => part.ExportDefinitions), e => e.ContractName == name) ? _container.GetExportedValue<object>(name) : null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (serviceType == null) throw new ArgumentNullException("serviceType");

            var name = AttributedModelServices.GetContractName(serviceType);

            return _container.GetExportedValues<object>(name);
        }
    }

 The final step we will need to set the Dependency Resolver and this is done in the Application Start inside the Global.asax

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            DependencyResolver.SetResolver(new MEFDependencyResolver(new CompositionContainerFactory().CreateContainer()));
        }

Now we are ready to use MEF inside of MVC.

To use MEF inside of MVC just attach the [Export] attribute to controller and then import the object you require, like this:

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController : Controller
    {
        [ImportMany]
        private List<IAddress> Addresses { get; set; }

        public ActionResult Index()
        {
            return View(Addresses);
        }
    }

Make sure that the Part Creation Policy is Non-Shared otherwise you will only be able to visit the page once.

That is it, what more could you want, oh the code samples, here they are:

Using MEF in MVC 3.zip (845.26 kb)

I've been working on providing a full plugin for MEF and MVC, so I've rebuilt a sample in VS12 and sepatated  all the components.

Using MEF in MVC 3.zip (7.44 mb)

If you are interested in pulling out all the Views, content and JavaScript then it would be worth having a look at the RazorGenerator

 

 

Assigning SSL certificate in IIS 6

If when in a test invironment you need to test out SSL (HTTPS) on your website you can create a self-assigning SSL certificate (this process only appiles to IIS6)

Typically, Secure Socket Layer (SSL) Certificates are created for domains by first generating a Certificate Signing Request (CSR) through Internet Information Services (IIS), sending the request to a known Certification Authority, such as GeoTrust, which generates a corresponding Certificate file for use in conjunction with the CSR, completing the request and securing communications on the domain.

However, IIS does come with the ability to create a 'self-signed' certificate, in which the server generating the CSR also generates the corresponding Certificate file. These are mainly used for testing, development and troubleshooting, as the certificate will only be recognized as valid by the server it is hosted on. Attempting to view the secured domain externally would receive an error that the certificate is not valid, as it has not been approved nor is recognized by a known Certification Authority.

To create a self-signed SSL certificate for any hosted domain on your server, you will first need to download and install the SSL Diagnostics Kit v1.1, which can be obtained free of charge from Microsoft via the following URL:

SSL Diagnostics Version 1.1 (x86) - SSLDiag.msi (532.00 kb)

Given the option to either Run or Save the file, choose 'Save'.

For now, let's save the file to the desktop. Click 'Save' again.

Once the download is complete, double-click the icon to begin the installation.

Click 'Next' on the initial window.

Enter your desired Name and Company information, and click 'Next'.

The next screen will provide options for which type of installation you prefer. You can click 'Complete' to install the Diagnostics.

You are now ready to install the diagnostics. Click 'Install'.

When the installer confirms it has completed, click 'Finish'.

Now, we need to get some information from IIS before we can generate the self-signed certificate. Open IIS by navigating to 'Start --> Administrative Tools --> Internet Information Services (IIS) Manager'.

Once IIS is open, expand the Server Name, then click on the 'Web Sites' folder. This will bring up a list of all web sites on the server in the right-hand pane. You will notice that each site has a unique number assigned to it under the 'Identifier' column. This is the number which we need in order to create the self-signed certificate. As you can see, the Identifier for 'example.com' is 957.

Next, we need to open a DOS Prompt. You can do this by navigating to 'Start --> Run', typing 'CMD', and clicking OK.

Once the DOS prompt is open, we will need to navigate to the directory where the SSL Diagnostic Toolkit is located. This directory is 'C:\Program Files\IIS Resources\SSLDiag'. To navigate to this directory, at the DOS prompt, enter the following command:

cd C:\Program Files\IIS Resources\SSLDiag

The 'cd' command stands for Change Directory. Press Enter once the command is typed in, and the prompt will bring you right to the directory, as seen below.

Now, we need to enter the command which will actually create the certificate. The base command to create the certificate is 'ssldiag /selfssl', however command requires certain parameters for the certificate to be successfully created. These parameters are as follows:

    /N: - This specifies the common name of the certificate. The computer name is used if there is no common name specified.
    /K: - This specifies the key length of the certificate. The default is length 1024.
    /V: - This specifies the amount of time the certificate will be valid for, calculated in days. The default setting is seven days.
    /S: - This specifies the Identifier of the site, which we obtained earlier. The default will always be 1, which is the Default Web Site in IIS.

Let's use the following command to create a self-signed certificate for 'example.com' (you'll need to ensure that the DNS server has this domain name pointing to your IIS machine) which is valid for two years, using a common name of 'www.example.com', a key length of 1024:

ssldiag /selfssl /N:CN=example.com /K:1024 /V:730 /S:957

Once you have set the parameters to your preference, enter the command into the DOS prompt, and press Enter. After pressing Enter, the DOS prompt will simply move to the next line.

Now, we can check IIS and verify the certificate is now in place. Using the steps outlined above, navigate back to IIS, right-click on the domain, and choose 'Properties'.

Inside the Properties window, click on the 'Directory Security' tab.

On the Directory Security tab, under the 'Secure Communications' heading, click on the 'View Certificate' button, as it is now enabled.

This windows confirms the certificate has been successfully installed. Note the 'Issued By' field, as typically the issuer would be a known Certification Authority, such as GeoTrust, however here the issuer is 'example.com'. This confirms the certificate is self-signed. Click OK to close the window.

You can now view the site on the server under a secure heading. Again, please note that as the certificate is self-signed, and does not have a matching Root Certificate from a Certification Authority, attempting to view the site under a secure heading from an external location will cause a certificate error. Self-signed certificates should only be used for testing and development, and under no circumstances should be substituted for a CA-approved SSL Certificate for a live, production website.

This has been extracted from ServiceFirst Support

The TFS shuffle

If you are like me you perform a shuffle before checking anything in to a Source Control Repository and TFS is no different

As for shuffle:

  1. Get Latest
  2. Fix merge conflicts
  3. Build
  4. Fix build errors
  5. Run tests
  6. Fix broken tests
  7. Go to 1 (until there is nothing new to get)

Only check in when all steps are complete.

Then check the Pending Changes that you have nothing else left to check in, if you do then perform the above shuffle for each pending change.

To get to the Pending Changes window select View-->Other Windows-->Pending Changes

Other useful references:

http://codebetter.com/jeremymiller/2005/07/25/using-continuous-integration-better-do-the-check-in-dance/

http://www.extremeprogramming.org/rules/collective.html

Debian and installing LXDE (Lightweight X11 Desktop Environment)

This is the second part of my Raspberry PI posts, the first covered the installation of Debian on to a virtual machine.  This this post I'll be getting the fresh install to include a lightweight desktop called LXDE 

So first up your Debian and login

Here is the set of command you need to type to get LXDE up and running:

su root
apt-get install lode xorg
apt-get install server-xorg-video-all
exit
starts
 

One last thing I'll show you is installing packages, as we'll be using the Raspberry PI we'll be using the Aptitude which is an old-fashioned GUI interface to assist in installing packages

aptitude
 

So that's it for today, you have a good looking interface and the ability to install packages

Getting ready for my Raspberry PI and installing Debian

I've ordered my Raspberry PI, so I'm planning how and what I'm going to be doing with it.

I have many small projects I'd like to get underway, but ones which spring to mind first are building a home Media Centre, Network Storage device that supports many drives, and one that is hot on my list is the ability to connect the Raspberry PI to my Arduino and build a small portable device that can tell me where and how to access Wifi while I'm out and about.

But before I do anything lets get a virtual machine up and running so we can start playing as if we were on the Raspberry PI:

It has been rumoured that Debian will be the preferred OS to use on the PI due to it small foot print, so let go and get it

http://www.debian.org/distrib/netinst

I selected and downloaded small CDs and the kfreebsb-i386, mainly because I am running on a Mac and will be running my virtual machine inside of Parallels.

Thing to remember when creating your virtual machine is set your memory to 256mg as this is all you'll have to play with inside your PI.

Here is a YouTube video that I made which goes through the installation of Debian in real time, as it takes under 15 minutes to install

 

So first steps complete.

The next Blog on the Raspberry PI will be to install a graphical user interface on to your Debian operating system.

Regular Expression cheat sheet

Always up for cheating, so when I came across a website dedicated to cheat sheets I was over the moon. http://www.addedbytes.com/

The one I am using the most has to be RegEx as I am now finally getting to grips with the syntax and expressions.

regular-expressions-cheat-sheet-v1.pdf (568.89 kb)

Screencast-O-matic

After finding Screen Toaster some three years ago now, I found out the other month that the website has been pulled, it's a shame as this was such a useful tool.

But today I found Screen-O-Matic a small java application, like Screen Toaster, that just works.

You don't even need an account, and if you want to go Pro it's only $12 a year.  Lets hope that this model is sustainable and long lasting.

Balsamiq Mockups the next stage

I've been pushing Balsamiq Mockups for a number of years, it was on my toy list for 2009.

Once you have a mock up of your wireframe and the customer is happy with the look, the next stage is to convert it to HTML, previously I have prefered to pass this to a designer to make it look pretty.  But the problem you'll have with making something look nice is that the customer will think it is DONE and you just don't want that to happen.

I came across a Balsamiq Mockup to HTML/CSS converter this morning from NedeCo it just does the job and generates a simple and easy to follow HTML and CSS.

This is a perfect starting point for your application and you'll be able to get your business and architecture up and working before the customer gets any expectitions of a DONE project.

BalsamiqConverter.zip (511.03 kb)

Upgrading from MVC 2.0 to MVC 3.0

Have you tried to upgrade an MVC 2.0 application to MVC 3.0, it's not easy as you need to change a lot of configuration.

Well Eilon Lipton has a codeplex project to make life easier ASP.NET MVC 3 Application Upgrader. This is a standalone application that takes the troubles away for you and delivers an MVC 3.0 application

Mvc3AppConverter.zip (430.58 kb)

Visual C# and .NET 4.0 samples

I came across some nice C# samples from Microsoft today providing everything from Hello World, to how to use Yield and how to program Attributes.

Official Visual Studio 2010 Samples for C# 4.0

Worth having a look at if you are a beginner or a seasoned programmer.

Language Samples

The C# 4.0-specific samples are called:

  • Named and Optional
  • Office Sample
  • Python Sample
  • Simple Variance.

Here is the complete list of language samples:

  • Anonymous Delegates: Demonstrates the use of unnamed delegates to reduce application complexity.
  • Arrays: Shows how to use arrays.
  • Attributes: Shows how to create custom attribute classes, use them in code, and query them through reflection.
  • Collection Classes: Shows how to make non-generic collection classes that can be used with the foreach statement.
  • COM Interop Part I: Shows how to use C# to interoperate with COM objects.
  • COM Interop Part II: Shows how to a use a C# server together with a C++ COM client.
  • Commandline: Demonstrates simple command-line processing and array indexing.
  • Condiational Methods: Demonstrates conditional methods, which provide a powerful mechanism by which calls to methods can be included or omitted depending on whether a symbol is defined.
  • Delegates: Shows how delegates are declared, mapped to static and instance methods, and combined into multicast delegates.
  • Events: Shows how to declare, invoke, and configure events in C#.
  • Explicit Interface: Demonstrates how to explicitly implement interface members and how to access those members from interface instances.
  • Generics: Shows how to make generic collection classes that can be used with the foreach statement.
  • Hello World: A Hello World application.
  • Indexers Part I: Shows how C# classes can declare indexers to provide array-like access to objects.
  • Indexers Part II: Shows how to implement a class that uses indexed properties. Indexed properties enable you to use a class that represents an array-like collection.
  • Libraries: Shows how to use compiler options to create a DLL from multiple source files; also, how to use the library in other programs
  • Named and Optional (C# 4.0): Demonstrates Named and Optional parameters, an alternative to method overloads
  • Nullable: Demonstrates value types, such as double and bool, that can be set to null
  • Office Sample (C# 4.0): Demonstrates how Dynamic and COM Interop make it easy to call Microsoft Office in C# 4.0
  • OLEDB: Demonstrates how to use a Microsoft Access database from C# by creating a dataset and adding tables to it.
  • Operator Overloading: Shows how user-defined classes can overload operators
  • Partial Types: Demonstrates how classes and structures can be defined in multiple C# source-code files
  • PInvokeShows how to call exported DLL functions from C#
  • Properties: Shows how properties are declared and used; also demonstrates abstract properties
  • Python Sample (C# 4.0): Learn how to call a Python script by using the Dynamic feature in C# 4.0
  • Security: Discusses .NET Framework security and shows two ways to modify security permissions in C#: using permission classes and permission attributes
  • Simple Variance (C# 4.0): See how Covariance and Contravariance are supported in generic interfaces and delegates
  • Structs: Shows how to use structs in C#.
  • Threading: Demonstrates various thread activities such as creating and executing a thread, synchronizing threads, interacting between threads, and using a thread pool
  • Unsafe: Shows how to use unmanaged code (code that uses pointers) in C#
  • User Conversions: Shows how to define conversions to and from user-defined types
  • Versioning: Demonstrates versioning in C# by using the override and new keywords
  • XML Documents: Shows how to document code by using XML
  • Yield: Demonstrates how to use the yield keyword to filter items in a collection

LinqSamples

These samples help you learn LINQ quickly. They also act as a reference and guide for those with existing LINQ experience. A few handy utilities are also included. They are available in the LinqSamples folder.

  • DynamicQuery: Code to create LINQ queries at run time.
  • LinqToNorthwind: A basic example of how to use LINQ To SQL to query a database
  • LinqToXmlDataBinding: Bind LINQ to XML code to WPF controls
  • ObjectDumper: A utility for writing the output from a LINQ query to the screen in text mode
  • PasteXmlAsLinq: A Visual Studio addin that automatically converts XML to LINQ to XML.
  • QueryVisualizer: Allows LINQ to SQL developers to see the SQL for their query, and also to see the results of the query in a grid.
  • Reflector: Use LINQ to right queries against the objects in your code using the Reflection APIs
  • RSS: This sample acts as a tiny web server that aggregates several RSS feeds
  • SampleQueries: This is the most important sample and contains about 500 examples of how to use each of the query operators in LINQ to Objects, LINQ to SQL, LINQ to XML and LINQ to DataSet.
  • SimpleLambdas: Several examples of how to write and use lambda expressions
  • SimpleLinqToObjects: The hello world of the LINQ samples. This shows you how easy it is to do simple queries of in-memory objects using LINQ to Objects.
  • SimpleLinqToXml: Get started using LINQ to XML.
  • WebServiceLinqProvider(TerraService): A custom LINQ provider and client for the TerraServer-USA Web service.
  • Whitepapers: The following papers are stored in this directory in Word format:
    • LINQ Project Overview
    • LINQ to SQL Overview for C# and VB
    • Standard Query Operators
    • LINQ to XML Overview
  • WinFormsDataBinding: Learn how to display LINQ queries with grids in a Windows form. It includes a one to many query example.
  • XQuery: Another simple LINQ to XML sample query. This sample shows the minimal code necessary to write a LINQ to XML query

About the author

You have probably figured out by now that my name is Bryan Avery (if not, please refer to your browser's address field).  Technology is more than a career to me - it is both a hobby and a passion.  I'm an ASP.NET/C# Developer at heart...

Month List