How I prefer to design…

by Mikael Henriksson 4. June 2011 13:25

I just read a great post by Alex James. He raises a few valid points. Some things I discovered over the last few weeks when I had to write tests for some functionality I had previously written without tests.

When writing the integration tests I discovered that it would have been much easier to express what I intended my code to do before I wrote the implementation. Now it doesn’t need to be perfect. Hey it doesn’t even need to make sense because in starting with some silly expectations before you write the implementation you will quickly improve the expressiveness of those expectations and when you feel like the intent is clear and concise go write the implementation. It’s a different design process but very similar and you won’t worry so much about anything except just that functionality you absolutely must have.

It's very helpful to try and incorporate some BDD into your workflow.

Tags:

BDD

How do I run a WCF service inside an MVC website OR Do you make good use of Linq?

by Mikael Henriksson 30. October 2010 18:22

The goal of this post

It took me some time to figure out how to have WCF services running inside an MVC website so I want to show you that but at the same time I want to show a smart way you can use Linq to remove some unnecessary code and at the same time make the code more readable and clear.

The background story

I recently had to create a route constraint for my MVC code because of wanting to add some internal REST service for getting products via the WCF REST template. This does not work by default for the following reason, MVC needs a default route and the default route overrides the service route because it is too generic (catch-all) but let’s back up a little. First of all the way MVC routing works is internally it doesn’t work out of the box so you need to tell MVC how it should route incoming requests. Fortunately the MVC templates are setup with the basic (catch-all) routes needed to get something running quickly. Unfortunately I it doesn’t come with any advanced routes default and no constraints but we’ll get to that next.

The problem

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("*.ico");
    routes.IgnoreRoute("*.js");
    routes.MapRoute("Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults
}

That is pretty much what ships with MVC. I did add two more routes one for my Product Service and one for my Registration Service. In .NET 4.0 this is done easily like below

routes.Add( new ServiceRoute("Register", 
            new WebServiceHostFactory(), 
            typeof(RegisterService)));
    
routes.Add(    new ServiceRoute("Product", 
            new WebServiceHostFactory(), 
            typeof(ProductService)));

The service routes should be added last, after the “Default Route” otherwise it could break SEO. MVC routing would end up looking like

http://site.com/default?controller=somecontroller&action=someaction

At this point though routing to the actual service doesn’t work. Your controller factory tries to find a controller because the catch all (default) route will be run before the service routes and it can’t find the controller for product or register.

The solution

We need to exclude our services from the default route. To do this and maintain some flexibility I chose to create a custom constraint. I found some solid guidance over on Stephen Walters blog http://stephenwalther.com/blog/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx
Stephen has created a NotEqualConstraint that I want to use but Stephen considered only one constraint and I want multiple since I have multiple WCF services running. I modified Stephens code a little and ended up with the following class.

public class NotEqualConstraint : IRouteConstraint
{
    private readonly string[] _match;

    public NotEqualConstraint(params string[] match)
    {
        _match = match;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var exists = false;
        foreach (var s in _match) {

            exists = String.Compare(values[parameterName].ToString(), s, true) != 0;
            if (exists) {
                break;
            }
        }

        return exists;
    }
}

Now I can switch the default route from the standard MVC example to the below code making use of an override of the MapRoute function.

routes.MapRoute("Default", // Route name
       "{controller}/{action}/{id}", // URL with parameters
       new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
       new { controller = new NotEqual("Register", "Product") }); // Constraints

Code works (what a bliss) but I am not too happy about the looping. It’s not clean enough for my taste.

The bonus

This basically has nothing to do with the post itself but is just a general tip on how to make good use of Linq2Objects. The above code can be simplified to the following using the Linq extension method Any.

public class NotEqualConstraint : IRouteConstraint
{
    private readonly string[] _match;

    public NotEqualConstraint(params string[] match)
    {
        _match = match;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return _match.Any(s => String.Compare(values[parameterName].ToString(), s, true) != 0);
    }
}

