Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, 22 October 2017

C# Async Programming - Tasks for dummies

There are umpteenth articles / blogs / guides about the Task-based Asynchronous Pattern used in C# for asynchronous programming. However, I feel that explanations are often convoluted and difficult to follow for something new to language / programming. This week, I explained the pattern to a graduate following some review comments and couldn't find an easy-to-understand article, so thought to explain it myself here.

This will be a series of blogs. I will try to keep it as simple as possible without compromising on completeness. Starting with one of the most basic concept - "The Task".

What is a Task?
Task is the C# abstraction of an asynchronous operation. In other words, it some series of code that executes asynchronously. It may or may/not return a result. 

How are Tasks created?
Tasks can be created explicitly by creating an object of type Task or Task or implicitly by running an async method. For example, both of these expressions end up resulting a task

var task = Task.Run( () => { … });

Func taskFunction = ( async () => { await foo() } ); taskFunction.Invoke();

Tasks and Threads
There are some differences when tasks are created explicitly or implicitly but let's not go there. 

There is a common misunderstanding that creating a task means running on a new thread. This is not true. Whether or not task creates a new thread depends upon how it is created.

For tasks created using Task Parallel Library, using Task.Run() for instance, a thread is created with the task. Running the following code 

              
Console.WriteLine($"Application Thread ID : {Thread.CurrentThread.ManagedThreadId}");
Task.Run(() =>
{
Thread.Sleep(30);
Console.WriteLine("Inside Task");
Console.WriteLine($"Task Thread ID : {Thread.CurrentThread.ManagedThreadId}");
});

Will produce

Application Thread ID : 2
Back to application Thread ID : 2
Inside Task

Task Thread ID : 3

Tasks created by async methods DO NOT create a new thread. Once once task is blocked, control is shifted to other task that is in ready state. 

For example, the following code 

Console.WriteLine($"Application Thread ID : {Thread.CurrentThread.ManagedThreadId}");
Func localTask = (async () =>{Console.WriteLine("Inside Task");Thread.Sleep(30); 
Console.WriteLine($"Task Thread ID :{Thread.CurrentThread.ManagedThreadId}");
});
localTask.Invoke();               
  
Will produce 

Application Thread ID : 2
Inside Task

Back to application Thread ID : 2
Task Thread ID : 2

Note that the thread Id is the same. This means that tasks, unless created by task parallel library, do not run in parallel. They share the same thread and uses context switching to pass control as tasks are blocked and become available again.

The Await Operator
This brings us nicely to the await operator. In simplest words, the await operator cause context switching. The operator is used when executing code block needs to get a result from a task that is running asynchronously. Calling await will block the current routine, only to be returned when the task it is waiting on has completed.

Conclusion
I hope this post will help people in understanding C# tasks. Some of the key take away from this post
  • Tasks can be explicitly using Task Parallel Library or implicitly using async keyword.
  • Task are not same as threads. Some tasks are created in a new thread - the ones created by TPL for instance. While others are created on the same thread.

Monday, 9 October 2017

Migrating ASP.NET MVC website to ASP .NET Core

I maintain an ASP.NET MVC website that I have been meaning to move to ASP.NET Core, but found the .Net Core 1.1 library rather limited. With the release of .NET Core 2.0 and ASP.NET Core 2.0, we decided to migrate the websites to the new framework. The site has been operational since October 2010 and was built using ASP.NET MVC 2.0. It has gone through various bouts of upgrades and is currently using ASP.NET MVC 5.2.0, which forms the baseline of this conversion. I had several discoveries along the way so thought to blog about them. 

In this post, I am going to write about prep and moving our "Model" to Entity Framework .Core 2.0


Background

The model of our website was built using Entity Framework code first. All database operations were performed using repository pattern. Our repository interface looks as follows

    public interface IRepository : IDisposable where TEntity : class
    {
        IQueryable GetQuery();
        IEnumerable GetAll();
        IEnumerable Find(Expression> predicate);
        TEntity Single(Expression> predicate);
        TEntity First(Expression> predicate);
        void Add(TEntity entity);
        void Delete(TEntity entity);
        void Attach(TEntity entity);
        void SaveChanges();
        DbContext DataContext { get; }
    }

