Self Hosting an Old ASMX Web Service

Sometimes you’re stuck taking old tech and merging it with new tech.  The other day at work, I found myself wanting to self host an old ASMX web service from an simple WinForms app to support a simple simulator.  I was able to find a great post from the co-founders of Pluralsight Aaron Skonnard, all be it an old post, fascinating none the less.  I would recommend reading Aaron Skonnard’s article for more detail, in this post I will paraphrase the example with a link to my example code.

Download SelfHostedSoapService.zip

The reason why self hosting works so well now goes way back to Windows 2003/XP SP2.  Microsoft had rewritten its protocol stack for HTTP handling, http.sys which is now at the kernel level.  It is important to note that this gave rise to the abstracting .NET applications from being tied to IIS.  This is what all of the cool ASP.NET MVC OWIN stuff is written on top of and allows us to write a “simple” self hosted web server.  .NET 2.0 came out with managed classes to make this possible

  • HttpListener – configures and starts an listener for HTTP requests
  • HttpWorkerRequest  - abstract class used by ASP.NET to process requests
  • SimpleWorkerRequest – provides a simple implementation of HttpWorkerRequest to handle basic GET requests
  • ApplicationHost.CreateApplicationHost – creates application domain for hosting ASP.NET (caveat is assemblies must be in the GAC or in the bin folder of relative to running process)

I created 3 projects to hose a simple Calculator.asmx web service example:

  • Library – contains the HTTP listener and worker class
  • Console – starts the web server on a given port
  • WinFrom – uses the ASMX web service to execute calculator methods

 

Library contained 2 key classes.

HttpListenerWrapper.cs


This will host the HttpListener class so that we can run our process on a separate thread.  The code for this is below.

[sourcecode language='csharp'  padlinenumbers='true']
    /// <summary>
    /// A wrapper for the HttpListener so we can start and stop our listener.
    /// </summary>
    /// <seealso cref="System.MarshalByRefObject" />
    public class HttpListenerWrapper : MarshalByRefObject
    {
        private HttpListener _listener;
        private string _virtualDir;
        private string _physicalDir;

        public void Configure(string[] prefixes, string v, string p)
        {
            _virtualDir = v;
            _physicalDir = p;

            Console.WriteLine($"Configuring HTTP listener with virtual directory [{v}] and physical directory [{p}]");

            //  the HttpListener that will be used to extract request
            _listener = new HttpListener();

            // listener configuration for how http.sys will map incoming HTTP requests
            // can use http://*:8081 or http://+:8081.  for production use, wildcards should never be used
            foreach (string prefix in prefixes)
                _listener.Prefixes.Add(prefix);
        }

        public void Start()
        {
            _listener.Start();
        }

        public void Stop()
        {
            _listener.Stop();
        }

        public void ProcessRequest()
        {
            // receives the incoming request for processing
            HttpListenerContext ctx = _listener.GetContext();
            Console.WriteLine($"Request: {ctx.Request.RawUrl}");
            ;
            // create our worker that will act as our web server and allow ASP.NET to process its pipeline
            HttpListenerWorkerRequest workerRequest = new HttpListenerWorkerRequest(ctx, _virtualDir, _physicalDir);
            // process the request
            HttpRuntime.ProcessRequest(workerRequest);
        }
    }
[/sourcecode]

HttpListenerWorkerRequest.cs


This represents our web server that contains the methods needed to allow ASP.NET to process its pipeline.

