binary dreams

a world of 1s and 0s

How to set the company name in your Visual Studio project without a new template

Whenever I create a new solution in Visual Studio 2013 (my current IDE of choice) I have to set the

The Problem

Whenever I create a new solution in Visual Studio 2013 (my current IDE of choice) I have to set the Company name twice for each brand new project.

Right-click on your project and select Properties.

Click on Assembly Information...


Then change the CompanyName to whoever you work for but I don't want to do that every time.

How I found it

I knew I didnt want a custom project template just for these to properties so I knew I needed to find the actual file. Turns out its not in the file itself.

I decided to look in this ProjectTemplate location for a project.

In this case I am showing the TestProject.zip in the Test\1033

If you choose any project in this folder you will find a ZIP file with 3 files inside.

Copy the assemblyinfo.cs to another folder and Edit in Notepad. And there it is.

I then did a web search for 'where is the $registeredorganization$ set'. Turns out this is set in the registry but not the entries listed on this page.

The fix

To save you editing these properties in your brand new Vusal Studio projects you just need to edit the registry.

Go to Start and type 'regedit' into the search box. Then click on the 'regedit.exe'.

First backup your current registry by going to File > Export, select your save location, type a file name, make sure Export Range is set to All and click Save.


Find the entry 'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion'. When you click on the CurrentVersion folder you will see two properties among many, RegisteredOrganization and RegisteredOwner.

Right-click on each property, select Modify, update with your organisation and click OK.


Create your brand new project and you will find you have your company as it should be.

You may need to restart Visual Studio.

Done!

Give your QA a stub while you develop your service

In my development career I have often needed to provide a stub of my service. In this case I develop

In my development career I have often needed to provide a stub of my service to help test an application.

I originally started to hardcode data to return specific responses. I realised this was wrong a few years ago when I had to continually change customer identifiers to suit the testing taking place. This was wrong and so I changed my strategy from then on.

In this post I will go through what a stub should and should NOT do, show how my reusable stub class works and provide an example of it.


The stub rules

A stub should:

  • Provide the ability to return a response that is not easily repeatable.
  • Enable it to be used in a larger test with other applications.
  • Save the developer and/or QA doing all sorts of complex data setup that may be required. I.e. Database.
  • Allow anyone to set the response of the service method to whatever is possible for that operation.
  • Be lean. It shouldn't be time-consuming to maintain.
  • NOT tightly couple specific data requests to specific responses. This only increases the maintenance for the developer to change it when required.

Do bare in mind this solution does limit the stub by returning the same response to whatever called it after whoever set it. For example, if two people want different responses then they need to negotiate their time testing of the service.


The response object we want to stub

We want to set the main method to return this response object.

    [DataContract]     public class CalculateResponse     {         [DataMember]         public ValueType TypeOfValue { getset; }         [DataMember]         public object Result { getset; }     }

    public enum ValueType
    {
        Byte,
        Short,
        ShortUnsigned,
        Integer,
        IntegerUnsigned,
        Double,
        Float
    }


The stub base class 

So to make it easier to reuse I needed two reusable methods to call for a Set method and the main method.

The SetResponse will take whatever object the TResponse is and the method name, serialise the TResponse object into xml and save it as the method name, for example CalculatorServiceStub_Calculate.xml. If the XML file already exists the code will overwrite it.