We use interface inheritance to create repository for each of our model objects, so for a object "Token", the repository looks like following


    public interface ITokenRepository : IRepository
    {
    }

With the interface inheritance in place. our single generic repository class can the logic for database operations as shown below

public class Repository : IRepository where TEntity : class
    {
        private DbContext _context;

        private IDbSet _dbSet;

        private static string _connectionString = string.Empty;

        public Repository(IDataContextFactory dbContextFactory)
        {
            if (string.IsNullOrWhiteSpace(dbContextFactory.ConnectionString))
            {
                _context = dbContextFactory.Create(ConnectionString);
            }
            else
            {
                _context = dbContextFactory.Create();
            }
            
            _dbSet = _context.Set();
        }

        public Repository(DbContext context)
        {
            _context = context;
            _dbSet = _context.Set();
        }

        public DbContext DataContext
        {
            get
            {
                return _context;
            }
        }
        public IQueryable GetQuery()
        {
            return _dbSet;
        }

        public IEnumerable GetAll()
        {
            return GetQuery().AsEnumerable();
        }

        public IEnumerable Find(Expression> predicate)
        {
            return _dbSet.Where(predicate);
        }

        public TEntity Single(Expression> predicate)
        {
            return _dbSet.SingleOrDefault(predicate);
        }

        public TEntity First(Expression> predicate)
        {
            return _dbSet.FirstOrDefault(predicate);
        }

        public void Delete(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            _dbSet.Remove(entity);
        }

        public void Add(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            _dbSet.Add(entity);
        }

        public void Attach(TEntity entity)
        {
            _dbSet.Attach(entity);
        }

        public void SaveChanges()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
        }

        public static string ConnectionString 
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    _connectionString = ConfigurationManager.ConnectionStrings["Rewards"].ConnectionString;
                }

                return _connectionString;
            }
        }
    }

The class above does all the heavy lifting for us. We just need to define classes that implement each of our models' repository interface. For our model Token, it would be


public class TokenRepository : Repository , ITokenRepository
    {
        public TokenRepository(IDataContextFactory dbContextFactory)
            : base(dbContextFactory)
        {   
        }

        public TokenRepository(DbContext dataContext) 
            : base(dataContext)
        {
        }
    }


Entity Framework Core 2.0 limitations

1. No Many-To-Many Relationship

The biggest issue we have encountered while migrating to .Net Core 2.0 is lack of resolution for Many-To-Many relationships. This is an open issue, which haven't been resolved yet. For us, it means a lot of re-work.

With the POCO way of working, you would start with writing your domain model and your write your business logic using models, without really thinking about relational database details. We have a lot of code where our LINQ queries were based on domain model relationships. Now, we need to re-work all those. 

This, in my mind, is a major issue and though ways to resolve this issue, it prevents Entity Framework .Core from being a true ORM tool. 

As an example, consider you have two entities Parent and Student in your model, where a student can have multiple parents and a parent can have multiple students. With Entity Framework 6, the model definition was sufficient to imply the correct type of relationship. If you have to do it explicitly, you could do it at the time of model creation like below
modelBuilder.Entity()
              .HasMany(p => p.Parents)
              .WithMany(r => r.Students)
              .Map(m =>
              {
                  m.ToTable("ParentStudents");
                  m.MapLeftKey("Student_ID");
                  m.MapRightKey("Parent_ID");
              });
You can then go on and work with defining a collection of Parents in Students class and a collection of Students in Parent class. The .WithMany() method  is not there in Entity Framework Core.

The lack of Many-To-Many feature in EF Core is hard to justify. POCO came out as a good model for domain driven development and not supporting many-to-many in a domain driven world is hard to justify. We didn't want to "dilute" the model with resolving entities, so we decided to "implement" the many-to-many resolution in our code. This series of post describes a good way of keeping domain relationship in our objects, so that there is no change in business logic in other parts of the application.


2. IDbSet Interface 

The IDbSet interface was removed in Entity Framework 6.0, because the team were looking to add new operations to it without defining a new set of interfaces. This is pretty well documented in EF 6.0 design decisions. I do not agree to this decision as it breaks the whole promise of interface as immutable being. The EF team wanted to avoid creating interfaces like IDBSet2, etc for more functions they decided to do away with it. However, the interface is still present in the in EntifyFramework 6.0 library, so our code still worked. Now we had to replace any use of IDbSet with the DBSet class. Also, meant our test code had to be re-written as we mocked IDbSet to for results from database.