[sourcecode language='csharp' ]
    /// <summary>
    /// Represents our web server which sets up the processing for ASP.NET
    /// </summary>
    /// <seealso cref="System.Web.HttpWorkerRequest" />
    public class HttpListenerWorkerRequest : HttpWorkerRequest
    {
        private HttpListenerContext _context;
        private string _virtualDir;
        private string _physicalDir;

        public HttpListenerWorkerRequest(
            HttpListenerContext context, string vdir, string pdir)
        {
            if (null == context)
                throw new ArgumentNullException("context");
            if (null == vdir || vdir.Equals(""))
                throw new ArgumentException("vdir");
            if (null == pdir || pdir.Equals(""))
                throw new ArgumentException("pdir");

            _context = context;
            _virtualDir = vdir;
            _physicalDir = pdir;
        }

        // required overrides (abstract)
        public override void EndOfRequest()
        {
            _context.Response.OutputStream.Close();
            _context.Response.Close();
            //_context.Close();
        }
        public override void FlushResponse(bool finalFlush)
        {
            _context.Response.OutputStream.Flush();
        }
        public override string GetHttpVerbName()
        {
            return _context.Request.HttpMethod;
        }
        public override string GetHttpVersion()
        {
            return string.Format("HTTP/{0}.{1}",
                _context.Request.ProtocolVersion.Major,
                _context.Request.ProtocolVersion.Minor);
        }
        public override string GetLocalAddress()
        {
            return _context.Request.LocalEndPoint.Address.ToString();
        }
        public override int GetLocalPort()
        {
            return _context.Request.LocalEndPoint.Port;
        }
        public override string GetQueryString()
        {
            string queryString = "";
            string rawUrl = _context.Request.RawUrl;
            int index = rawUrl.IndexOf('?');
            if (index != -1)
                queryString = rawUrl.Substring(index + 1);
            return queryString;
        }
        public override string GetRawUrl()
        {
            return _context.Request.RawUrl;
        }
        public override string GetRemoteAddress()
        {
            return _context.Request.RemoteEndPoint.Address.ToString();
        }
        public override int GetRemotePort()
        {
            return _context.Request.RemoteEndPoint.Port;
        }
        public override string GetUriPath()
        {
            return _context.Request.Url.LocalPath;
        }
        public override void SendKnownResponseHeader(int index, string value)
        {
            _context.Response.Headers[
                HttpWorkerRequest.GetKnownResponseHeaderName(index)] = value;
        }
        public override void SendResponseFromMemory(byte[] data, int length)
        {
            _context.Response.OutputStream.Write(data, 0, length);
        }
        public override void SendStatus(int statusCode, string statusDescription)
        {
            _context.Response.StatusCode = statusCode;
            _context.Response.StatusDescription = statusDescription;
        }
        public override void SendUnknownResponseHeader(string name, string value)
        {
            _context.Response.Headers[name] = value;
        }
        public override void SendResponseFromFile(
            IntPtr handle, long offset, long length)
        { }
        public override void SendResponseFromFile(
            string filename, long offset, long length)
        { }

        // additional overrides
        public override void CloseConnection()
        {
            //_context.Close();
        }
        public override string GetAppPath()
        {
            return _virtualDir;
        }
        public override string GetAppPathTranslated()
        {
            return _physicalDir;
        }
        public override int ReadEntityBody(byte[] buffer, int size)
        {
            return _context.Request.InputStream.Read(buffer, 0, size);
        }
        public override string GetUnknownRequestHeader(string name)
        {
            return _context.Request.Headers[name];
        }
        public override string[][] GetUnknownRequestHeaders()
        {
            string[][] unknownRequestHeaders;
            System.Collections.Specialized.NameValueCollection headers = _context.Request.Headers;
            int count = headers.Count;
            List<string[]> headerPairs = new List<string[]>(count);
            for (int i = 0; i < count; i++)
            {
                string headerName = headers.GetKey(i);
                if (GetKnownRequestHeaderIndex(headerName) == -1)
                {
                    string headerValue = headers.Get(i);
                    headerPairs.Add(new string[] { headerName, headerValue });
                }
            }
            unknownRequestHeaders = headerPairs.ToArray();
            return unknownRequestHeaders;
        }
        public override string GetKnownRequestHeader(int index)
        {
            switch (index)
            {
                case HeaderUserAgent:
                    return _context.Request.UserAgent;
                default:
                    return _context.Request.Headers[GetKnownRequestHeaderName(index)];
            }
        }
        public override string GetServerVariable(string name)
        {
            // TODO: vet this list
            switch (name)
            {
                case "HTTPS":
                    return _context.Request.IsSecureConnection ? "on" : "off";
                case "HTTP_USER_AGENT":
                    return _context.Request.Headers["UserAgent"];
                default:
                    return null;
            }
        }
        public override string GetFilePath()
        {
            // TODO: this is a hack
            string s = _context.Request.Url.LocalPath;
            if (s.IndexOf(".aspx") != -1)
                s = s.Substring(0, s.IndexOf(".aspx") + 5);
            else if (s.IndexOf(".asmx") != -1)
                s = s.Substring(0, s.IndexOf(".asmx") + 5);
            return s;
        }
        public override string GetFilePathTranslated()
        {
            string s = GetFilePath();
            s = s.Substring(_virtualDir.Length);
            s = s.Replace('/', '\\');
            return _physicalDir + s;
        }

        public override string GetPathInfo()
        {
            string s1 = GetFilePath();
            string s2 = _context.Request.Url.LocalPath;
            if (s1.Length == s2.Length)
                return "";
            else
                return s2.Substring(s1.Length);
        }
    }
[/sourcecode]

The Console application puts it all together.  It’s a big tricky due to the requirements of ApplicationHost.CreateApplicationHost, so there are a few post build folder and copy setup needed to allow the ASMX to run correctly.  Namely

  1. You must copy our library into a bin folder under where the Console executable will run
  2. You must copy the Calculator.asmx so it will be in the same folder as Console application executable
  3. You must copy the Calculator.asmx.cs file into a App_Code folder under where the Console executable will run

Here is the Program.cs of the Console application which fires up the HTTP listener to support the ASMX web service.