Footnote

Some people take great pride in their many lines of code. I am the opposite and certainly so when it makes the code even cleaner.

Tags: , ,

MVC | WCF | LINQ

How do I execute SQL script files from PowerShell during deployment?

by Mikael Henriksson 24. October 2010 19:40

This was a bit tricky figuring out. I was dead sure there was something I could use built in for MS SQL at least but to complicate things further I have to open an SSH connection before I can connect to the database server.

Since the SSH one was easier and a prerequisite I started with that one. What I wanted was to open putty with some arguments like a password but putty just closes itself after opening the connection so I had a read up on putty and it turns out it does not support command line access very good. Plink on the other hand fully supports what I needed. Since I always type this password I had some problems with authenticating. I totally got the password wrong all the time when looking at it and had to revert back to just writing it without looking or thinking. The Start-Process command does exactly what I needed.

For the MS SQL Server I was right there is a module for that but finding it was a pain in the neck. I kept reading about this Invoke-Sqlcmd but couldn’t find how to get it into my script but finally I found it over at MSDN (who would have guessed?). A potential problem with this approach is that the SSH connection speed isn’t instant so we need to pause for a few seconds before trying to connect with the database.

Since I am limited in the number of simultaneous connections it’s also really important to close that connection when I ‘m done so I have to loop through all the processes and “kill ’em all”. There is actually an alias for Stop-Process which is named Kill but to be really sure everyone understands what I am doing I chose to not use any short aliases for my scripts. It’s imperative that I start expressing myself clearer and more thorough.

Anyway, I hope someone finds this post useful.

add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100

$putty = "C:\apps\putty\plink.exe" 
Start-Process $putty -ArgumentList "-load saved_session -pw Password"

Start-Sleep -s 7
$base_dir = "D:\Projects\Project"