3. No Lazy Loading

The entity framework does not support lazy loading as of yet. There is an open issue for it on github.  The feature request is in the backlog of EF team but there is no date of adding it yet. Lazy loading is the default behaviour of Entity Framework and would be there for you if you have the navigation property defined as virtual. This is another big way in which Entity Framework core breaks backward compatibility. 

The way around is to "Eager Loading" i.e. ensure that you use the .Include("") and .ThenInclude("") method in all places, where you are relying on Lazy loading. This is no simple as it's easy to miss it out at placed and the error is only manifested at run time. One way of go about doing it, is to find references of all virtual properties and add .Include("") where the object is "hydrated".


4. No GroupBy Translation

Entity Framework Core 2.0 doesn't support translate Group By to SQL. So, if your application is using GroupBy() method, you might need to take a look for alternatives. Fortunately, more support for Group By is getting added in EF Core 2.1.

The only way to resolve this issue without punitive performance impact is to move the logic to stored procedures. We were using GroupBy mostly in our reports, which were already a candidate to use stored procedures. So, although there was some work involved but the result was much better performance.


Final Words...

My experiences with migrating code from Entity Framework 6.0 to Entity Framework Core 2.0 would not have uncovered all pertaining issues in migration process but this post might help out someone who is looking to take the plunge. 

In my view, Entity Framework Core 2.0 is still a bit under cooked but if you are willing to take do the extra effort, it has enough functionality for you to move your model / data libraries to it.

Saturday, 23 September 2017

Extending Team Explorer in Visual Studio 2017

Visual studio extensibility has always been a great feature in Visual Studio and enhance the entire development experience. With Visual Studio 2017, there were a bunch of very substantial changes made with respect to extensibility. Most of these changes comes from the fact that Visual Studio now supports a lighter installation version with bare minimum feature installation as default. There is also the option to have multiple installation on the same machine. So, what does it mean for for extensions? 

VS2017 extensions now following the vsix v3 file format. If you have an extension for earlier visual studio versions and you want to port it to VS2017, it means a whole bunch of changes. Here, I am going to write an extension that demonstrate extending Team Explorer. We will create a very simple extension that has a button on Team Explorer, which will open notepad.

Project Creation & Dependencies

Let's start with creating a new extensibility vsix project. You will only see the option if you had selected the VS SDK option while installing visual studio. Let's call our project TeamExplorerExtSample. Visual Studio 2017 uses .Net Framework 4.6.1, so we select this version.



Once the project is created, you will see a couple of web files and a file called source.extension.vsixmanifest, which contains extension information. We will come to this file later.

Now let's add references to the assemblies we would need to extend Team Explorer. Note that with visual studio 2017, assemblies are not added to GAC so we would need to make sure that all desired assemblies are included in the vsix. To display a navigation button in team explorer, we would need to implement the interface ITeamExplorerNavigationItem2, so we would need to add references to the following assemblies
  •     Microsoft.TeamFoundation.Controls
  •     System
  •     System.ComponentModel.Composition
  •     System.Drawing

VSIX Manifest file:

The manifest file contains information about the extension, it's dependencies, assets and pre-requisites. Double click on the source.extension.vsixmanifest to see details. To extend Team Explorer, the key thing to remember is to add the assembly containing classes that implement Team Explorer interfaces as a MEF component. This will ensure that visual studio loads it up when loading team explorer.

Our VSIX manifest file looks like this


Extending ITeamNavigationItem2

Our extension will create a button in Team Explorer that opens up the notepad application. To do this, we need to extend the ITeamNavigationItem2 interface. The interface is found in Microsoft.TeamFoundation.Control assembly that we have already referenced. We will also need to add TeamExplorerNavigationItem attribute. Our very simple class looks as below.