public void SetResponse<TResponse>(TResponse response, string methodName)     where TResponse : classnew() {     if (response == null)         throw new ArgumentNullException("request");     if (string.IsNullOrWhiteSpace(methodName))         throw new ArgumentException("Value cannot be null, empty or have whitespace."
"methodName");     try     {         var xml = CreateXML<TResponse>(response);         SaveXML(methodName, xml.ToString());     }     catch (Exception exception)     {         // log the exception         throw;     } } private StringBuilder CreateXML<TResponse>(TResponse response)      where TResponse : classnew() {     var xml = new StringBuilder();     var serialiser = new XmlSerializer(response.GetType());     var writerSettings = new XmlWriterSettings();     using (XmlWriter xmlWriter = XmlWriter.Create(xml, writerSettings))     {         serialiser.Serialize(xmlWriter, response);     }     return xml; } private void SaveXML(string methodName, string xml) {     string fullPath = StubXmlLocation(methodName);     using (Stream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))     {         XmlDocument document = new XmlDocument();         document.LoadXml(xml);         document.Save(stream);     } }

The xml filename is created using the StubXmlLocation method.

        private string StubXmlLocation(string method)
        {
            var setting = ConfigurationManager.AppSettings["StubXmlOutputLocation"];
            string path = string.IsNullOrWhiteSpace(setting) ? @".\" : setting;
 
            string className = this.GetType().Name;
 
            return string.Format("{0}{1}_{2}.xml", path, className, method);
        }

The RetrieveResponse will take the method name. The Xml will be loaded from the expected filename and serialised into the TResponse object.

public TResponse RetrieveResponse<TResponse>(string methodName)     where TResponse : classnew() {     if (string.IsNullOrWhiteSpace(methodName))         throw new ArgumentException("Value cannot be null, empty or have whitespace."
"methodName");     TResponse response = new TResponse();     try     {         XDocument xmlDocument = XDocument.Load(StubXmlLocation(methodName));         using (TextReader textReader = new StringReader(xmlDocument.ToString()))         {             var serialiser = new XmlSerializer(response.GetType());             response = (TResponse)serialiser.Deserialize(textReader);         }     }     catch (Exception exception)     {         // log the exception         throw;     }     return response; }

Using both of these public methods works incredibly well because any changes to the service contract will be reflected the next time the SetResponse method is called and the new XML saved.

The saved xml file contents could look like this:

<?xml version="1.0" encoding="utf-16"?>
<CalculateResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <TypeOfValue>Integer</TypeOfValue>
  <Result xsi:type="xsd:int">10</Result>
</CalculateResponse>


The Service Stub

Now in your service you would have something like this using the two methods. Now your stubbing is so easy!

public class CalculatorServiceStub : StubBaseICalculatorServiceStub {     public CalculateResponse Calculate(CalculateRequest request)     {         if (request == null)             throw new ArgumentNullException("request");         return RetrieveResponse<CalculateResponse>("Calculate");     }     public void SetCalculate(SetCalculateRequest request)     {         if (request == null)             throw new ArgumentNullException("request");         SetResponse<CalculateResponse>(request.Request, "Calculate");     }

}


I have attached the example Visual Studio 2012 project as a ZIP file. CalculatorService.zip (79KB)

Get stubbing!

How to use Moles

This blog post is a copy of information I gathered at the time many moons ago for Moles and may well

This blog post is a copy of information I gathered at the time many moons ago for Moles and may well be inaccurate now but here for reference. I was using Visual Studio 2010 at the time.

Moles best practice

When moling, follow this best practice:

  • Use moles as a last resort. Stubs are the preference to mocks. If the object you want to mock has an interface or base class create a stub!
  • Always mole your external classes, even constructors! Even empty ones. Do not rely on other code not changing for your tests to pass.
  • The preference is for system DLLs to not be moled unless absolutely necessary. You really want them to work as they normally should. Plus you don't want loads of moles for loads of .NET interactions. Moling a system DLL would be required if you must interact with, configuration, files or some other external dependency.
  • Observer Locals
    Use booleans when testing for when a property is get or set and when methods are called. For when collections are built, a count should be adequate. Then Assert at the end of the test.
  • Use Stubs rather than Moles wherever possible as moles have reportedly worse performance. There is no study to confirm this or even how badly the performance is. It is just in said in the Moles documentation. http://research.microsoft.com/en-us/projects/pex/documentation.aspx
  • Consider putting reuseable mock methods into own class with the naming convention as <ClassName>Mock, e.g. DateTimeMock.
  • A mock method should ideally handle only one method in the object even if you mock all the other ones. This allows better reuse across the tests as some paths will not require the mocked methods.
  • Use our custom the ParameterValidator class (which throws a ParameterValidatorException) to check mole parameters instead of Assertions to keep to the principle of one Assert per test. This will also not confuse anyone when tests break.

Moles knowledge base

MoleNotImplementedException thrown

Fix

Add missing mole.

How do you mole an object in System.dll/mscorlib.dll?

Fix

Mole the DLL as normal but add the following attributes to the xml file:

<Moles xmlns="http://schemas.microsoft.com/moles/2010/">

<Assembly Name="System" ExportedTypes="true" ReflectionOnly="true" />

</Moles>

There are some special types that cannot be moled. There is currently no list of specific types that are listed as unmoleable.

From http://stackoverflow.com/questions/8144653/moling-system-dll.

Moved a class, namespace changed and not moling that class?

Fix

Clean the solution and rebuild.

Mole complains about COM object

Fix

Moling Interop.Vixcom needed the "Embed interop Types" property on the dll set to false to stop Moles generator complaining.

InvalidOperationException: Dynamic operations can only be performed in homogenous AppDomain

Fix

Change a value in the Moles config file:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\Microsoft.Moles.VsHost.x86.exe.config

From:

  <runtime>
     <legacyCasPolicy enabled="true" />
  </runtime>

To:

  <runtime>
     <legacyCasPolicy enabled="false" />
  </runtime>

Information

http://social.msdn.microsoft.com/Forums/en/pex/thread/0a931fc1-9049-482a-bf2d-5499ccf65b82

TFS build shows a Moles warning

Example

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets (1360): Could not resolve this reference. Could not locate the assembly "mscorlib.Moles, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0ae41878053f6703, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

Fix

  • Unload the test roject. Right-click on the unloaded project and select "Edit ... proj"
  • Replace this reference
    <Reference Include="mscorlib.Moles.dll, Version=4.0.0.0, Culture=neutral, 
    PublicKeyToken=0ae41878053f6703, processorArchitecture=MSIL"
     />  
  • With this
    1. <Reference Condition="Exists('..\..\MolesAssemblies\mscorlib.Moles.dll')" Include="mscorlib.Moles.dll">   
    2.   <SpecificVersion>False</SpecificVersion>   
    3.   <HintPath>..\..\MolesAssemblies\mscorlib.Moles.dll</HintPath>  
    4. </Reference>  
  • Note: The moles hint path assumes the test project is referencing from a "bin\Debug" folder.
  • Note: If you get local compile warnings of "The referenced component 'mscorlib.Moles' could not be
    found.
    " then ignore it.

How to install a certificate to call an external service

Installing a certificate to use with an external service.

In my previous company I needed a set of instructions for anyone to use when installing an Experian certificate on a server. This certificate was required when calling the Experian servers from a WCF service hosted in IIS. These instructions can be reused for other similar scenarios.

Now we need to add the certificate.

  1. Click Start > Run...
  2. Type MMC and click OK
  3. Click Yes and the Management Console will open.
  4. Select File > Add Remove Snap-in.
  5. Double-click on Certificates.
  6. Select Computer Account and click Next then Finish.
  7. Click OK.
  8. Expand the Certificates (Local Computer).
  9. Right-click on Personal, select All Tasks and Import.
  10. Browse to the location of the certificate you are using. You may need to change the type of files to "All files".
  11. Click OK.
  12. Click Next.
  13. Enter the password (if required). the UAT certificate password is "password".
  14. Click Next and Finish.
  15. Click on the Personal > Certificates folder.
  16. Drag and drop the Intermediate certificate to the Intermediate Certification Authorities > Certificates folder.
  17. Drag and drop the Trusted Root CA to the Trusted Root Certification Authorities > Certificates folder.
  18. Now we need to make sure the Network Service has the permission to use the certificate.
  19. Still in MMC, expand the Personal > Certificates folder.
  20. Right-click on the certificate supplied and select All Tasks > Manage Private Keys...
  21. Click Add and in the object names text box enter NETWORK SERVICE.
  22. Click OK and OK again.
  23. Close the MMC. No need to save console settings.

 

One more thing. I highly recommend you use the Smoke Tester to do some basic tests on the certificate after installation.

How to check the results of an XPath query against an XML document using the SmokeTester

In June 2014 my ex-colleague open sourced a smoke test tool that we began using at&amp;nbsp;our previous

In June 2014 my ex-colleague open sourced a smoke test tool that we began using at our previous company. It was originally created by another colleague to be used for deployment testing. You could check a WCF service responds as expected, a database connection succeeds or the AppSettings in a configuration file are as expected.

I had a problem recently where I needed to confirm my WiX installer had successfully set the website Windows Authentication providers to "NTLM, Negotiate" - in that order. To do this I needed to create a brand new smoke test - the XMLDocumentTest.

The idea of this smoke test is to run an XPath query over an XML document. In my test I needed to check the IIS applicationHost.config file. Here is a sample of it's contents:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="Fake Application">
<system.webServer>
<security>
<authentication>
<digestAuthentication enabled="false" />
<basicAuthentication enabled="false" />
<windowsAuthentication enabled="true">
<providers>
<clear />
<clear />
<add value="NTLM" />
<add value="Negotiate" />
</providers>
</windowsAuthentication>
</authentication>
</security>
</system.webServer>
</location>
</configuration>

Then if you run this XPath query over it.

/configuration/location[@path='Fake Application']/system.webServer/
security/authentication/windowsAuthentication/providers/add

You should get this result.

<add value="NTLM" />
<add value="Negotiate" />

I highly recommend the XPathBuilder application to work out your query for the smoke test.

The smoke test will look like this. Make sure the XPathQuery and ExpectedOutput elements have no line breaks, otherwise the test will not succeed.

<?xml version="1.0" encoding="utf-16"?>
<ConfigurationTestSuite xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>XMLDocumentTests</Name>
<Description>This a sample smoke test of the XMLDocumentTest</Description>
<Tests>
<Test xsi:type="XMLDocumentTest">
<TestName>Check Windows Auth providers</TestName>
<Path>C:\location\of\configfile\</Path>
<Filename>applicationHost.config</Filename>
<XPathQuery>/configuration/location[@path='Fake Application']/system.webServer/
security/authentication/windowsAuthentication/providers/add</XPathQuery>
<ExpectedOutput><add value="NTLM" /><add value="Negotiate" /></ExpectedOutput>
</Test>
</Tests>
</ConfigurationTestSuite>

To use the tool you can run this command. Make sure the InstallationSmokeTest.exe and smoke test file are together when running it.

InstallationSmokeTest.exe Run FakeSmokeTest.xml

At the time of posting the new test is only in the Main branch. You can download the latest Smoke Tester from CodePlex and read more information on the smoke tester here.

How to fix orphaned SQL login users

If ever you have the message that the login failed it may be because of an orphaned user.

Run this to check what orphaned users you have.

EXEC sp_change_users_login 'REPORT'

Then run this to fix it. Where ‘LoginName’ is the login and then the user it is attached to.

EXEC sp_change_users_login'UPDATE_ONE','LoginName','LoginName'

From this website http://mcpmag.com/articles/2011/02/17/fixing-sql-server-2008-database-orphans.aspx

How to easily reset your UK (or other domain) Windows password

My&amp;nbsp;employer&amp;nbsp;has been migrating to another domain for some time. This has been a problem wh

My employer has been migrating to another domain for some time. This has been a problem when you have to reset more than one password and your e-mail depends on the legacy domain. I found a way where you have no need to login as UK OR wait for Outlook to tell you you need to change your password.

Do this.

  1. Press Ctrl-Alt-Del to view the lock screen menu.
  2. Select Change a password...
  3. Type in your UK login i.e. UK\Username
  4. Enter your old and new passwords.
  5. Click OK.

 

Done!

How to enable your Wix installer to upgrade your application

To  help reduce the amount of manual steps required in my change management form I needed to avoid uninstalling and installing our product.

To do this I found a way in WiX to upgrade the product using the following.

<Upgrade Id="PUT_UPGRADECODE_GUID_HERE">
<UpgradeVersion OnlyDetect="yes" 
Minimum="!(bind.FileVersion.YOUR_PROJECT_DLL.dll)" 
Property="NEWERVERSIONDETECTED" 
IncludeMinimum="no" />
<UpgradeVersion OnlyDetect="no" 
Maximum="!(bind.FileVersion.YOUR_PROJECT_DLL.dll)" 
Property="OLDERVERSIONBEINGUPGRADED" 
IncludeMaximum="no" />
<!-- Detect for changes in 4th field only -->
<UpgradeVersion Property="ANOTHERBUILDINSTALLED" 
Maximum="!(bind.FileVersion.YOUR_PROJECT_DLL.dll)" 
Minimum="!(bind.FileVersion.YOUR_PROJECT_DLL.dll)" 
IncludeMinimum="yes" 
IncludeMaximum="yes" 
OnlyDetect="no" />
</Upgrade>

In your Product.wxs file. Change the ProductId attribute to just an asterisk(*). The UpgradeCode attribute should stay as it is.

<Product Id="*" Name="Your Project" 
Language="1057" 
Version="!(bind.FileVersion.YOUR_PROJECT_DLL.dll)" 
Manufacturer="Your Company Ltd" 
UpgradeCode="PUT_UPGRADECODE_GUID_HERE">

Now add the complete <Upgrade> section. Put it near the top between the <Media> and the <UI> tags.

The <Upgrade> Id in should be the same GUID as the UpgradeCode in the <Product> tag above.

Change the YOUR_PROJECT_DLL to your DLL.  

To stop an install of an older version over a newer version add the following tag before the <InstallExecuteSequence>. 

<CustomAction Id="CA_BlockOlderVersionInstall" 
Error="A later version of [ProductName] is already installed. Setup will now exit." />
<InstallExecuteSequence> ...

Add the following to the start of your <InstallExecuteSequence> tag.

<InstallExecuteSequence>
<Custom Action="CA_BlockOlderVersionInstall" After="FindRelatedProducts">
<![CDATA[NEWERVERSIONDETECTED]]>
</Custom>
<LaunchConditions After="AppSearch" />
<!-- Schedule RemoveExistingProducts early -->
<RemoveExistingProducts After="InstallInitialize" />
... other custom actions ...
</InstallExecuteSequence>

Now test it! 

How to use C# properties with SOLID class design principles

It wasn&#39;t so long ago I was using properties without any consideration to how they SHOULD be used. I&#39;m going to show you how you can use them properly with the help of SOLID Class Design Principles.

It wasn't so long ago I was using C# properties without any consideration to how they SHOULD be used. I'm going to show you how you can use them properly with the help of SOLID Class Design Principles.

Case 1:

This is a typical class you might have written.

public class Person
{
public string Forename { get; set; }
public string Surname { get; set; }
public Person() {}
}

STOP! Using public setters here with the person attributes breaks the Single Responsibility Principle (SRP) because the class has more than one reason to change. The class breaks this with two reasons - Forename and Surname.

To fix this, make the setters of those properties private and create an Update method like so:

public class Person
{
public string Forename { get; private set; }
public string Surname { get; private set; }
public void Update(string forename, string surname)
{
Forename = forename;
Surname = surname;
}
}

Now the class has one reason to change rather than two.

In general an object should not have it's state changed unless it was changed by an action. Remember OO design is about data hiding, how an objects attribute changes is of no concern to its consumer. Only the object needs to know how it changes.

Case 2:

How would you check the object is valid? Check each property like this:

var person = new Person();
person.Update("forename", "surname");
if (person.Surname != null && person.Forename != null)
{
SaveToDatabase(person);
}

STOP! This breaks the Dependency Inversion Principle (DIP) - Depend on abstractions not on concretions. We need to create a validation method to abstract us from the attributes. The properties should not be checked outside of the class but from inside the class.

Lets rewrite it.

Create an interface

public interface IValidate
{
	bool IsValid();
}

Now change the Person class.

public class Person : IValidate
{
public string Forename { get; private set; }
public string Surname { get; private set; }
public void Update(string forename, string surname)
{
Forename = forename;
Surname = surname;
}
public bool IsValid()
{
return (Forename != null) && (Surname != null);
}
}

With the Person class rewritten you would use it like so.

var person = new Person();
person.Update("forename", "surname");
if (person.IsPersonValid())
{
SaveToDatabase(person);
}

How to configure your unsecured WCF or ASMX service for round-robin load balancing

I was asked to investigate how to get our load balancing working with our services stack. Our services stack is used by many clients, a bespoke legacy Delphi EPOS application and various internal websites.

This blog post details how to load balance using an unsecured endpoint only. To use a secured endpoint needs further investigation. In our case an unsecured endpoint was acceptable because we are not communicating outside our company network.

The load balancer

We have a Netscaler hardware load balancer configured as Round-Robin with Persistence set to None. This means each call will go to the next server and the connection to a server will not be persisted. 

Our network guy configured the load balancer to call a url every 5 minutes - in this case a service. Once called it will return the service page and it will check for specific text and as long as that happens then its successful. Doing this gives us an early warning system if a service or IIS is down and adds to the practice of zero-downtime deployments. 

Enable your WCF Service to be load balanced

Add this binding to your web.config:

<bindings>
<customBinding>
<binding name="httpBinding">
<httpTransport keepAliveEnabled="false" />
</binding>
</customBinding>
</bindings>

 If you have existing applications that use an existing endpoint, do not replace it but add the following endpoint to your web.config. 

<services>
<service>
<endpoint address="http://fakehost/fakewebsite/FakeService.svc/custom" 
contract="FakeContract.IFakeContract" binding="customBinding" 
bindingConfiguration="httpBinding" name="custom" />
</service>
</services>

How to enable your client to call a load balanced application

Add this binding to your client app.config: 

<bindings>
<customBinding>
<binding name="httpBinding">
<httpTransport keepAliveEnabled="false" />
</binding>
</customBinding>
</bindings>
Add this endpoint to your client app.config:
<client>
<endpoint address="http://fakehost/fakewebsite/FakeService.svc/FakeService/basic" 
contract="FakeContract.IFakeContract" binding="customBinding" 
bindingConfiguration="httpBinding" name="basic" />
</client>
 
Your local network admin might advise that you need to add this <bypasslist> element to a <defaultProxy>: 
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<bypasslist>
<add address="10.*"/>
</bypasslist>
<proxy autoDetect="False" proxyaddress="http://fakeproxy" bypassonlocal="True" />
</defaultProxy>
</system.net>

You don't want to go via your network proxy if you don't need to. It's inefficient.

How to call a load balanced ASMX service

To call an ASMX service that is load balanced you must add the following custom binding and a similar endpoint.

<system.serviceModel>
<bindings>
<customBinding>
<binding name="HttpBinding">
<textMessageEncoding messageVersion="Soap11" />
<httpTransport keepAliveEnabled="false" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://fakeserver/FakeService/Fake.asmx" 
binding="customBinding" bindingConfiguration="HttpBinding" 
contract="FakeProxyServiceReference.FakeSoap" name="CustomBinding_HttpBinding" />
</client>
</system.serviceModel>