[sourcecode language='csharp' ]
    class Program
    {
        static bool run = true;
        static string port = ConfigurationManager.AppSettings["port"];

        /// <summary>
        /// Example 1: self hosted web serivce using System.Web.Hosting.ApplicationHost.  Supports full web ASMX web serivce
        /// </summary>
        static void Main(string[] args)
        {
            //  run our web server
            ThreadPool.QueueUserWorkItem(RunListener);

            // wait for user to tell us to stop
            Console.ReadLine();
            run = false;
        }

        static void RunListener(object state)
        {
            var currentDir = Directory.GetCurrentDirectory();

            HttpListenerWrapper listener = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(typeof(HttpListenerWrapper), "/", currentDir);

            listener.Configure(new[] { $"http://localhost:{port}/", $"http://127.0.0.1:{port}/" }, "/", currentDir);

            listener.Start();

            Console.WriteLine($"Listening for requests on http://localhost:{port}/");

            while (run)
                listener.ProcessRequest();

            listener.Stop();
        }
    }
[/sourcecode]

Building the Console application will yield the following output:

image

Running the application will yield the following:

CalculateWebServiceConsole

Opening a browser and navigating to http://localhost:8080/Calculator.asmx will respond with web services definition page

CalculateWebServicePage

image

CalculateWebServiceAddMethodResult


The WinForm application used the WSDL from the web service to generate a proxy and call the simple functions on the Calculator.  There is not error handling in the app to keep it simple.

CalculateWinFormApp

 

And there you have it.  Self hosting a old school ASMX web service.  If you want to host a WCF web service this is a bit easier as there is plumbing out of the box in the System.ServiceModel library for this purpose.  See Microsoft post here and ServiceHost class.

Download SelfHostedSoapService.zip

Docker - A New Way To Think Virtual But Not Be Virtual

At times you get the pleasure of working with some cutting edge technology that gives you the "wow that's pretty slick" feeling.  Other times it can be a rocky unstable mess.  Docker is one such technology that has not been the later.  The concept is simple, run this self contained little unit on bare metal as if it were a virtual machine.  The analogy many liken this too is a shipping yard with lots of containers.  The containers are the self contained packages and since all containers have the same shape the can be stacked and treated the same even though each container's internals can vary greatly.  Hence, one of the reasons Docker calls these units containers.

I've had success setting this up on Windows and a Mac, both of which use a tool called boot2docker.  Since Docker only runs on Linux systems, both Windows and Mac need to use Virtual Box to spin up a Linux machine that can host Docker.  For Windows check out https://docs.docker.com/installation/windows/ and for Mac see https://docs.docker.com/installation/mac/.  I had a little trouble at first on Windows, which required deleting the VM on disk then re-initializing docker.  After they are up and running, it's a breeze getting a container started, just type "docker run container name".  It's that simple.  Of course, if you want your container to expose ports and do other things there's a little more to it, but if you want to test out Linux based products, this is a very slick way to do it.  To see a list of docker supported containers go to https://registry.hub.docker.com/Pluralsight also has some good modules on how to use docker.

Atlasian SourceTree : A Great Git Visual Tool

Git is source control system that has risen to new heights.  Even Team Foundation Server no exposes Git.  Many use the Git command line operations but I always prefer the visual tools for day to day work.  Atlasian, produces of Jira, Confluence, Stash, Bamboo, have a tool call SourceTree which is a excellent tool for managing Git.  You can download it for Windows or Mac here http://www.sourcetreeapp.com/.

Install Mongo On Windows As a Service

Mongo is a common NoSql database that is flexible and easy to use.  It’s ability to scale and shard across many nodes makes it a great option for load balancing and scaling an application domain that fits a NoSql type schema.

1.  Download the latest version of Mongo that fits your platform (i.e. x86, x64).  Run the installer and place the application files in C:\Tools\MongoDB…  Follow my environment variable setup post for certain development folders.

2. Create an environment variable MONGO_HOME to point to the root of the mongo application directory.  If you followed my post on environment variable setup this would be %TOOLS_HOME%\MongoDB…  Add %MONGO_HOME%\bin to the Path environment variable.

3.  Create a directory to store the mongo data.  The simple approach is to create the directory C:\data\db.  This is Mongo’s default but can be changed using it’s configuration file.

4.  Create a log directory for the Mongo logs.  The simplest is to create “log” directory under the root Mongo directory C:\Tools\Mongo….

5.  Create a mongodb.conf file in C:\Tools\MongoDB… root directory.  This put the following minimum information in the file.

systemLog:
   destination: file
   path: "/Tools/MongoDB 2.6 Standard/log/mongodb.log"
net:
   bindIp: 127.0.0.1
   port: 27017
storage:
   journal:
      enabled: true
   dbPath: "/data/db"

 

6.  Open a command window (ensure it’s in Administrator mode) enter the following command.  This will work if your Path variable is set correctly.

mongodb.exe --config "C:\Tools\MongoDB 2.6 Standard\mongodb.conf" --install

Setup Java Development on Windows : Git, Tomcat, Maven, Java JDK

This is a Java development setup that is a continuation of a long ago post regarding Eclipse setup. In this post I exclude the IDE and include Git and Tomcat, two common elements in a Java developers toolbox now.