namespace TeamExplorerExtSample
{
       using System;
       using System.ComponentModel;
       using System.Diagnostics;
       using System.Drawing;
       using Microsoft.TeamFoundation.Controls;
       [TeamExplorerNavigationItem("C9B2CF74-0C87-4CEA-ACA9-8CC1C816D7F3", 1800)]
       public class NotepadNavigationItem : ITeamExplorerNavigationItem2
       {
              public bool IsEnabled => true;
              public int ArgbColor => 0;
              public object Icon => null;
              public string Text => "Open Notepad";
              public Image Image => null;
              public bool IsVisible => true;
              public event PropertyChangedEventHandler PropertyChanged;
              public void Dispose()
              {
                     this.Dispose(true);
                     GC.SuppressFinalize(this);
              }
              protected virtual void Dispose(bool disposing)
              {
              }
              public void Execute()
              {
                     Process.Start("notepad.exe");
              }
              public void Invalidate()
              {
              }
       }
}

As you can see, the only matter we have got in the class is a call to Process.Start to start up notepad. The navigation item appears as below


Click on the button and a new instance of notepad opens up.

Conclusion:

Admittedly. this is a very simplistic extension but contains all the steps you need to extend Team Explorer. You can add classes to add Pages, Sections and Links in Team Explorer, add icons \ images and menu items. The code sample from post is here

Saturday, 12 January 2013

Of Microsoft Fakes, Internal Classes and Signing Keys


Recently there was a question raised in the community about using Microsoft fakes for internal classes and what should be specified in the InternalVisibleTo attribute in the AssemblyInfo file. There was some confusion so I thought it would be useful to write a detailed post about it.

For the purpose of this post, I created a class library (SimpleLibrary.dll) that contain two internal classes:

  1. TextFileReader: Responsible for reading contents from a given text file.
  2. Client: Uses the TextFileReader class.

We will create a simple unit test where we will use generated shims for the TextFileReader class, so that the test is not dependent upon the existence of a text file in the file system. The code for the two classes is as follows:

TextFileReader

namespace SimpleLibrary
{
using System.IO;

internal class TextFileReader{
internal string ReadFile(string fileName)
{
StreamReader file = null;
string text = string.Empty;
try{
file = new StreamReader(fileName);
text = file.ReadToEnd();
}
finally{
if (file != null){
file.Close();
file.Dispose();
}
}
return text;
}
}}

Client 


namespace SimpleLibrary
{
internal class Client {
private TextFileReader fileReader;

internal Client(TextFileReader fileReader){
this.fileReader = fileReader;
}

internal string TestMethod(string fileName){
return fileReader.ReadFile(fileName);
}
}}


As you can see, the TextReaderFile is an internal class with an internal method "ReadFile" and Client is another internal class that depends upon an instance of the TextReaderFile and uses it's "ReadFile" method.

SimpleLibrary.Test


Now lets create a unit test project to test our library, we will call it SimpleLibrary.Test. In order to test our internal classes in the unit test project, we will need to include the "InternalVisibleTo" attribute in the AssemblyInfo.cs file of the SimpleLibrary project as follows:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SimpleLibrary.Test")]

Our unit tests can now see the internal classes and we can write unit tests for these. However, if we want to generate fakes for the internal classes, we will also have to include "InternalVisibleTo" attribute for the fakes assembly as well.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SimpleLibrary.Fakes")]

Adding the above attribute will allow the generated SimpleLibrary.Fakes class to view internal classes and methods.

Now, we can generate fakes for the library by right clicking on the reference to SimpleLibrary and clicking on the "Add Fakes Assembly" option.

Our very simple unit test is as follows:


namespace SimpleLibrary.Test
{  
using Microsoft.QualityTools.Testing.Fakes;  
using Microsoft.VisualStudio.TestTools.UnitTesting;  
using SimpleLibrary.Fakes;      

[TestClass]      
public class ClientTest  
{      
[TestMethod]
public void TestReadFile()
{
using (ShimsContext.Create()) {

// Arrange
ShimTextFileReader shim = new ShimTextFileReader();              
shim.ReadFileString = (filename) => { return "The file content."; };              
var target = new Client(shim.Instance);              

// Act              
var actual = target.TestMethod(@"C:\somefile.txt");

// Assert              
Assert.AreEqual("The file content.", actual);          
}      
}  }}


The test creates a shim of the TextFileReader class and uses it while calling the TestMethod in the client class.

Strong Named Assemblies:


Now, lets consider that the assembly SimpleLibrary has to be strongly named, so will have to sign the assembly. We do that by generating a key file "SimpleLibraryKey" and use it to sign the assembly as shown

