If you get the above error when trying to add a WCF service reference that you have previously deleted then try:

  • deleting the Service References.DeviceService.Reference.cs.dll file you’ll find under obj\Debug\TempPE. 
  • deleting the service folder you’ll still find under Service References on disk, even though you deleted the reference in Visual Studio.
  • commenting out all references to the service’s namespace in your code
  • rebuilding

Having come third in the first event "Show Off" entry, for PDC 2005, I decided to submit an entry for the 2008 PDC.

I decided to base my entry on a .NET code injection blog article I’d written a couple of months ago.  I got a very positive response from the people running the contest, although on the night I didn’t actually win.

I missed the showing of my entry because I was attending a dinner thrown by Microsoft Switzerland for the people that attended the PDC from Switzerland.

In any event, here is my entry: http://damianblog.com/DamianMehersPDC2008ShowOff.wmv

 

I just attended the Microsoft PDC in LA.  One of the many excellent sessions was a pre-conference on WCF, part of which was presented by Ron Jacobs. Ron did a fantastic job of explaining WCF REST Services and the WCF REST Starter Kit.

One of the examples he showed from the WCF REST Starter kit was an example where the response type (JSON or XML) is dynamically set based on the HTTP request’s requested content type in the "Accepts" HTTP Header.

That example works by switching between two different operation implementations (methods).

I liked the idea of using the requested content type to automatically return JSON or XML depending on the requested content type, but I wasn’t so keen on having to implement two methods.

I thought I’d try to get a similar thing working but using a single operation implementation which is called no matter whether or JSON or XML are requested.

The DynamicResponseType attribute

