Code challenge from lantmateriet.se

Yesterday I found a code challenge on http://www.lantmateriet.se/knackkoden that I decide to take a look on. We first need to decode the base 64 encoded text to get the actual instructions.

Problem
Gör ett program som skriver ut talen i mängden {1, 2, …, 10500} i stigande ordning.
Om talet är jämnt delbart med 3 så ska www. skrivas ut istället för själva talet.
Om talet är jämnt delbart med 5 så ska lantmateriet skrivas ut istället för själva talet.
Om talet är jämnt delbart med 7 så ska .se skrivas ut istället för själva talet.
Om talet är jämnt delbart med 3, 5 och 7 så ska www.lantmateriet.se skrivas ut istället för själva talet.
Inga nyradstecken ska skrivas ut, utan allt ska skrivas ut på en och samma rad.
Utskriften inleds enligt nedan:
1 2 www. (och så vidare…)
Inget mellanrum som sista tecken.
MD5-summan av utskriften är 402087a86f4fbd5d01d80baec13fddc5
Men vad är SHA-1-summan?

Solution
Anyone that can come up with another or better solution?

public static void Main()
{
    const int NumberOfIterations = 10500;
    var sb = new StringBuilder();
    for (var i = 1; i <= NumberOfIterations; i++)
    {
        if (i % 3 != 0 && i % 5 != 0 && i % 7 != 0)
        {
            sb.Append(i + " ");
            continue;
        }
 
        if (i % 3 == 0 && i % 5 == 0 && i % 7 == 0)
        {
            sb.Append("www.lantmateriet.se ");
            continue;
        }
 
        if (i % 3 == 0)
        {
            sb.Append("www. ");
        }
        else if (i % 5 == 0)
        {
            sb.Append("lantmateriet ");
        }
        else if (i % 7 == 0)
        {
            sb.Append(".se ");
        }
    }
 
    var resultString = sb.ToString().TrimEnd();
    if ("402087a86f4fbd5d01d80baec13fddc5" != GetMD5HashData(resultString, Encoding.UTF8))
    {
        Console.WriteLine("Error missmatch MD5 hash");
        return;
    }
 
    Console.WriteLine("The SHA1 hash is:" + GetSHA1HashData(resultString, Encoding.UTF8));
}

You can download the complete solution here: LantmaterietKnackkoden

Dear Engineers, your job is not to write code!

I recently found a blog post by Laura Klein that did really speak to me. It simple state that our job is not to produce as much code as possible, we are suppose to add value for the customer. This implies that it’s more important to know the customer and to add metrics that proves that we are actually adding value instead of simple hacking according to specification.

You can read the full blog here.

Get full qualified host name in WIX

In one of our install we need to know the full qualified computer name during installation. For that purpose I did create an custom action with a simple vbscript that simple get the computer name and domain name and create the full qualified string and set property FQDN accordingly.

<CustomAction Id="FindHostDomain" Script="vbscript" Return="check">
  <![CDATA[
  Dim Info
  Set Info = CreateObject("AdSystemInfo")
  Dim InfoNT
  Set InfoNT = CreateObject("WinNTSystemInfo")
 
  Session.Property("FQDN") = lcase(InfoNT.ComputerName & "." & Info.DomainDNSName)
  ]]>
</CustomAction>

To execute this script and set FQDN so we can use it in our component’s add this to the install execution sequence.

<InstallExecuteSequence>
  <Custom Action="FindHostDomain" Before="CostInitialize" >Not Installed</Custom>
</InstallExecuteSequence>

System.UnauthorizedAccessException: Access to the path is denied when using System.OI.FileStream

During a recent deployment to production environment we started to get System.UnauthorizedAccessException on places we hade not seen it before. After some debugging a pattern appeared. The problem is that if you don’t use the FileStream constructor with FileAccess parameter you will get FileAccess.ReadWrite selected by default. So in our cases the User account running our service did only have read access to the file with is correct since we are only expecting to read from the file.

using (FileStream fs = new FileStream(filePath, FileMode.Open))
{}

Make sure, you ask for what you really need. If your application needs only Read access to a file, make sure to specify that in your FileStream constructor.

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{}

HowTo add new key to appsettings with WIX