Now compile the solution and you will get the following errors

"Friend assembly reference "SimpleLibrary.Test" is invalid. Strong-name assemblies must specify a public key in their InternalVisibleTo declarations."
"Friend assembly reference "SimpleLibrary.Fakes" is invalid. Strong-name assemblies must specify a public key in their InternalVisibleTo declarations."

To resolve this, we need to sign our SimpleLibrary.Test assembly and change our InternalVisible attribute in the SimpleLibrary project to include the PublicKey as shown below


[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SimpleLibrary.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001006bec6379ed95c6180028a6bc797cdb256805f6dcb61cbdf4f3f3493c5c25efb411fa33472565a5b5426161fd16a6a10802ae710f2e6828d175a2346e33f3831520bcf00e8584919cdf34ed11e51bb988f624360aeadf9b4dc764adc8aeab9939ad209b35f17f2d63192288b0e9bbe5ac013c56d7575b9277cde19e1be7d74f8b")]

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SimpleLibrary.Fakes, PublicKey=00240000048000009400000006020000002400005253413100040000010001006bec6379ed95c6180028a6bc797cdb256805f6dcb61cbdf4f3f3493c5c25efb411fa33472565a5b5426161fd16a6a10802ae710f2e6828d175a2346e33f3831520bcf00e8584919cdf34ed11e51bb988f624360aeadf9b4dc764adc8aeab9939ad209b35f17f2d63192288b0e9bbe5ac013c56d7575b9277cde19e1be7d74f8b")]

Please note that by default the generated SimpleLibrary.Fakes.dll assembly will be signed with the same key as used in the original class. If we want, we can also use a different key to sign our fakes assembly. Recompile the project and we got errors similar to


"'SimpleClient' is inaccessible due to its protection level...."

The key step here is to include the KeyFile attribute in the Compilation element of the SimpleLibrary.Fakes file. The attribute will look like following, where Key file is the name of the key file used for signing the assembly

<Compilation KeyFile="SimpleLibraryKey.snk" />

Please note that the key file for the fakes assembly can be different from the original one. As long, as you are specifying the PublicKey of the key file specified in the Compilation attribute in the InternalVisible attribute, your code will compile and you can fake the internal classes.


Update 30/01/2013:

I have received some feedback and stand corrected on the key is used by Microsoft Fakes. The default key used by Fakes will always be the one shown below

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("SimpleLibrary.Fakes, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e92decb949446f688ab9f6973436c535bf50acd1fd580495aae3f875aa4e4f663ca77908c63b7f0996977cb98fcfdb35e05aa2c842002703cad835473caac5ef14107e3a7fae01120a96558785f48319f66daabc862872b2c53f5ac11fa335c0165e202b4c011334c7bc8f4c4e570cf255190f4e3e2cbc9137ca57cb687947bc")]


My original understanding was that the key used by Micorosft Fakes is the same key that signs the assembly  it is faking. This is obviously not correct and this is mentioned clearly in MSDN http://msdn.microsoft.com/en-us/library/hh708916.aspx.  You can of course use a different key and and in that case the &ltCompilation KeyFile=""> would be required.

Saturday, 5 January 2013

Mocking HttpWebRequest using Microsoft Fakes

In my last post, I detailed the use of  RegisterPrefix method of the WebRequest class to mock calls to HttpWebRequest. I also mentioned that an alternative mechanism to isolate calls to HttpWebRequest was to use the Shims feature in Microsoft Fakes Framework. In this post, I will demonstrate how to do so.

Microsoft Fakes provides two ways of achieving isolation of "code under test" from underlying assemblies namely Stubs and Shims. The Stubs feature generates a dummy class implementing the interface to be stub'ed out allowing you to specify responses made to different method calls in your code. Shims, on the other hand, divert calls within the code of the underlying classes to the code you have written in your definition of the Shim. I wrote a post about Microsoft Fakes sometimes ago.

Coming back to the topic, below is a class that makes a call to the web service.