This is how it works.  You decorate your method with an additional DynamicResponseType attribute which I have defined:

   1: [ServiceContract]
   2: [ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
   3: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   4: public class Service1
   5: {
   6:     [OperationContract]
   7:     [WebGet(UriTemplate = "GetData?param1={i}&param2={s}")]
   8:     [DynamicResponseType]
   9:     public SampleResponseBody GetData(int i, string s)
  10:     {
  11:         return new SampleResponseBody() { 
  12:             Name = "Test",
  13:             Value = s, 
  14:             Time = DateTime.Now.ToShortTimeString() 
  15:         };
  16:     }
  17: }
  18:  
  19: public class SampleResponseBody
  20: {
  21:     public string Name { get; set; }
  22:     public string Value { get; set; }
  23:     public int IntValue { get; set; }
  24:     public string Time { get; set; }
  25: }

An example client

Then when the client requests a specific type (XML or JSON), it is served automatically.

Below I have a pure HTML/Javascript client with two buttons, each of which call the same  GetWebRequest function when they are clicked but passing a different requested content type as a parameter.  The GetWebRequest function issues an HTTP request to the WCF operation I showed above.

The first button says it wants JSON, and the second XML.  This is done by setting the "Accept" request header:

   1: <body>
   2:     <form id="form1" runat="server">
   3:     <div>
   4:     
   5:     <input type="button" value="Click to request JSON" 
   6:         onclick="GetWebRequest('application/json');" />
   7:     
   8:     <input type="button" value="Click to request XML" 
   9:         onclick="GetWebRequest('application/xml');" />
  10:     
  11:     </div>
  12:     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
  13:     </form>
  14:  
  15: <script type="text/javascript">
   1:  
   2:   function GetWebRequest(acceptType) {  
   3:     var wRequest = new Sys.Net.WebRequest();
   4:     wRequest.get_headers()["Accept"] = acceptType;
   5:     var url = "/Service1.svc/GetData?param1=12&param2=";
   6:     wRequest.set_url(url + new Date());
   7:     wRequest.set_httpVerb("GET");
   8:     wRequest.add_completed(OnWebRequestCompleted);
   9:     wRequest.invoke();
  10:   }
  11:  
  12:   function OnWebRequestCompleted(executor, eventArgs) {
  13:     alert(executor.get_responseData());
  14:   }

</script>

  16: </body>

This is the form that gets displayed initially:

image

When you click on the first button we request JSON from the WCF Service operation:

image

When you click on the second button we request XML from the same WCF Service operation:

image

How it works.

I’ve created my own  WCF ServiceHostFactory which I wire up in the SVC file:

   1: <%@ ServiceHost Language="C#" 
   2:     Debug="true" 
   3:     Service="WcfService2.Service1" 
   4:     CodeBehind="Service1.svc.cs" 
   5:     Factory="DamianBlog.ServiceHostFactory2Ex" %>

In my ServiceHostFactory2Ex class I ensure that my own WebServiceHost class gets created.

Then in my own WebServiceHost I ensure that my own WebHttpBehavior replaces the standard one.

Next in my own WebHttpBehavior I override the GetReplyDispatchFormatter method and return my own IDispatchMessageFormatter.

In my own IDispatchMessageFormatter I implement the SerializeReply method and then use a JSON formatter or XML formatter depending on the "Accepts" HTTP request header which I pick up from the OperationContext.Current.RequestContext.RequestMessage.

The full source is available for download here http://damianblog.com/WCFDynamicResponseDemo.zip.

Rob Jacobs blogs at http://blogs.msdn.com/rjacobs/

All the documentation says to press two-fingers and click, but actually you must press down three fingers and then click to right-click when running Vista, Boot Camped on the new MacBook Pros (late 2008).

[Edited 23rd Oct to compress returned JavaScript]

I recently wrote a blog post showing how you can use controls from the AJAX Control Toolkit in ASP.NET MVC applications, specifically the ListSearchExtender.  Stephen Walther also wrote one on using the Calendar control here.

One thing that bugged me was that it was painful to find out what scripts a particular control depended on, so that they could be included in the JavaScript used to initialize a control.

I decided to create a simple MVC Controller/View that would return back all the JavaScript required for any particular ASP.NET AJAX Control Toolkit control.

This is the old code for using the ListSearchExtender in an ASP.NET MVC View:

<select id="Countries">
    <option>Switzerland</option>
    <option>United Kindom</option>
    <option>United States</option>
</select>

<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.Common.Common.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.ExtenderBase.BaseScripts.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.Compat.Timer.Timer.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.Animation.Animations.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.Animation.AnimationBehavior.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.PopupExtender.PopupBehavior.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.PopupControl.PopupControlBehavior.js" type="text/javascript"></script>
<script src="/Scripts/AjaxControlToolkit.ListSearch.ListSearchBehavior.js" type="text/javascript"></script>

<script type="text/javascript">
Sys.Application.initialize();
Sys.Application.add_init(function() {
    $create(AjaxControlToolkit.ListSearchBehavior,
        { "id": "ListBox1_ListSearchExtender" },
        null, null, $get("Countries"));
});
</script>

This is the new code to pull in the dependencies:

<select id="Countries">
    <option>Switzerland</option>
    <option>United Kindom</option>
    <option>United States</option>
</select>

<script src="/ControlDependencies/Get?extenderTypeName=AjaxControlToolkit.ListSearchExtender" type="text/javascript"></script>

<script type="text/javascript">
Sys.Application.initialize();
Sys.Application.add_init(function() {
    $create(AjaxControlToolkit.ListSearchBehavior,
        { "id": "ListBox1_ListSearchExtender" },
        null, null, $get("Countries"));
});
</script>

You’ll see that all the individual script includes have been replaced by a single call to the Get action on the ControlDependencies controller.

This is the source to the controller:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
using AjaxControlToolkit;

namespace TestDependencies.Controllers {
public class ControlDependenciesController : Controller {
    readonly Assembly toolkitAssembly =
        typeof(AjaxControlToolkit.Utility).Assembly;

    [OutputCache(VaryByParam = "extenderTypeName",
                 Duration = 86400,  // One day
                 Location = System.Web.UI.OutputCacheLocation.Client)]
    public ActionResult Get(string extenderTypeName) {

        if (string.IsNullOrEmpty(extenderTypeName)) {
            return new EmptyResult();
        }

        // Get the type representing the extender we are handling
        Type extenderType = toolkitAssembly.GetType(extenderTypeName,
                                                    false);
        if(extenderType == null) {
            return new EmptyResult();
        }

        // What other extenders does this one depend on?
        Stack<Type> dependencies = new Stack<Type>();
        AddDependencies(extenderType, dependencies);

        // What scripts do those extenders require?
        List<string> scriptsToInclude = new List<string>();
        GetDependencyScripts(dependencies, scriptsToInclude);

        return PartialView(scriptsToInclude);
    }

    // Find the types that the specified extender type depends on
    static void AddDependencies(Type extenderType,
                                Stack<Type> dependencies) {
        dependencies.Push(extenderType);
        Attribute[] attributes =
            Attribute.GetCustomAttributes(extenderType,
                      typeof(RequiredScriptAttribute));

        foreach (RequiredScriptAttribute attribute in attributes) {
            AddDependencies(attribute.ExtenderType, dependencies);
        }
    }

    // Find the scripts used by the specified extender types
    static void GetDependencyScripts(IEnumerable<Type> dependencies,
                                     ICollection<string> scripts) {
        foreach (Type dependency in dependencies) {
            Attribute[] attributes =
                Attribute.GetCustomAttributes(dependency,
                           typeof(ClientScriptResourceAttribute));

            foreach (ClientScriptResourceAttribute attribute in attributes) {
                if (!scripts.Contains(attribute.ResourcePath)) {
                    scripts.Add(attribute.ResourcePath);
                }
            }
        }
    }
}
}

The View is a User Control that simply outputs all of the required scripts.  This is the code-behind:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Web.Mvc;

namespace TestDependencies.Views.ControlDependencies {
  public partial class Get : ViewUserControl<List<string>> {

    protected void Page_Load(object sender, EventArgs e) {
      Response.ContentType = "application/x-javascript";

      // Get compressed stream if possible
      Stream outputStream = GetOutputStream();

      using(StreamWriter outputWriter = new StreamWriter(outputStream)) {

        // Standard AJAX library
        string script = File.ReadAllText(
                              MapPath("/Scripts/MicrosoftAjax.js"));
        outputWriter.WriteLine(script);

        // Required scripts
        foreach(string scriptPath in ViewData.Model) {
          script = File.ReadAllText(MapPath("/Scripts/" + scriptPath));
          outputWriter.WriteLine(script);
        }

      }
      Response.End();
    }

    // Compress scripts if possible -- stolen from ToolkitScriptManager
    // in AJAX Control Toolkit
    private Stream GetOutputStream() {
      Stream outputStream = Response.OutputStream;
      if(!Request.Browser.IsBrowser("IE") ||
                         (6 < Request.Browser.MajorVersion)) {
        foreach(
          string acceptEncoding in (Request.Headers["Accept-Encoding"] ??
                                       "").ToUpperInvariant().Split(',')) {
          if("GZIP" == acceptEncoding) {
            Response.AddHeader("Content-encoding", "gzip");
            outputStream = new GZipStream(outputStream,
                                          CompressionMode.Compress);
            break;
          }
          if("DEFLATE" == acceptEncoding) {
            Response.AddHeader("Content-encoding", "deflate");
            outputStream = new DeflateStream(outputStream,
                                             CompressionMode.Compress);
            break;
          }
        }
      }
      return outputStream;
    }
  }
}

The ASCX is empty:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Get.ascx.cs" Inherits="TestDependencies.Views.ControlDependencies.Get"  %>

There are two advantages to using this technique.  Firstly performance should be increased since all the required scripts are returned in a single response.  Secondly you don’t have to manually work out the dependencies for a particular ASP.NET AJAX Control Toolkit control.

Using Moq ExpectSet

September 17th, 2008

I am trying out Moq, having used RhinoMocks a fair bit in the past.

I was having trouble using the ExpectSet method which verifies that a property has been set, and a google search found nothing that directly answered my question.  I wanted to know how to verify that the value set is what was expected.

It turns out that you need to define a callback in which you have the assertion to verify that the property has been set to the correct value.

[TestMethod]
public void TestAppleShiner() {

    // Mock the interface being passed to the class to be tested
    var fruit = new Mock<IFruit>();

    // Define the expectation that the Colour property will be
    // set to Green
    fruit.ExpectSet(f=>f.Colour).Callback(
        setColor=>Assert.AreEqual("Green", setColor)).Verifiable();

    // Run the test
    ApplePolisher applePolisher = new ApplePolisher();
    applePolisher.Polish(fruit.Object);

    // Verify that the test passed (note .Verifiable on the ExpectSet)
    fruit.VerifyAll();
}

public interface IFruit {
    string Colour { get; set; }
}

public class ApplePolisher {
    public void Polish(IFruit fruit) {
        fruit.Colour = "Green";
    }
}
 
After ExpectSet, call the Callback method giving the name of the variable to hold the passed in value, and then the assertion with regards to its value.

BeebMC 2.3 Released

September 14th, 2008

Download it here: http://www.beebmc.com/

Fixes a bug reported by a couple of people where although it launched properly, it would not play music.

TraceJS V2 R.I.P.

September 9th, 2008

A couple of years ago I posted a small blog entry on a throwaway tool that I had created that uses the Debug API to log all JavaScript that Internet Explorer executes.

A year ago I decided to take a year off from consulting, mainly to spend a lot more time with our kids while they are still young, but also to have some time to explore some product ideas.

The first idea I wanted to explore was whether or not it might be possible to extend the idea I’d had in that older blog post to actually make a commercial product that would not only trace all JavaScript, but would also show call stacks, and show how often functions were executed.

Technically it was tricky because I wanted my custom JavaScript debugger to be loaded in-process into Internet Explorer, since I thought that this might speed it up considerably. The secret turned out to be that I needed to pass a special flag to IDebugProgramProvider2->GetProviderProcessData (the PFLAG_DEBUGGEE flag).

After a couple of months of development I finally got it all working.

You started it from the IE Tools menu:
image

This would create a separate TraceJS dialog: image

Then as you access a page that contains JavaScript the TraceJS Window shows the statements that are being executed:image image

Once you’d captured the JavaScript execution, you could replay the executed JavaScript, either step-by-step, or continually at a pace you define:image

Finally you could  drill-down to see which functions are called the most, and who calls them:image

I had it all working in my initial build environment, which was XP based.  Then I tested in Vista, and I couldn’t get it to work  (the GetProviderProcessData failed).  Ouch!

I took a step back, gave the product a long hard look, and decided to stop development.  It was too slow (despite being entirely in-process), I couldn’t implement features I needed such as timing (the debugging/tracing added too much overhead), and I couldn’t get it working on Vista.

Now that IE8 has similar profiling features I’m happy I stopped when I did.

Of course the biggest mistake I made was to register the domain names for the product before it was completed (tracejs.com, jsprof.com, jsprofiler.com and javascriptprofiler.com are all mine).

If there is one sure way to kill a product idea it is to register domain names before you’ve executed on the product idea itself :-).