Create the following environment variables (similar to updating you .bashrc file).

  • HOME = {drive}:\Source
  • SDKS_HOME = {drive}:\SDKs
  • TOOLS_HOME = {drive}:\Tools
  • Download and extract or install msi/exe.

    1. Downloaded Java JDK, the latest or the version of you choice. Make sure you get the correct one for you architecture (i.e. x86, x64,..).  When running the installer, place the JDK in %TOOLS_HOME%.  You will end up with something like C:\Tools\jdk_…
    2. Download Maven latest maven version and extract to %TOOLS_HOME%.  You will end up with something like C:\Tools\maven-3.2.5…
    3. Download Ant latest ant version and extract to %TOOLS_HOME%.  You will end up with something like C:\Tools\ant…
    4. Download Git installer for windows. Install complete with git bash.
    5. Download Apache Tomcat version that you’d want and extract to %TOOLS_HOME%.  You will end up with something like C:\Tools\apache-tomcat-7.0.59-windows-x64…

    Create the following environments variables

    The root directory for these applications will be the directory where you will find the bin folder and other application specific folders.

  • JAVA_HOME = %SDKS_HOME%\jdk_… to the root folder.
  • MAVEN_HOME = %TOOLS_HOME%\maven-… to the root folder.
  • ANT_HOME = %TOOLS_HOME%\ant-… to the root folder.
  • %CATALINA_HOME% = %TOOLS_HOME%\apache-tomcat-… to the root folder.
  • Append the following line to the system Path environment variable

    Don’t forget a semicolon after each new entry.

    • %JAVA_HOME%\bin
    • %MAVEN_HOME%\bin
    • %ANT_HOME%\bin
    • %CATALINA_HOME%\bin

    At this point you will be able to open the git bash window and run the following.

    • java -version
    • git --version
    • mvn –version
    • ant -version
    • For tomcat you will have to manually path over to tomcat bin and run “sh version”.  bash shell doesn’t convert c:\Tools\… correctly for this one.

    Getting Revision Number in TFS Team Build

    If you’ve ever been wondering how to get the value of the $(Rev:r) (or $(Rev:rr)) value in you team build, you can’t.  If you have a pretty boilerplate versioning where you do Major.Minor.Release.Revision then using the $(Rev:r) is pretty handy.  A company I work for now uses Major.Minor.Patch.Revision.  Below is how I was able to extract the revision number during TFS build workflow time.

    1.  Our BuildNumberFormat is set close to the default: $(BuildDefinitionName)$(Rev:.r).  We can use this fact to extract the revision number.

    2.  Create a string variable that is scoped to Run On Agent called RevisionNumber.  Don’t use Version or something like that which has a class name in the TFS namespaces (i.e. Version is type being used as int).

    image

    3.  Near the top of the “Run On Agent” area of you build template, add a Assign task item from the toolbox.  I added mine to the sequence called Initialize Variables because it logically made sense here.

    • Set To to be RevisionNumber
    • Set Value to be the following expression
    Int32.Parse(BuildDetail.BuildNumber.Remove(0, BuildDetail.BuildNumber.IndexOf(".") + 1))

     

    With this in place you can use the revision number to create any numbering based of this value.

    Quick Way To Create a MSI For You Web Projects Using Wix

    I’ve know about Wix (Windows Install Xml) tool set for quite some time but haven’t had much to do with it.  Wix is a great tool for working within the Windows environment.  It is a XML based way of defining how you want you MSI packaged.  It comes with Visual Studio template projects, and few very useful tools.

    Background of my problem to solve: My company has been using Web Site projects and Visual Studio Deployment/Setup projects for a very long time.  I know, all these project types are the bane of Visual Studio’s ease of use when it comes to projects.  Our requirement is to create MSI installers of our web services.

    I’ll be assuming you are using a web application project type, web site projects are deprecated after Visual Studio 2010. Below are some simple steps you can take to create a MSI out of your web application projects.

    NOTE: One thing about Wix that helps a lot, is consistent naming convention for items that are not auto-generated, for example, IIS virtual directory component IDs ending in “.VDir” or folder IDs ending in “Folder”.

    1.  Install the latest Wix Toolset, http://wixtoolset.org/.  To save yourself time, add the the Wix bin (something like C:\Program Files (x86)\WiX Toolset v3.8\bin) folder to your PATH environment variable so the tools can be accessed on the command line.

    2.  Go to you web application.  Right click and select Publish.  You will be just publishing to a local folder so if you have other publishing profiles create a new one, call it LocalFolder or something like that.  The publishing properties should look like the following.

    image

    3.  Create a Wix project in the same solution of the web application project.

    4.  Add the web application project as a reference in the Wix project as shown below.  Yes, Wix has build dependencies, it’s pretty cool!

    image

    4.  Now we will create a component wix file, a file defining all of our project outputs we want in our MSI (i.e. dlls, asmx, etc.).  Below is the following line I’ve used to quickly generate a wix file, which usually doesn’t need much tweaking after it’s done.

    heat dir "C:\Temp\HtngWebServices" -out "{PathToWhereYouWantYourWixFix}\Components.wxs" -gg -g1 -sreg -sfrag -var var.{ProjectName}.ProjectDir -dr WebServicesFolder -cg HtngWebServicesComponents

    dir = directory which you will pull files from to generate wxs file

    out = the location you want to create the wxs file in, generally this will be your Wix project or a Wix setup library project.

    var = variable to place in front of the file location of the file being referenced in wix, this will be apparent when I describe the how the Wix project references work below.

    dr = Directory reference to root directories, see Wix documentation.

    gg, g1, sreg, sfrag = see Wix documentation.

    5.  Once the Components.wxs is generated (Compnonents.wxs is just a name I choose for simplicity of example), add it to the Wix project. 

    Opening the Components.wxs that was generated by “heat”, you’ll notice a line like “Source="$(var.HtngWebServices.ProjectDir)\Web.config".  The part I’ve italicized is a variable, see Using Project References and Variables, is a project ref so when our dependent project builds all the files we need will be located by Wix, this is handy but may not fit everyone’s situation.

    image

    6.  In the Wix project, add the following Wix library references, which are found in C:\Program Files (x86)\WiX Toolset v3.8\bin\.

    image 

    At the top of your Product.wxs file you will need to add the following XML namespaces.

         xmlns:iis="http://schemas.microsoft.com/wix/IIsExtension"      xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"

    7.  Add a wix file (.wxs) to your Wix project called IISConfiguration.wxs.  This is where the IIS settings will go.

    8.  In the IISConfiguration file you will need to add DirectoryRef for virtual directories that you need.  See the IIS documentation for detail, below is what It looks like

    image

    9.  You will need to add feature(s) to the Product.wxs file that was generated with the project.  Here we’ve used 2 features, see Feature documentation.  Each of the ComponentRef under the IIS virtual directories section shown below will be linked to the next step, and the item circled in read represents the ComponentRef of our web application project components and virtual director.

    image

    10.  A few more fragments will need to be added to you Product.wxs file to complete the installation information that the MSI will need.  Below is a shot of these sections.

    First Fragment – this is for IIS extension to know what web site your are targeting, see IIS extensions.

    Second Fragment – the first directory structure is the “TARGETDIR” directory which are constants from MSI framework, see MSDN, the rest is nesting for our installation location.  The other DirectoryRef towards the bottom is for permissions for IIS process to access the installed folders.

    image

     

    To be honest the learning curve is a little steep for Wix at first but once you wrestle it down, you begin to be able to follow what is going on.  The best guide is their documentation http://wixtoolset.org/documentation/ and Google other examples of specific tasks you are trying to achieve.  This thread is a accumulation of such time spent Googling various specifics of “how-to”’.

    Errors In TFS Build Definition With Different Version of Visual Studio Installed

    As Visual Studio 2012 and 2013 came out, I installed them to try them out and get to know the enhancements and changes.  At work, we use Visual 2010 and TFS 2010.  Using the team build workflow is OK, it has it merits with visual layout and .NET code access when using activities like if statements.  The one downside that I ran across after install VS2013 was nearly the whole workflow build definition had errors now!

    It turns out that there are assembly reference issues between having VS2010 and VS2013 side by side.  Being a little dismayed, and not to mention ugly to look at, I ventured into what to do to fix it.

    1.  First, you have to manage your build definition in a project just like you would code.  Below is an example.  The project can be a simple class library with not code files, just build definitions.  I do this whenever I setup TFS.

    image

    2.  You need to add a reference to all the libraries being reference in the xaml code.  If you open your xaml by selecting View Code you can see all the references.  To add reference right click project references and navigate to the location of the correct TFS libraries, most of them are in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\, I just search for dll under C:\Program Files (x86)\Microsoft Visual Studio 10.0.

    image

    image

    What is a .winmd and how to use it in a desktop application

    A .winmd is a file used by Windows 8 WinRT (Windows Run Time).  winmd stands for Windows Meta Data file which is the same format used by the .NET framework for the CLI (common language interface).  As such it can be viewed by .NET tools such as Reflector and the ildasm tool packaged with .NET.  You can find these files in various places but one command place is c:\Windows\System32\WinMetadata.

    These files are focused on Windows store apps but it doesn’t preclude you from using them in a traditional desktop app.  To do so you need to do the following to your desktop application in order to leverage functionality in these APIs.

    1.  Unload your application.  Edit the project file and add the tag near target version, “<TargetPlatformVersion>8.0</TargetPlatformVersion>”.

    2.  Reload your project.  You will need to add a reference to the following DLLs.

    C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\WindowsBase.dll

    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Runtime.dll

    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Runtime.WindowsRuntime.dll

    3.  Now you will be able to leverage functionality provided by the WinRT framework, such as camera, NFC, etc.

    Setting Up TFS Team Build To Use TFS Build Extensions

    The other day I was reminded of how great TFS Build Extensions really are.  I’ve used them in the past and currently use them and still have not tapped there fullest resources but find they are always there to do 99% of what I need done.  If you are using TFS and team build, these are a must.  In this post I’m going to do a quick run through on setting up build extension on your build machine as well as your local development environment.  A more detail version of what I summarize below is found in the TFS Build Extensions Documentation.

    1.  Download the TFS Build Extensions from http://tfsbuildextensions.codeplex.com/.  Unzip content into C:\Tools\.

    2.  Follow the directions in TFS Build Extensions Documentation to check in these build extension into the {team project}\BuildProcessTemplates\Custom Assemblies.  This will be used by the build controller/build agent as well as you when you are working on the build workflow and need toolbox items.

    Below is an example of a team project with the Custom Assemblies folder under BuildProcessTemplates and a ProcessTemplates.sln which has 1 project to house our build definitions.

    image

    3.  After following the setup steps TFS Build Extensions Documentation you will be able to create a workspace to your build templates folder, get latest, and open the build template project the documentation had you create.  The key to being able to work on the template on your development machine is to include the TFS extension in your toolbox.  Following the documentation will have you setup for this so your development will look like the following.  In the toolbox I added the items from the library TfsBuildExtensions.Activities.dll, which should be in your {team project}\BuildProcessTemplates\Custom Assemblies\ folder.

    image

    Using WPF and Vector Graphics

    Recently I’ve been taking a look at WPF, Microsoft’s not so new now replacement for WinForms.  With the little free time that I have, I’ve relied heavily on Pluralsight for getting up to speed on various technologies.  In working with WPF, I was trying to leverage their concept of “lookless” controls which is very powerful and much nicer to design with than WinForms. 

    To summarize my tribulations, I was having a hard time loading a local resource that was a SVG.  Blend Expression, a WPF designer, doesn’t support SVG directly but it does support .pdf (a form of SVG) and .ai (Adobe Illustration).  There are a couple of ways to product .pdf or .ai files.  My approach was to use a tool I’ve used in the past, Inkscape, see Inkscape A Cool Tool.  Inkscape also support generating a XAML file directly from the SVG file which you can leverage directory or copy the contents of XAML output into a resource dictionary.

    1.  Open or create your SVG file in Inkscape.

    2.  PDF format: Select Save As and choose .pdf format.  It will display a dialog as below once you click Save, ensure you select “Convert texts to paths”, then click OK.  Once the file is saved you can rename the file extension from .pdf to .ai.  It will now be recognized in Expression Blend.

    image

     

    3.  XAML format:  Select Save As and choose .xaml format.  This will export it directly to a XAML file.  You can take the content line, element is a ViewBox, and put that directory in a resource file.

    Outlook 2013 Always Prompts for Credentials using Active Directory

    You ever have those technical issues that aren’t quit annoying enough to deal with in your normal day of busyness?  I really have enjoyed where Microsoft have taken Office in the last few years, but after installing Office 2013 Professional, which has Outlook 2013, I kept receiving a login prompt for my Active Directory credentials every time I open Outlook.  For a while, I thought it was something to do with our IT’s exchange server, but did a little googling to figure it out. 

    It turns out that if you have Exchange connected through HTTP, it will always prompt, even if you ask it to remember you credentials, or even tell it not to prompt!  How annoying.  Below is the image of the setting you need to uncheck to fix this pest of an issue.

    image

    You can get to this screen by going to: Account Settings, double click the mail account in question, click the More Settings… button, then click the Connection tab.

    Sass CSS with Compass using Grunt Not Working on Windows

    My team is using AngularJS, Node.js, Grunt, Sass CSS via Compass, Yoeman, and a few other web toolsets.  The other day when running the serve process to generate the css output from Sass CSS, the css wasn’t able to generate.  It turned out that Compass was setting the permissions on the .tmp folder where it puts the CSS to a state that didn’t all the process to write the file, hence a Permission Denied error.  To fix this issue I followed the StackOverflow thread http://stackoverflow.com/questions/22596760/yeoman-error-errnoeacces-on-line-897-of-c-permission-denied which did these steps.

    Open a command prompt and run the following.

    1. gem uninstall sass (if you have multiple version, select all)
    2. gem uninstall compass
    3. gem install compass --pre
    4. gem install sass --pre

    Setting Up PhoneGap/Cordova for Visual Studio

    It’s always a struggle to find time to invest in side projects when you work and play an active role in your kids lives.  I appreciate when installing tools is just simple and you don’t have to google “why doesn’t …. do …” or “where is…” because the instructions aren’t straight forward or are missing steps/pieces.  I found this the case with the latest phonegap instructions as of 2014-3-9.

    1. Install Windows SDK.  I’m using Windows 7.1 because I have a Win7 machine, I found SDK here.  This installed Visual Studio 2010 Express for Windows Phone (VS2010).
    2. Download PhoneGap SDK and unzip in C:\Tools.  PhoneGap SDK is on github here.
    3. In the C:\Tools\phonegap-master (you might have to drill down a bit) there will be a lib folder, and in it there are folders for the different target frameworks one of which is “windows-phone”.  As of recent the Visual Studio template .zip is not there.  I had to run a batch filed called “createTemplates.bat” which created templates for WP8 and WP7.
    4. Once you have the Visual Studio .zip file template(s), copy those to your \Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#.
    5. Open VS2010 and create a new project.  You will now see a project template as shown below.  The template name may change at some point.

    image

     

    The project structure will look like the following.

    • cordova – build tools
    • cordovalib – code for browser engine interaction
    • www – folder for html/js/css of your app
    • plugins – plugins for interfaces on your phone (i.e. camera, contacts)

    image

    Installing Node.js and Other Packages

    Keeping up with technology can be a job in itself.  Learning is fun, but is quickly forgotten so writing things down can always save you time later.  This thread goes over various was of installing Node.js and other packages.

    Installing Node.js

    There are 2 ways in which you can install Node.js.  Node.js comes with node package manager now so it will not need to be installed independently.

    Installer (recommended): Go to node.js.org and use the installer for your OS.  Run the installer.

    Homebrew (Mac only): Run the command “brew install node”.  You will have to have homebrew installed.

     

    Other Node packages t

    Installation will use node package manager.  You can list the node modules for your node application by listing the directory of “node_modules”.

    Express – web application framework for node

    npm install -g express --save

    NOTE: once you create a application with express (i.e. express AppName) you will have to navigate to AppName folder and run the command “npm install” to install the components defined in node’s package.json.

    Yeoman – front end tool focused on scaffolding (yo), building/testing (grunt), and dependency management (bower)

    npm install -g yo --save

    npm install -g generator-webapp --save

    coffee-script – scripting language that builds down to javascript.

    npm install coffe-script --save

    node-dev – a tool for node that will monitory files and auto restart the node app when a file has changed.

    npm install node-dev –save

    NOTE: When using this you will want to separate development dependencies from production ones.  In the package.json, you can create a “devDependencies” like so:

    {
    "name": "application-name",
    ...,
    "dependencies": {
    "express": "2.5.8",...
    },
    "devDependencies": {
    "node-dev": "~0.2.2"
    }
    }

    mocha – javascript test framework for node

    npm install mocha –save

    NOTE: put this in your dev dependencies

    REQUIRES: request

    request – modeule that simplifies the process of making http calls

    npm install requets --save

    Redis – open source advanced key-value store

    npm install redis hiredis connect-redis --save

    REQUIRES: Installation of Redis backend.  On a Mac use homebew “brew install redis”, Windows see redis.io.

    connect-assets – transparent file compilation and dependency management for Node’s connect framework

    npm install connect-assets --save

    socket-io – simplifies the use of IO on all browsers.  See WebSockets for information on this topic.

    npm install socket-io --save

    AngularJS – front end web application framework dealing with models, views, collections, and events

    npm install angular --save

    Backbone – front end structured for web applications dealing with models, views, collections, and events

    npm install backbone --save

    RELATED: Marionettejs (npm install backbone.marionette --save)

    ASP.NET Debugging in Visual Studio 2013 IIS Express Not Continuing

    Looking at VS2013, I’m impressed with it’s speed over VS2012 not to mention that Microsoft appears to be releasing more often and taking into consideration a lot of community feedback.   Other than the quickly visible improvements, I noticed that the virtual web server would stop working when debugging was stopped in Visual Studio. To fix this open you ASP.NET project properties and uncheck “Enable Edit and Continue”.  Once this is unchecked IIS Express will run after debugging has stopped.

    image

    Mocking ASP.NET MVC HttpConext and Sessions

    Unit testing ASP.NET MVC controllers can be difficult when you start to use the HttpContext and Session state.  The following snippet of code will allow you to mock, using the Moq framework, the HttpContext properties.  Add this to your test project.

    using System.Collections.Generic;
    using System.Web;
    using Moq;
    using System.Collections.Specialized;
    using System.Web.Routing;
    using System.Web.Mvc;

    namespace WebBackOffice.Tests
    {
    public class ContextMocks
    {
    public Mock<HttpContextBase> HttpContext { get; private set; }
    public Mock<HttpRequestBase> Request { get; private set; }
    public Mock<HttpResponseBase> Response { get; private set; }
    public RouteData RouteData { get; private set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="ContextMocks"/> class.
    /// </summary>
    /// <param name="controller">The controller to add mock context to.</param>
    public ContextMocks(Controller controller)
    {
    // define all the common context objects, plus relationsips between them
    HttpContext = new Mock<HttpContextBase>();
    Request = new Mock<HttpRequestBase>();
    Response = new Mock<HttpResponseBase>();
    RouteData = new RouteData();

    HttpContext.Setup(m => m.Request).Returns(Request.Object);
    HttpContext.Setup(m => m.Response).Returns(Response.Object);
    HttpContext.Setup(m => m.Session).Returns(new FakeSessionState());

    Request.Setup(m => m.Cookies).Returns(new HttpCookieCollection());
    Request.Setup(m => m.QueryString).Returns(new NameValueCollection());
    Request.Setup(m => m.Form).Returns(new NameValueCollection());

    Response.Setup(m => m.Cookies).Returns(new HttpCookieCollection());

    // apply the mock context to the supplied controller instance
    RequestContext rc = new RequestContext(HttpContext.Object, new RouteData());
    controller.ControllerContext = new ControllerContext(rc, controller);
    }

    /// <summary>
    /// Sets the ajax request header so that mocked HttpRequest shows as a ajax call.
    /// </summary>
    public void SetAjaxRequestHeader()
    {
    Request.Setup(f => f["X-Requested-With"])
    .Returns("XMLHttpRequest");
    }

    private class FakeSessionState : HttpSessionStateBase
    {
    Dictionary<string, object> _items = new Dictionary<string, object>();

    public override object this[string name]
    {
    get
    {
    return _items.ContainsKey(name) ? _items[name] : null;
    }
    set
    {
    _items[name] = value;
    }
    }
    }
    }
    }

    Below is an example of using this in a unit test, based on nunit test framework.  During the setup, create the ContextMock and associated with the controller under test.

    namespace MySite.Tests
    {
    public class AccountControllerTests
    {
    private MyAccountController myAccountController;
    private ContextMocks contextMock;
    private Mock<IAccountService> accountServiceMock;

    [SetUp]
    public void Setup()
    {
    // create new controller under test
    myAccountController = new MyAccountController();

    // create mock HttpContext
    contextMock = new ContextMocks(myAccountController);

    accountServiceMock = new Mock<IAccountService>();
    myAccountController.AccountService = accountServiceMock.Object;
    }

    [TearDown]
    public void Cleanup()
    {
    myAccountController = null;
    contextMock = null;
    accountServiceMock = null;
    }

    [Test]
    public void SignUp_AjaxRequest_Returns_JsonResult()
    {
    // arrange
    string email = "test@test.com";
    string password = "Some#rei!23";

    // configure ajax mock request
    contextMock.SetAjaxRequestHeader();

    accountServiceMock.Setup(f => f.CreateAccount(It.IsAny<string>(), It.IsAny<string>()))
    .Returns(new SignUpResponse(SignUpResponse.ReturnCodeType.Success));

    // act
    ActionResult actual = myAccountController.SignUp(email, password);

    // assert
    Assert.IsInstanceOf<JsonResult>(actual);
    }
    }
    }

    Fixing 'mscorlib.dll' targets a different processor When Building x86

    Currently I’m working on a product that has been around for a long time, and will be for a lot longer.  Even thought 64bit has been out for a long time, this application has it roots in 32bit.  This is not necessarily a bad thing, as 64bit will not provide any real processing performance enhancements.  Prior to Visual Studio 2010, building with AnyCPU platform configuration was straight forward.  Now that we support purely 64bit OS on our server side, things because a little more difficult.  Long story short, we needed to configure everything to specify x86.  In doing so, we continued to get build errors on our TFS team build server.  The error “error CS1607: Assembly generation -- Referenced assembly 'mscorlib.dll' targets a different processor” would show up all over the place.  After ensuring that all our projects were set to x86 and the Configuration Manager for debug/release specified x86, we eventually found that the build process MSBuild Platform needed to be set to X86.

    As an interesting note, in our researching over x86 and x64, we came across this article AnyCPU Exes are usually more trouble than they're worth.  If you’ve been adding new projects in Visual Studio 2010, you’ll notice that they all default to x86. 

    Office Communicator Is Cool Check This Out

    So being a somewhat Microsoft shop, we use Office Communicator which is a pretty dandy little piece of software for inter company screen sharing and instant messaging.  The other day a colleague had a theory that we could create an infinite loop with Office Communicator by doing  a three way share.  Well it worked and was quite humorous, here is our result.

    image

    Alter Visual Studio Template Files

    Out of the box, I’ve found Visual Studio template files to be just fine.  Recently I was doing some researching into using StyleCop so I installed in on my machine.  Little did I know, it went behind the scenes and altered some if now all template files.  In particular, I don’t care for their Interface and Class file templates, I tend to use ReSharper and GhostDoc to do cleanup and documentation.  If you want to change or revert your templates, your in luck, Visual Studio has backups.  Follow the steps below to restore whatever templates you need to.  In the example I will be restoring the C# class file for Visual Studio 2010 (10.0).

    1.  Go to the template folder you desire.  You will find the templates in the Program Files folder (Program Files (x86) on 64 bit system) and the particular version  here C:\Program Files\Microsoft Visual Studio {Version of VS, 10.0, 9.0…}\Common7\IDE\ItemTemplates.  In the case of the C# class you will have to drill down into \CSharp\Code\1033\ folder, and in there you will find a file called Class.zip.bak.  Delete the existing Class.zip file, copy the Class.zip.bak and rename it to Class.zip.  Do this process for any other templates you wish to revert.

    2.  Reset the IDE environment.  Open a Visual Studio command prompt (I do it in administrator mode on Windows 7).  It’s found in All Programs^Microsoft Visual Studio {Version 2010, 2008,…}^Visual Studio Tools.  Once the command windows is open run “devenv /setup” and you’re all set!