When adding a new key for appsettings you need to split the action in 3 steps.
1. Create the new empty “add” element
2. Create and set the “key” attribute. The tricky part here is how to add the “key” to new created “add” element from step one. One way is to assume that the new created “add” element is the only element without a “key” attribute
3. Create and set the “value” attribute.

<util:XmlFile 
  Id='conf1' 
  Action="createElement" 
  ElementPath="//configuration/appSettings" 
  Name="add" 
  File="[INSTALLDIR]Web.config" 
  Sequence="1" />
<util:XmlFile 
  Id='conf2' 
  Action="setValue" 
  ElementPath="//configuration/appSettings/add[\[]not(@key)[\]]"
  Name="key" 
  Value="NewConfig" 
  File="[INSTALLDIR]Web.config" 
  Sequence="2" />
<util:XmlFile 
  Id='conf3' 
  Action="setValue" 
  ElementPath="//configuration/appSettings/add[\[]@key='NewConfig'[\]]"
  Name="value" 
  Value="the new value" 
  File="[INSTALLDIR]Web.config"
  Sequence="3" />

HowTo to set appsettings during installation using WIX

The point where most people have a hard time is remembering is to escape brackets. This to ensure WIX will not think it a property. If you forget to-do this you may end up in a situation where “config2” value will bet set on “config1” instead. See a correct example bellow

[ should be [\[]
] =should be [\]]

<Component Id='UpdateConfig' Guid='A89D47AF-7DBE-4a8d-9848-F35C78FD95ED' DiskId='1' KeyPath="yes">
  <util:XmlFile Id='config1' 
                Action="setValue" 
                ElementPath="//configuration/appSettings/add[\[]@key='FirstKey'[\]]/@value"
                File="[INSTALLDIR]Web.config" 
                Value="[NEWVALUE1]" />
  <util:XmlFile Id='config2' 
                Action="setValue" 
                ElementPath="//configuration/appSettings/add[\[@key='SecondKey'[\]]/@value"
                File="[INSTALLDIR]Web.config" 
                Value="[NEWVALUE2]" />
</Component>

And the example web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="FirstKey" value="oldvalue"/>
    <add key="SecondKey" value="oldvalue"/>
  </appSettings>
</configuration>

HowTo update appsettings programmatically

Recently I was writing functional test for an application that read settings from the appsettings element in App.Config. The problem was that the application under test was expecting to react different based on the settings so need a way to alter the values between tests. I ended up writing bellow code for it

private static void SetAppSettings(string key, string value)
{
   Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
   config.AppSettings.Settings[key].Value = value;
   config.Save(ConfigurationSaveMode.Modified);
   ConfigurationManager.RefreshSection("appSettings");
}

Scrumy on Softpedia

Today I happen to find out that Scrumy have been added to Softpedia’s library of software. It’s nice to see that people are interested in my project and that they have even rated it with 5 stars.

http://www.softpedia.com/get/Programming/Components-Libraries/Scrumy.shtml

Share source files between Visual Studio projects

After some time developing software you naturally start to repeat yourself and solve the same problem over and over again. If you could simple share this implementations between all your solution’s, you would save a lot of time. On common way to share source code between different project is to create separate tool/”good to have code” assembly and simply include this project or assembly into every solution. Many times I find this very heavy weighted and overkill. But the big problem according to me is that you have expanded the attack surface of your application, by adding public API’s that you are not using but can be used by hackers. So the other solution is to simple add the part you actual need to your solution. By adding the source file as linked resources, will enable you to share it between many projects and still maintain only one copy of the file.

Another good example of usage is if you for example are creating an application for both windows phone 7 and windows. In this case you need two separate projects for every class library.

In Visual Studio, choose ‘Add As link’ when adding an existing item.
AddAsLink in Visual Studio

Get all iteration paths in TFS programtically

A common way to organize work items in TFS is to assign them to different iterations. I’m using this with the scum model where every sprint corresponds to one iteration. So how can we get all iteration paths in TFS to use them in our own implementation. The information is not saved on the work items, we will need to look directly at the project object and recursively iterate on the iteration object tree to get all iteration paths.

Example project
TFSIterationPath
In this example you will be able to connect to a TFS server and get all work items based on project and iteration path listed.
Read more

Next Page »

winterbottom_dny@mailxu.com