Invoke-Sqlcmd `
            -ServerInstance "127.0.0.1,1433" `
            -Database "Database" `
            -Username "Username" `
            -Password "Password" `
            -InputFile "$base_dir\src\Database\1.schema.sql"

$ids =Get-Process plink | Select-Object id

foreach ($id in $ids) {
    Stop-Process -Id $id.Id -Force `
                    -WarningAction:SilentlyContinue ` 
                    -Confirm:$false
}

Tags: ,

Continuous Delivery | PowerShell

How do I perform FTP uploads using PowerShell?”

by Mikael Henriksson 22. October 2010 22:51

It can be done pretty easily when you know how. The trick with PowerShell is to make good use of the power of .net framework. I just created a Github project called ps-ftp.  It’s pretty straight forward and since you can find the code there I’m just going to post an example usage.

$credential = new-object System.Net.NetworkCredential("username", "password")   
$url = "some.ftp.url.com"
$dir = D:\Project\Application\Release\WebClient
upload-directory -url $url -dir $dir -credential $credential

If you find any issues and what not please create an issue or even better fix it and do a pull-request.

Tags: ,

PowerShell | Continuous Delivery

How do I implement PHP compatible openssl sign/verify in C#?

by Mikael Henriksson 17. October 2010 11:28

This post should have been written ages ago. I had such a hard time figuring out how to solve this one I really want to share the working solution with everyone but have had to live life. I’ll write something about how to live life in a future post. Right now I’ll focus on OpenSSL and the PHP implementation of openssl_sign and how to implement openssl_verify to verify what was signed.

To start with there needs to be keys exchanged. Both parties should exchange public keys. The public keys should be used for verifying what the other end signed with their private key. Do not make the mistake of sending private keys. Then you need to generate a new one Smile.

Prerequisites

Before coding

First we need to create a new set of keys. This is done in two steps, first we generate a new private key and then we generate a public key using the private key as base.

#Private:
openssl genrsa -out private.pem 2048

#Public:
openssl rsa -pubout -in private.pem -out public.pem -outform PEM

Now we can send our public key to wherever it needs to go and start coding.

The code

using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;

namespace System.Cryptography
{
    public class Crypt
    {
        ///<summary>
        ///    Verifies that data and the openssl_signed signature can be verified with the given publicKey
        ///</summary>
        ///<param name = "msg">Raw data extracted on our side.</param>
        ///<param name = "signature">The data signed with other sides private key.</param>
        ///<param name = "publicKey">Other sides public key stored safely with us for authentication purposes.
        ///    <remarks>
        ///        either as a file path reference or raw text.
        ///    </remarks>
        ///</param>
        ///<returns></returns>
        public static bool Verify(String msg, String signature, String publicKey)
        {
            RsaKeyParameters remotepubkey = GetRsaPublicKey(publicKey);

            ISigner signer = SignerUtilities.GetSigner("SHA1withRSA");

            signer.Init(false, remotepubkey);
            var bytes = Convert.FromBase64String(signature);
            var msgBytes = Encoding.UTF8.GetBytes(msg);
            signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
            return signer.VerifySignature(bytes);
        }

        /// <summary>
        ///     Signs a string with our private key. The string can later be verified with our public key at receiving end.
        /// </summary>
        /// <param name = "data">The data that shall be signed.</param>
        /// <param name = "privateKey">Our private key, either as a file path reference or raw text.</param>
        /// <returns></returns>
        public static String Sign(String data, String privateKey)
        {
            RsaPrivateCrtKeyParameters privKey = GetPrivateKey(privateKey);
            ISigner sig = SignerUtilities.GetSigner("SHA1withRSA");
            sig.Init(true, privKey);
            var bytes = Encoding.UTF8.GetBytes(data);
            sig.BlockUpdate(bytes, 0, bytes.Length);
            byte[] signature = sig.GenerateSignature();

            var signedString = Convert.ToBase64String(signature);

            return signedString;
        }

        /// <summary>
        ///     Returns an instance of <see cref = "RsaKeyParameters" /> based on the supplied pemFile or pemstring
        /// </summary>
        /// <param name = "pemFile">Either the file path or the file content as text.</param>
        /// <returns></returns>
        public static RsaKeyParameters GetPublicKey(String pemFile)
        {
            return GetRsaPublicKey(pemFile);
        }

        /// <summary>
        ///     Returns an instance of <see cref = "RsaPrivateCrtKeyParameters" /> based on the supplied pemFile or pemstring
        /// </summary>
        /// <param name = "pemFile">Either the file path or the file content as text.</param>
        /// <returns></returns>
        public static RsaPrivateCrtKeyParameters GetPrivateKey(String pemFile)
        {
            if (string.IsNullOrEmpty(pemFile))
                throw new ArgumentNullException("pemFile");

            string privateKey = File.Exists(pemFile) ? File.ReadAllText(pemFile) : pemFile;

            var reader = new PemReader(new StringReader(privateKey));
            RsaPrivateCrtKeyParameters privkey = null;
            Object obj = reader.ReadObject();
            if (obj is AsymmetricCipherKeyPair) {
                privkey = (RsaPrivateCrtKeyParameters) ((AsymmetricCipherKeyPair) obj).Private;
            }
            return privkey;
        }

        /// <summary>
        ///     Returns an instance of <see cref = "RsaKeyParameters" /> based on the supplied PEM or DER file location or the PEM string
        /// </summary>
        /// <param name = "pemFile">Either the file path or the file content as text.</param>
        /// <returns></returns>
        public static RsaKeyParameters GetRsaPublicKey(string pemFile)
        {
            RsaKeyParameters pubkey = null;
            if (!File.Exists(pemFile)) {
                pubkey = GetPemPublicKey(pemFile);
            }
            else if (pemFile.EndsWith(".pem")) {
                pubkey = GetPemPublicKey(File.ReadAllText(pemFile));
            }

            return pubkey;
        }

        private static RsaKeyParameters GetPemPublicKey(string key)
        {
            var reader = new PemReader(new StringReader(key));
            object obj = reader.ReadObject();
            if (obj is RsaKeyParameters) {
                return (RsaKeyParameters) obj;
            }
            return null;
        }
    }
}

Tags: ,

C# | OpenSSL

Remote validation with MVC and jQuery (or my compliments to the chef)

by Mikael Henriksson 8. September 2010 22:09

First of all I want to direct you to one of the best blog posts ever. I could be giving away free points because it saved my soft behind from getting whipped but really guys, after searching high and low for some time and ending up with nothing I was finally able to do remote validation with jQuery and MVC!

Actually I have been able to do remote validation before but not using MicrosoftMVCJQueryValidation.js at the same time. Problem is that MMVCJQV overwrites the rules with some metadata somehow (not sure how but I’m working on it). So adding a remote rule at document.ready does nothing because MMVCJQV will just wipe it.

There was a tiny problem with his code though. I could not get it to work with more than one additionalProperty so I modified it a little. His method would never return more than the first additionalProperty  so Invoice_Id would be the value for a date etc .

I changed the following code:

if (props) {
    var data = {};

    for (var i = 0, l = props.length; i < l; ++i) {
        var param = props[i];
        data[props[i]] = function () {
            return $("#" + param).val();
        }
    }

    obj["data"] = data;
}

 

Into this :

if (props) {
    var data = {};
    for (var i = 0; i < props.length; i++) {
        var param = props[i];
        data[props[i]] = $("#" + param).val();
    }

    obj["data"] = data;
}

Edit:

Forgot to mention how I handle this on server side. I just use a FormCollection

[HandleError]
[HttpPost]
public virtual ActionResult DayIsValid(FormCollection form)
{
    var day = short.Parse(form["Day"]);
    var invoiceId = int.Parse(form["Invoice_Id"]);
    var result = _repository.DayIsUniqueForInvoice(invoiceId, day);
    var startDate = DateTime.Parse(form["Invoice_StartDate"]);  
    DateTime dtTo = startDate;

    // overshoot the date by a month
    dtTo = dtTo.AddMonths(1);
    dtTo = dtTo.AddDays(-(dtTo.Day));

    return Json(result && dtTo.Day >= day);
}

Keep in mind folks that it’s the generated id for the property that it will look for not the property name! Very important if you have complex models.´

Thanks again to Richard Kimber

Tags:

The reason for my social media come back

by Mikael Henriksson 16. August 2010 18:58

First of all I have not yet decided on whether or not I’ll keep the facebook account if I do it will be ONLY because  of linking back to my blog. I read somewhere that if you want to be someone on the internet you should get a profile on every major community and link to the rest.

Twitter


For twitter well I was sort of annoyed with it, I still feel there is way too little signal compared to the noise and I am only following a few but! I believe I was using twitter the wrong way. You are not supposed to read full conversations unless of course your twitter client allows that. At the same time I wish people would stop abusing twitter for discussing things. Nehmen Sie bitte ein IM -Client für langwierige diskussionen! No matter how I feel about that I have stopped caring so much about keeping up. I’ll get to know eventually and it’s a great way to keep track of some companies, products and persons I wouldn’t otherwise.

Facebook

I honestly just joined to be able to participate in the following competition : http://www.anp.se/newsletter/821693/414A584373474351467644455043. It’s pretty cool that they give away like €2,000 worth of tickets. I am dying to go talk to everyone and listen to some of the guys / girls I look up to but feel it’s a bit pricy to pay myself so wish me luck!

Tags:

Personal

How projections are done with NHibernates QueryOver

by Mikael Henriksson 13. August 2010 23:30

Some people are probably thinking “why the hell did they create a new api to query the database?”. The main reason for this is of course to make NHibernate less scary. You see, some people are afraid of “magic strings”. I am not very concerned about that but I do like the api for it’s readability and I’ll give a couple of examples though I won’t go over how do accomplish it with criteria or hql because I neither like nor master them and there is no way I am going to learn them either since I don’t have to.

First example projections:

CurrentSession.QueryOver<Employee>()
.Where(x => x.UserName == HttpContext.Current.User.Identity.Name)
.JoinQueryOver(x => x.Company)
.Select(x => x.Company.Id)
.SingleOrDefault<int>();

What I do here is to the following. I tell NHibernate to give me the employees with the matching username. Then join the query over Company (this is of course using the mapped relation) now select the companies id and return that single value as an integer.

The resulting query looks like below and gives me the desired value without having to load everything from both employee and company:

QueryOver_1

Tags:

NHibernate

DO Parse That Xml

by Mikael Henriksson 8. August 2010 21:53

This is a response to John Sonmez post “Don’t Parse That Xml”.

I am not going to say that John is wrong on the generation part, it’s a good tip but he seems to totally have forgotten about LINQ to XML. I have had to work with some API’s that don’t benefit from that type of  generated schema and classes because request / response can be different. Yes there is a schema for it but using that schema means adding god knows how many unneeded classes. For what reason should I then use this approach? Just to not have to parse the xml by hand? That’s like saying you should always use domain driven design even for displaying a simple table with some data in it on the web. What if all I need is that simple table with 4 columns? I would 10 times out of 10 drag and drop onto the designer window. Secondly I believe that all developers should get some hands on experience with reading/writing xml because it’s knowledge that will be of good use for many years to come.

But I am not just going to state my opinion I am going to give you some actual code.  I am not interested in hearing things like –”Dude, you are using magic strings”. If you don’t like strings move on. And if you want to know how I handle getting xml values etc have a look over at github

Let’s take the following as an example. I want to search for a person in a country in some external API and check if that person actually exist. The external API is really complex, it supports searching in most major countries and the API does some deciding for you based on the data you provide so it needs to be dynamic.

The service has one single method and it takes a xml-as-string. I have a schema but as I said previously but it contains a lot of overhead.

<request type="search">
    <country>SE</country>
    <names>
        <firstName>Mikael</firstName>
        <lastName>Henriksson</lastName
        <middleName>Kristofer</middleName>
    </names>
    <addresses>
        <address type="default">
            <streetName>Stallvägen</streetName>
            <streetNumber>48</streetNumber>
            <city>Växjö</city>
        </address>
    </addresses>
    <!-- Rest of request removed for brevity -->
</request>

I could take another aproach here and use LINQ to XML. What I want here is to take some internal object and map it to the Xml. There are a multitude of ways to do this but I’ll stick with the simplest one possible for the simple reason that yes I need to do some logic on the server side to map the classes but ensuring that everything goes ok is down to unit tests in my humble opinion. Coming up is an incredibly simple class called RequestBuilder in the serialization scenario I still need to transfer data to the objects before I can serialize them so I don’t see any gains really unless of course I  can use something like AutoMapper to transfer the data automatically. Here is the class:’

public class RequestBuilder
{
    readonly XDocument _doc = new XDocument();
    readonly User _user;

    public RequestBuilder(User user) {
        _user = user;
    }

    public XDocument BuildRequestDocument() {
    
        _doc.Add(BuildCountry(), 
            BuildPerson(), 
            BuildAddress());

        return _doc;
    }

    public XElement BuildAddress()
    {
        var addresses = new XElement("addresses");
        foreach (var address in _user.Addresses) {
            addresses.Add(new XElement("address",
                            new XAttribute("type", address.AddressType),
                            new XElement("streetName", address.StreetName),
                            new XElement("streetNumber", address.StreetNumber),
                            new XElement("city", address.City)));
        }

        return addresses;
    }

    public XElement BuildPerson() {
        return new XElement("person",
            new XElement("firstName", _user.FirstName),
            new XElement("middleName", _user.MiddleName),
            new XElement("lastName", _user.LastName));
    }

    public XElement BuildCountry() {
        return new XElement("country", ParseCountry());
    }

    private string ParseCountry() {
        var defaultAddress = 
            _user.Addresses.Single(x => 
                x.AddressType == AddressType.Default);
            
        switch (defaultAddress.Country) {
            case "Sverige":
                return "SE";
        }

        throw new NotImplementedException("Could not map the countries");
    }
}

Just to make sure we are on the same page before I continue I’d like you to fully understand the two classes address and user.

public class User
{
    public User() {
        Addresses = new List<Address>();
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public IEnumerable<Address> Addresses { get; private set; }
 }

public class Address
{
    public AddressType AddressType { get; set; }
    public string StreetName { get; set; }
    public string StreetNumber { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

 

Now I can easily test this with something like the following

[TestFixture]
public class SearchRequestBuilderTests
{
    [TestFixtureSetUp]
    public void FixtureSetUp()
    {
        InitUser();
        _builder = new RequestBuilder(_user);

    }
    [Test]
    public void Can_build_person()
    {
        var element = _builder.BuildPerson();
        Assert.That(
            element.Element("firstName").Value == "Mikael" &&
            element.Element("lastName").Value == "Henriksson" &&
            element.Element("middleName").Value == "Kristofer");
    }

    private void InitUser()
    {
        _user = new User
        {
            FirstName = "Mikael",
            LastName = "Henriksson",
            MiddleName = "Kristofer"
        };

        _user.Add(new Address
        {
            AddressType = AddressType.Default,
            City = "Växjö",
            Country = "Sverige",
            StreetName = "Stallvägen",
            StreetNumber = "48"
        });
    }
    static User _user;
    static RequestBuilder _builder;
}

 

Quick summary

I never said that John’s suggestion was a bad one. I just said that there is in my opinion a really good alternative if you don’t need all the classes that the schema generation would produce. I really like his post there are a lot of people that don’t know that this can be done from a single xml document. If you need the whole darn thing and the classes makes sense then use it! But if you only need a subset of the information or you find that the classes generated are just too complicated to be used then the above is a viable solution.

Tags: ,

C# | Xml

jQuery ate my values

by Mikael Henriksson 22. July 2010 20:33
I wanted to clear some textboxes when it gets focus so that the user does not have to clear the textbox before they enter whatever text. I came up with the following pretty quickly.
$('input[type=text]').focus(function () {    
    $(this).val('');
});

This worked like a charm!

I clicked a textbox and it got cleared, perfect right? Wrong! The problem here is that no matter how the textbox gets focus the box will be cleared. While tabbing through the form I cleared it completely and had to reload the entire page to get the values back. I thought of implementing some sort of ctrl+z to undo changes but realized I am better of not going down that road.

If it isn't broken…

UPDATE (2010-07-26): As suggested in the comments it’s actually a great idea to store the value locally and if the textbox is empty when the user leaves it we just add the original value back. This can be done like follows:

$(document).ready(function() {
        $('input[type=text]').bind('focusin', function(e) {
            tbData = $(this).val();
            $(this).val('')   
        });
        $('input[type=text]').bind('focusout', function(e) {
            if ($(this).val() == '') {
                $(this).val(tbData);
            }
        });
});

 

I’d like to shorten this a little but can’t get it working as expected. I’d probably want to get rid of the global variable for instance. Expect another update sometime soon.

UPDATE (2010-08-05): I found another way of solving the exact same problem which sort of makes more sense even though I can’t get rid of the global parameter.

$('input[type=text]').live('focusin focusout', function (evt) {
    if (evt.type == 'focusin') {
        tbData = $(this).val();
        $(this).val('');
    } else {
        if ($(this).val() == '') {
            $(this).val(tbData);
        }
    }
});

Tags:

jQuery

About the author

Life architect specialized in programming

Month List

Widget Twitter not found.

Root element is missing.X