namespace FakesClass
{
    using System;
    using System.Net;
    /// <summary>
    /// Sample web service client class
    /// </summary>
    public class WebServiceClient
    {
        /// <summary>
        /// Calls a web service with the given URL
        /// </summary>
        /// <param name="url">The web service's URL</param>
        /// <returns>True if the services responds with an OK status code (200). False Otherwise</returns>
        public bool CallWebService(string url)
        {
            var request = CreateWebRequest(url);
            var isValid = true;
            try
            {
                var response = request.GetResponse() as HttpWebResponse;
                isValid = (HttpStatusCode.OK == response.StatusCode);
            }
            catch (Exception ex)
            {
                isValid = false;
            }
            return isValid;
        }

        /// <summary>
        /// Creates an HttpWebRequest object
        /// </summary>
        /// <param name="url">The URL to be called.</param>
        /// <returns>An HttpWebRequest.</returns>
        private static HttpWebRequest CreateWebRequest(string url)
        {
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Method = "GET";
            request.Timeout = 1000;
            request.Credentials = CredentialCache.DefaultNetworkCredentials;
            return request;
        }
    }
}
The CallWebService method takes in the url string of the web service to be invoked and returns true or false depending upon whether the HttpResponse has a status code of 200 (HTTP OK) or not. This is a very simple example. You can get your response object to return a response string of whatever your unit test requirements is.

Now that we have a class to unit test, I created a unit test project adding a project reference to the project containing the WebServiceClient class.

Once the unit test project is created, the next step is to generate Fakes class for the HttpWebRequest, HttpWebResponse and WebRequest class. Since, these class reside in the System namespace, the way to generate fake class is to right click on the System Reference and click on the option "Add Fakes Assembly" as shown:


Please note that to date this option (and Microsoft Fakes) is only available for the Ultimate edition of Microsoft Visual Studio 2012.

The "Add Fakes Assembly" option will add the following two assemblies as reference in your unit test project
  • mscorlib.4.0.0.0.Fakes
  • System.4.0.0.0.Fakes
and also add a folder called "Fakes" with the following two files added to it
  • mscorlib.fakes
  • System.fakes




The reason that there are two set of files are added to the solution is because the System namespace is implemented in two assemblies. Since, we are faking only classes in System.Net namespace, we can safely remove the reference mscorlib.4.0.0.0.Fakes and the file mscorlib.fakes. The final references looks as follows
The .fakes file contain details of the files that would be shim'ed or stubbed in the tests. Since, we want to use shim for WebRequest, HttpWebRequest and HttpWebResponse, change the contents of the System.fakes file to the following text.

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
    <Assembly Name="System" Version="4.0.0.0"/>
    <StubGeneration>
        <Clear/>
    </StubGeneration>
    <ShimGeneration>
        <Clear/>
        <Add FullName="System.Net.WebRequest!"/>
        <Add FullName="System.Net.HttpWebRequest!"/>
        <Add FullName="System.Net.HttpWebResponse!"/>
    </ShimGeneration>
</Fakes>
As you can see, we have cleared out all stub generation and added the three desired classes in the <ShimGenerate\> section. Now, we are all ready to use the generated shims in our unit tests.

The name convention that Microsoft Fakes uses for stubs and shims is Stub{ClassName} & Shim{ClassName} respectively so our shim'ed classes HttpWebRequest class will be called ShimHttpWebRequest class and so on.  The following unit test demonstrates using the Shims.

[TestMethod]
public void TestThatServiceReturnsAForbiddenStatuscode()
{
    using (ShimsContext.Create())
    {
        // Arrange
        var requestShim = new ShimHttpWebRequest();
        ShimWebRequest.CreateString = (uri) => requestShim.Instance;
        requestShim.GetResponse = () => { return new ShimHttpWebResponse() { StatusCodeGet = () => { return HttpStatusCode.Forbidden; } }; };
        var client = new WebServiceClient();
        var url = "http://testwebservice.mywebservice.com";
        var expectedResult = false;
        //Act
        bool actualresult = client.CallWebService(url);
        //Assert
        Assert.AreEqual(expectedResult, actualresult);
    }
}
Please note that the test makes a call to ShimContext.Create and creates objects of type ShimWebRequest and ShimWebResponse. Also, the call to ShimWebRequest returns a ShimHttpWebRequest object.

Updated 23/01/2013: Here is the link to the visual studio solution used in this post and my previous post about mocking HttpWebRequest. The solution contains two unit test projects for testing the same class, one illustrating the use of RegisterPrefix method and the other using the Shim feature of Microsoft Fakes.