There are a whole range of useful AJAX behaviors available in the ASP.NET AJAX Control Toolkit, and it would be cool to be able to use them from ASP.NET MVC. 

In this post I’ll show you how you can use one of the extenders that I created, the ListSearch Extender, with ASP.NET MVC.

Set up your ASP.NET MVC Project

To start create a new ASP.NET MVC project.

Next download the Microsoft AJAX Library, which contains the Javascript library used in the Microsoft ASP.NET AJAX implementation. Copy the MicrosoftAjaxLibrary folder in the ZIP you downloaded to the Content folder in your MVC project.

Now download the Script Only Files from the ASP.NET AJAX Control Toolkit and copy the AjaxControlToolkit folder in the ZIP to the Content f0lder in your MVC project.

Now that the folders are copied you need to make them visible to the project.  Open the Content branch of your project in the Solution Explorer, and then click on the Show All Files button:

 

Once you do this, you should see the two folders that you copied into the Content folder.  Right click on each folder and select Include In Project.

Now your MVC project will have access to the JavaScript files it requires.

Add the SELECT

To make use of these JavaScript libraries, open the Home action’s Index view under Views->Home->Index.aspx.  Modify the HTML to include a simple SELECT List:

<%@ Page Language="C#" ... %>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2> <%= Html.Encode(ViewData["Message"]) %></h2>
    <p>
        To learn more about ASP.NET MVC visit ...
    </p>

    <select id="Countries">
    <option>Switzerland</option>
    <option>United Kindom</option>
    <option>United States</option>
    </select>

