Wednesday, January 14, 2015

Online GUID converter

Sometimes I need to convert GUIDs without dashes to GUIDs with dashes or vice versa, so I've created this small page to help me with the conversion.

or

Tuesday, September 17, 2013

How to build a specific projects from a solution with MSBuild

Sometimes you want to build only a single project, or a list of projects from a solution without building the whole solution with MSBuild.

To do so, you can use custom build targets. You need to add a custom build target for every project you want to build containing the relative path in solution structure of the project (.csproj/.vproj).
Another thing you need to have in mind is that the dots(.) in the project name should be replaced with underscores(_). You can clean or rebuild adding :Clean, :Rebuild at the end of the target.

However if you can check all the MSBuild targets used from the solution. As you may know, when running MSBuild command against a solution file in-memory it is converted to an actual MSBuild project named [SolutionName].sln.metaproj. You can add an environment variable named msbuildemitsolution and set its value to 1 and run MSBuild from command line. Another option is to add /p:msbuildemitsolution=1 to the passed parameters to the build. This will generate the .metaproj file where you can find all the needed targets.

Lets illustrate all the above with a simple example.
Here is a simple project structure:

 
 
 
If we want to build Project.Four and rebuild ProjectTwo we need to call MSBuild with the following arguments:
 
msbuild BuildSpecificProjectsFromASolution.sln /t:"Folder2\Project_Four";"ProjectTwo:Rebuild"

 
You can find the sample solution here.

Tuesday, December 18, 2012

Using WIX with managed custom action

WIX is a great toolset for creating installers. In most of the cases when you need an installer you need some custom logic to be executed. It's great that WIX supports managed custom actions. Anyway it wasn't so easy for me to make it work, so I want to share my experience.
I will demonstrate it using the WIX Visual Studio add-in (version v3.7.1217.0).

We will create WIX Setup project and C# Custom Action Project.
We will add a dummy text file in the setup project to be used as installation content and will change a little bit the auto created Product.wxs file.
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="*" Name="WixWithCustomAction" Language="1033" Version="1.0.0.0" Manufacturer="Trifonov" UpgradeCode="60468a7d-6485-4e7e-bf82-503213bc43a8">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

    <Media Id='1' Cabinet='Dummy.cab' EmbedCab='yes' />

    <Directory Id='TARGETDIR' Name='SourceDir'>
      <Directory Id='ProgramFilesFolder'>
        <Directory Id='WixWithCustomAction' Name='WixWithCustomAction'>
          <Component Id="DummyContent" Guid="ba9028ae-0d3b-4b66-8560-f53330736265">
            <!-- Add the dummy file as content. -->
            <File Id="DummyFile" KeyPath="yes" Source="Dummy.txt" Vital="yes" />
          </Component>
        </Directory>
      </Directory>
    </Directory>

    <Feature Id="Complete" Title="WixWithCustomAction" Level="1">
      <ComponentRef Id='DummyContent' />
    </Feature>
  </Product>
</Wix>
That's how our solution looks like:

If we build the WixWithCustomAction project, WixWithCustomAction.msi will be created. If we run it WixWithCustomAction folder will be created in program files with Dummy.txt file inside.
But now we want to add a custom action which will create a file in C:\Temp folder. We will use the MyCustomActionProject for this. Let's change the CustomAction class a little bit:
using Microsoft.Deployment.WindowsInstaller;
using System.IO;

namespace MyCustomActionProject
{
    public class CustomActions
    {
        [CustomAction]
        public static ActionResult MyCustomAcion(Session session)
        {
            session.Log("Executing MyCustomAcion");

            File.CreateText(@"c:\temp\installed.txt");

            return ActionResult.Success;
        }
    }
}