</asp:Content>
 

Include the required Javascript files

Next you’ll need to have the page pull in the JavaScript files that are used by the ListSearch Extender:

<script type="text/javascript" src="/Content/MicrosoftAjaxLibrary/System.Web.Extensions/3.5.0.0/3.5.21022.8/MicrosoftAjax.debug.js"/>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Common.Common.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.ExtenderBase.BaseScripts.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Compat.Timer.Timer.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Animation.Animations.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.Animation.AnimationBehavior.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.PopupExtender.PopupBehavior.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.PopupControl.PopupControlBehavior.js" type="text/javascript"></script>
<script src="/Content/AjaxControlToolkit/3.0.20820.16598/3.0.20820.0/AjaxControlToolkit.ListSearch.ListSearchBehavior.js" type="text/javascript"></script>

 
You may need to change the version numbers depending on the versions of the Microsoft AJAX library and Toolkits you downloaded.
 
I found out which script files to include by creating a normal ASP.NET Project that used the ListSearch Extender, and set the ScriptManager’s ScriptPath property to a new folder I created in the project called /MicrosoftAjaxLibrary, to which I copied the same two folders that I copied to the Content folder above.  I accessed the page, and did a View Source to see what JavaScript was being used.
 

Initialize the Extender

Having included the required JavaScript files, you can now create a new ListSearch Extender and attach it to the SELECT you created above:

<script type="text/javascript">
    Sys.Application.initialize();
    Sys.Application.add_init(function() {
    $create(AjaxControlToolkit.ListSearchBehavior,
            { "id": "ListBox1_ListSearchExtender" },
            null, null, $get("Countries"));
    });
</script>
 

Access your page

 
Now when you run you’ll get the ListSearch Extender behavior attached to your SELECT:
 

Summary

 
Using the AJAX Control Toolkit is very straight-forward.  The trickiest part is determining exactly what script files you need to include.
 
Now you can use the whole set of behaviors that other people have created to add AJAX goodness to your ASP.NET MVC projects.

A couple of days ago I decided to move this blog from being hosted at Wordpress,com, to an account I have at Webhost4life.  You can add new domains to your account for only US$15 a year.

When I set the blog up at Wordpress.com, I ordered my custom domain (damianblog.com) and that is what I have been using.

Export your Wordpress.com hosted blog

The first thing I did was to export my blog from my Wordpress.com account, by logging in to Wordpress.com administration page for Damianblog, clicking on Manage, and then clicking on Export:

image

This generated an XML file which I saved on my local hard disk.

Installing Wordpress on webhost4life

Webhost4life offer a an automated installation of Wordpress using the "Php Free Plug-ins" item on the "Site Admin" tab of their control panel.  I first tried using this, however it currently installs version 2.0.3, which will not import the file I’d just exported from Wordpress.com.

After a little searching I came across this excellent page, which explains in detail what you need to do to set up the latest version of Wordpress.

It worked well for me, except for step 18 (giving NETWORK access) - I found I had to give access to IUSER_DEDI… and also IUSER_<webhost4life account name>.

I also created the zip at step 14 as ‘damianblog.zip’ and copied that to my root directory and then unzipped it, so that Wordpress was now installed under a ‘damianblog’ directory under my account root directory.

Setting up the damianblog DNS so that it points to Webhost4life

In the webhost4life control panel I went to the "Domain Name" item on the "Domains" tab in the control panel and added damianblog.com to map to the damianblog directory to which I’d installed Wordpress.

I paid my US$15, and I was given the name of two domain servers that I could now use to resolve damianblog.com.

Configuring your domain’s DNS servers to point to the webhost4life servers

In the Wordpress.com admin site I clicked on Upgrades and then on Domains (to the right of "Upgrades" and "Gifts") and saved the Customer Number shown at the bottom of the page, and then clicked on "Manage Your Domains" at the very bottom of the page.

This took me to a new page on securepaynet.net on which I entered my Customer Number that I just saved, and my password.  I clicked on damianblog.com and then clicked on "Nameservers" (the fourth tab), selected "Custom nameservers", and entered the name of the two name servers I’d been given when I set up the damianblog domain name in the Webhost4life control panel.

An hour or so later, when I pinged damianblog.com it returned my webhost4life IP address.

Panic

I went into my new Wordpress admin page on webhost4life, and clicked on Settings (on the right-hand part of the page), and made sure the Wordpress address (URL) was http://damianblog.com

I clicked on the Import link in the admin page, and imported the XML file I’d exported from the old blog hosted at Wordpress.com

I checked, and sure enough when I went to http://damianblog.com all was well.  I could relax.

As an afterthought I tried clicking on one of the links on the web that pointed to my blog.  It didn’t work.  Aggh.

It turns out that the default Permalink URL in my new blog was of the form http://damianblog.com/?p=123, whereas all my old postings hosted on Wordpress.com were of the form http://damianblog.com/2007/02/25/ajax-screencast/

I went to the Permalink section but none of the common settings were in the form I wanted (they all wanted to add ‘index.php’ to the URL).  I could configure a custom structure to be the way I wanted, but when you clicked on URLs the page was not found:

image

The solution was to create a small PHP file which handled the "URL Not Found" error and remapped the page as described here.  Just be careful when copying the PHP code from the web page because some of the single quotes are not the standard quotes that they should be.

Finally: the Simpla Theme

The new Wordpress installation did not come with the theme I’ve chosen: Simpla.  Installing it was pretty easy, I just unzipped the theme from http://ifelse.co.uk/simpla into the /wp-content/themes/ directory. 

Unfortunately none of my widgets showed on the right hand side.  I had to make a couple of small modifications to get that resolved.

Done

Now it all seems to be working properly and I can customize my installation as I wish.