Now we just need to call this custom action from the installer. To do this we will add a reference to this project in the setup project.
Now let's add the custom action in the Product.wxs file.
Adding the project as a reference allows as to use these variables.
But adding custom action is a little bit complicated. After building the MyCustomActionProject.dll file we will need a call to MakeSfxCA.exe and sfxca.dll in your installed WiX toolset as the dll need a reference to Microsoft.Deployment.WindowsInstaller.dll and has CustomAction.config attached. Calling the MakeSfxCA.exe tool will package the project output to MyCustomActionProject.CA.dll(here you can find some additional information about this).
As we use "C# Custom Action Project" there is an import added to $(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.CA.targets file which will create this package on build. To check this you can build the custom action project and see the output:
So the custom action in the Product.wxs needs to reference the .CA.dll file. Thats why we cannot use
$(var.MyCustomActionProject.TargetPath) as a source for the custom action binary, but we will have to construct the source path like this:
$(var.MyCustomActionProject.TargetDir)$(var.MyCustomActionProject.TargetName).CA.dll
The other option is not to use the project reference but add the full path to the custom action output.
So we will add the following rows to the wxs file
<!--The source file should be the MyCustomActionProject.CA.dll file, that's why it's constructed this way-->
<Binary Id='CustomActionBinary' SourceFile='$(var.MyCustomActionProject.TargetDir)$(var.MyCustomActionProject.TargetName).CA.dll' />

<!--The DllEntry must be the name of the method to be called from the custom action project, in our case - MyCustomActionMethod 
http://wix.tramontana.co.hu/tutorial/events-and-actions/at-a-later-stage 
The Execute attribute will specify the deferred status of our custom action.
And finally, HideTarget will allow us to disable logging the parameteres passed to this custom action if security considerations so dictate.-->
<CustomAction Id='CustomActionId' BinaryKey='CustomActionBinary' DllEntry='MyCustomActionMethod' Execute="deferred" HideTarget="yes"/>

<InstallExecuteSequence>
  <!--We want to call the custom action before the install finalizes-->
  <Custom Action='CustomActionId' Before='InstallFinalize'/>
</InstallExecuteSequence>
And that's it. Now if we build the setup project and run the created msi installer, c:\temp\installed.txt will be created as a part of the installation process.

You can find the solution file here - WixWithCustomAction.zip

Friday, November 30, 2012

Sending stream to ServiceStack

Recently I needed to make a ServiceStack service which can receive big files, so I wanted to use streaming to accomplish this. Unfortunately there isn't much information about using streams with ServiceStack, so I decided to share my experience.

We'll create a sample solution containing both Server and Client. We will create a class library containing the service itself and an Utility project. So here is the structure of our solution:
So let's continue with the implementation of the service.
First of all we'll need to install the ServiceStack nuget package in the ServiceStackStreaming.Service project:
PM> Install-Package ServiceStack
This will add the dlls needed for ServiceStack. Now let's create the DTO:
using ServiceStack.ServiceHost;

namespace ServiceStackStreaming.Service
{
    [Route("/upload/{FileName}", "POST")]
    public class UploadPackage : IRequiresRequestStream
    {
        public System.IO.Stream RequestStream { get; set; }

        public string FileName { get; set; }
    }
}
To enable Streaming support we need to implement IRequiresRequestStream which needs a RequestStream property of type System.IO.Stream. We'll add a FileName property and include it in the Route so that we would be able to pass the uploaded file name.
The next thing to do is to create the service itself:
using ServiceStack.Common.Web;
using ServiceStackStreaming.Utility;
using System;
using System.IO;

namespace ServiceStackStreaming.Service
{
    public class UploadService : ServiceStack.ServiceInterface.Service
    {
        public object Post(UploadPackage request)
        {
            // hack - get the properties from the request
            if (string.IsNullOrEmpty(request.FileName))
            {
                var segments = base.Request.PathInfo.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                request.FileName = segments[1];
            }

            string resultFile = Path.Combine(@"C:\Temp", request.FileName);
            if (File.Exists(resultFile))
            {
                File.Delete(resultFile);
            }
            using (FileStream file = File.Create(resultFile))
            {
                request.RequestStream.Copy(file);
            }
            
            return new HttpResult(System.Net.HttpStatusCode.OK);
        }
    }
}

Our dummy service will save the incoming file in the "C:\Temp" directory. With the code from line 12 to line 17 we are getting the FileName property if it's not set. It seems that when using streaming the additional properties are not processed and they are always null, so we'll do this little hack to get the properties parsing the request url.
The other trick we use here is the extension method of the System.IO.Stream class wich we have implemented in the ServiceStackStreaming.Utility project:
using System.IO;

namespace ServiceStackStreaming.Utility
{
    public static class StreamExtender
    {
        public static void Copy(this Stream instance, Stream target)
        {
            int bytesRead = 0;
            int bufSize = copyBuf.Length;

            while ((bytesRead = instance.Read(copyBuf, 0, bufSize)) > 0)
            {
                target.Write(copyBuf, 0, bytesRead);
            }
        }
        private static readonly byte[] copyBuf = new byte[0x1000];
    }
}
this simply copes the instance stream to the target stream. Another option is to use ServiceStack StreamExtensions WriteTo method instead of creating this utility method.
The last thing we need to do to create a functional service is to add the AppHost class, we will inherit  AppHostHttpListenerBase as we want to host the service in a window console application.
using ServiceStack.WebHost.Endpoints;

namespace ServiceStackStreaming.Service
{
    public class AppHost : AppHostHttpListenerBase
    {
        public AppHost() : base("Agent", typeof(UploadService).Assembly) { }

        public override void Configure(Funq.Container container)
        {
            // we can add the routing here instead of adding it as attribute to the DTO
            //Routes
            //    .Add("/upload/{FileName}", "POST");
        }
    }
}
We can configure the route here, but I prefer doing this with attribute.
Now let's host the service. To do this we'll need to add the same ServiceStack nuget to the SertviceStackStreaming.Server project and add the following code to the Program.cs file:
using ServiceStackStreaming.Service;
using System;

namespace ServiceStackStreaming.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var appHost = new AppHost();
            appHost.Init();
            appHost.Start("http://*:1999/");

            Console.WriteLine("Service listening on port 1999!");
            Console.ReadKey();
        }
    }
}

This will be enough to host the service listening to port 1999.
Now let's call the service from the ServiceStackStreaming.Client (again we'll have to instal the sam e nuget package here).
using ServiceStackStreaming.Utility;
using System.IO;
using System.Net;

namespace ServiceStackStreaming.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"c:\temp\upload.zip";
            
            HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://localhost:1999/upload/upload-copy.zip");
            client.Method = WebRequestMethods.Http.Post;
            
            // the following 4 rows enable streaming 
            client.AllowWriteStreamBuffering = false;
            client.SendChunked = true;
            client.ContentType = "multipart/form-data;";
            client.Timeout = int.MaxValue;

            using (FileStream fileStream = File.OpenRead(filePath))
            {
                fileStream.Copy(client.GetRequestStream());
            }

            var response = new StreamReader(client.GetResponse().GetResponseStream()).ReadToEnd();
        }
    }
}
And that's it. We create WebRequest, set the needed properties to enable streaming on the client and copy the file stream to the request stream. This will call the service and will upload the "C:\Temp\upload.zip" file as upload-copy.zip file.

You can find the sample code here: ServiceStackStreaming.zip

Thursday, November 15, 2012

Testing private methods with Visual Studio

When writing unit tests in most of the cases we have to test private methods. Let's see how this can be achieved using Visual Studio. I will give you three options:

  1. You can test private methods using Reflection, but this is not always a good option, as when you change the name or input arguments of a Method, you won't get any error when building, but you will get exceptions run time.
    We will use the project from my previous post Getting console output within a unit test.
    We will add a private method to the DummyClass:
    using System;
    
    namespace ConsoleLogger
    {
        public class DummyClass
        {
            public void WriteToConsole(string text)
            {
                Console.Write(text);
            }
    
            private void PrivateWriteToConsole(string text)
            {
                Console.Write("Private: " + text);
            }
        }
    }
    
    Now we can add a unit test to test the method using reflection:
    [TestMethod]
    public void PrivateWriteToConsoleReflection()
    {
        var currentConsoleOut = Console.Out;
    
        DummyClass target = new DummyClass();
        Type type = typeof(DummyClass);
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            var method = type.GetMethod("PrivateWriteToConsole", 
                BindingFlags.NonPublic | BindingFlags.Instance);
            method.Invoke(target, new object[1] { text });
    
            Assert.AreEqual(string.Format("Private: {0}", text), 
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    We get and invoke the method using reflection.

  2. Another options is to use PrivateObject class. Using it you can easily call private method, but you have the same problem, you won't get compile exception when name or parameters are changed. Here is the same test written using PrivateObject:
    [TestMethod]
    public void PrivateWriteToConsolePrivateObject()
    {
        var currentConsoleOut = Console.Out;
    
        PrivateObject target = new PrivateObject(typeof(DummyClass));
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            target.Invoke("PrivateWriteToConsole", text);
    
            Assert.AreEqual(string.Format("Private: {0}", text), 
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    
  3. And here is the third option which I think is the best. You can add .accessor file containing the name of the assembly whose private methods you want to see, or you can use Visual Studio "Create Unit Tests..." wizard to do this for you:

    this will add the following unit test:
    /// 
    ///A test for PrivateWriteToConsole
    ///
    [TestMethod]
    [DeploymentItem("ConsoleLogger.exe")]
    public void PrivateWriteToConsoleTest()
    {
        DummyClass_Accessor target = new DummyClass_Accessor(); // TODO: Initialize to an appropriate value
        string text = string.Empty; // TODO: Initialize to an appropriate value
        target.PrivateWriteToConsole(text);
        Assert.Inconclusive("A method that does not return a value cannot be verified.");
    }
    
    we will modify it for our needs:
    /// 
    ///A test for PrivateWriteToConsole
    ///
    [TestMethod]
    [DeploymentItem("ConsoleLogger.exe")]
    public void PrivateWriteToConsoleTest()
    {
        var currentConsoleOut = Console.Out;
    
        DummyClass_Accessor target = new DummyClass_Accessor();
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            target.PrivateWriteToConsole(text);
    
            Assert.AreEqual(string.Format("Private: {0}", text),
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    
    When Visual Studio builds the project it will generate ConsoleLogger_Accessor.exe assembly, containing DummyClass_Accessor class with public methods only.
  4. Just to mention that you can test internal methods using the same approaches, but you will have one more option - in the AssemblyInfo file of the assembly being tested, you can add  InternalsVisibleTo attribute to specify which assembly will see the internal methods, in our case:
    [assembly: InternalsVisibleTo("ConsoleLogger.Tests")]
    
    now we will add an internal method to the same class:
    using System;
    
    namespace ConsoleLogger
    {
        public class DummyClass
        {
            public void WriteToConsole(string text)
            {
                Console.Write(text);
            }
    
            private void PrivateWriteToConsole(string text)
            {
                Console.Write("Private: " + text);
            }
    
            internal void InternalWriteToConsole(string text)
            {
                Console.Write("Internal: " + text);
            }
        }
    }
    
    and here is the working test method:
    [TestMethod]
    public void InternalWriteToConsoleTest()
    {
        var currentConsoleOut = Console.Out;
    
        DummyClass target = new DummyClass();
    
        string text = "Hello";
    
        using (var consoleOutput = new ConsoleOutput())
        {
            target.InternalWriteToConsole(text);
    
            Assert.AreEqual(string.Format("Internal: {0}", text),
                consoleOutput.GetOuput());
        }
    
        Assert.AreEqual(currentConsoleOut, Console.Out);
    }
    
And here's the code - ConsoleLogger.zip

Getting console output within a unit test

Today I needed to test a method which writes to the Console to validate the ouput. It is not hard to change the default console output and check the result. However you may forget to return the original output at the end. So let's take a look at my solution.

Let say we have the following class we want to test:
using System;

namespace ConsoleLogger
{
    public class DummyClass
    {
        public void WriteToConsole(string text)
        {
            Console.Write(text);
        }
    }
}

I have created a small helper class to redirect the output to a StringWriter:
using System;
using System.IO;

namespace ConsoleLogger.Tests
{
    public class ConsoleOutput : IDisposable
    {
        private StringWriter stringWriter;
        private TextWriter originalOutput;

        public ConsoleOutput()
        {
            stringWriter = new StringWriter();
            originalOutput = Console.Out;
            Console.SetOut(stringWriter);
        }

        public string GetOuput()
        {
            return stringWriter.ToString();
        }

        public void Dispose()
        {
            Console.SetOut(originalOutput);
            stringWriter.Dispose();
        }
    }
}
Now let's write the unit test:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ConsoleLogger.Tests
{
    [TestClass]
    public class DummyClassTest
    {
        [TestMethod]
        public void WriteToConsoleTest()
        {
            var currentConsoleOut = Console.Out;

            DummyClass target = new DummyClass(); 
            
            string text = "Hello";

            using (var consoleOutput = new ConsoleOutput())
            {
                target.WriteToConsole(text);

                Assert.AreEqual(text, consoleOutput.GetOuput());
            }

            Assert.AreEqual(currentConsoleOut, Console.Out);
        }
    }
}
This way we are sure that the original output will be restored and it's easy to get the output from the console.

You can find the sample here ConsoleLogger.zip.

Thursday, November 8, 2012

How to configure local Nuget Repository

After my last posts about Nuget packaging I wanted to share another useful experience with Nuget.
You can create a local repository to store all the packages you need and not to download those every time.
  1. To do this I have created a folder C:\NugetConfig\Repo and I have copied there the Newtonsoft.Json.4.5.10.nupkg package file
  2. To make the both solutions use this local repository all I have to do is to change the following settings in the NuGet.targets file:
    <ItemGroup Condition=" '$(PackageSources)' == '' ">
        <!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
        <!--
            <PackageSource Include="https://nuget.org/api/v2/" />
            <PackageSource Include="https://my-nuget-source/nuget/" />
        -->
    </ItemGroup>
    
    and adding s new PackageSource location
    <ItemGroup Condition=" '$(PackageSources)' == '' ">
        <!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
        <!--
            <PackageSource Include="https://nuget.org/api/v2/" />
            <PackageSource Include="https://my-nuget-source/nuget/" />
        -->
        <PackageSource Include="C:\NugetConfig\Repo" />
    </ItemGroup>
    
    And that's it. This will make the solution search for the used packages in the given folder and you will get а meaningful error if the package could not be found.
  3. Furthermore you can add you local repository to the visual studio package sources
    so that you will be able to search and add packages from it to any new solution:
As usual you can find the code here NugetConfig-Local-Repo.zip.