woensdag 4 juli 2012

Stateless service

Taken from the BelFirst service specifications:

3. General Principles

3.1 Stateless service

While using the web service a state is maintained on the server. This allows the interface to use more atomic operation and hence richer functionality. Using the web service is done with a short session consisting of different calls$

Good job guys... /s
.

dinsdag 1 mei 2012

Convert any text to a string literal



The last couple of months I found myself trying to convert pieces of code or html to a string allot.  Some of the stuff I was trying to do includes:
All of the above required me to convert text with allot of quotes and abnormal characters into a string.  I searched the internet for some conversion site that would do this for me but couldn’t find one.  The only option that I had left was to write one of my own.

So if you are ever in the need to convert some pesky piece of text to a string and you’re not masochistic enough to do it manually, then be free to go to http://texttostringliteral.lucbos.net/ and this utility website will do it for you :-)

Till next time!

Small note: I’ve noticed the site takes a couple of seconds to load when my host recycled it.

vrijdag 27 april 2012

Removing a stuck sim in the Samsung Omnia 7


After attending the call for projects for windows phone 7 I got a lumia 800 from David Henry for submitting three apps in the marketplace.  It took me a while to switch phones but yesterday I finally got to it.  So then I would do what you’re supposed to do when switching phones, switch your sim card from one phone to the other.  That didn’t seem to go well and my sim card broke in half while trying to get it out of the Omnia 7.  Luckily for me it was just the adapter for the micro sim that broke of so the actual sim card could still be used.

I then tried to use some tweezers to get the sim card out but that didn’t seem to do any good. My last option then was getting the metal casing off, which surprisingly wasn’t that hard to do.

The first thing you’ve got to do is go to your usb charger port on the top of your phone and use a needle or screwdriver to get the top off.



When that’s done you’ll see 3 screws, unscrew them.  When the screws are out you can take the top lit off and slide the metal casing of your Omnia 7.



It’s that easy :-)  I didn’t see any warranty stickers or anything that can indicate loss of warranty so I think you’ll be safe on that part.  Removing the metal casing also doesn’t expose any of the electronics inside so there isn’t any risk of damaging anything.

Next posts I’ll try to cover some bits and pieces of the lumia 800.  Until next time ;-)

maandag 23 april 2012

Clean windows 8 metro project



Last week I attended a Windows 8 session at MIC.  While everyone was working on the labs I was trying to set up my project structure for my own metro project.  When I created a new Windows 8 metro project it struck me that the project template is just a PIA to start a new project with. 

The project starts up with a whole lot of redundant imports of namespaces and you get a free “default viewmodel” of which I can see no real world usage.  And the best thing of all is that all the item templates hook into this horrible standard project template by providing test data which plugs into this default viewmodel…

I’ve cleaned up the standard project template by releasing resharper on it and doing a code cleanup.  The default viewmodel has also been removed… I don’t think anyone will feel a big loss there.  You can download the new windows 8 project template here.

To be able to use that project template you have to place it in your project templates folder.  You can find this folder by going into the options menu in Visual Studio. Under the ‘General’ settings located under ‘Project and Solutions’  you can find the ‘User project templates location’ setting.



A small caution is that most of the default item templates won't build when the default viewmodel is removed but I consider this a good thing as you’ll probably don’t want that code anyway ;-)


dinsdag 3 april 2012

CSharpCodeProvider + MEF = Match made in heaven

Okay so the following post probably has zero business value (like some other posts do) but I quit enjoyed myself working on it.   What I wanted to try out was make a system that would be extensible by code the user provides… at runtime … in a console application.  So I started fiddling around with the CSharpCodeProvider and was quite impressed by how easy to use it was!
 
So what the CSharpCodeProvider allows you to do is compile code at runtime.  Not something the everyday developer has to do but very fun for hobby projects :-)  So I then thought it would be cool if I could load in that code at runtime and saw the behavior of my code change while I was running it!

Shinny diagram…oooooh

Off course loading code at runtime is a breeze with MEF, so the only thing I had to do is tell MEF in which directory to load up the assemblies.  Just for the sake of putting pretty diagrams on my blog, here is one explaining what I’m trying to do:



Implentation explanation

The idea I came up with was a simple application that responds to the user based on previous expressions that were provided.  Seems pretty abstracting saying it like that so I’ll show you some screenshots to make it more obvious:

So when the user logs in he can either insert a new expression or let the program evaluate userinput.



When the user chooses to Insert an expression he has to provide a lambda statement of the type func<string,bool>.  This statement will later on be used to evaluate user input. 

Then he is supposed to input an answer that the application will provide when the statement returns true.



The application will then inject the lambda and the answer into some source code and compile it to a new assembly.

If we then choose to evaluate user input the application will load all at runtime compiled assemblies and use them to evaluate the users input.




The user can then choose to provide as much expressions and answers as he likes and change the behavior of how the system will respond to certain user input. 

Now the geek part begins… code!

So when the application asks for the expression and answer it will inline the requested input in the following string:

private string CreateSourceCode(string lambda, string answer)
        {
            return
    @"using System;
    using System.ComponentModel.Composition;
    using TestCompilation;
    [Export(typeof(IExpression))]
    class NewExpression : IExpression
    {
        public Func<string, bool> Expression
        {
            get
            {
                return " + lambda + @"
            }
        }

        public string Answer
        {
            get
            {
                return " +
    "\"" + answer + "\"" + @";
            }
        }
    }";
        }

Essentially the user input in combination with the string should provide a valid class in source code.  Maybe you’ve noticed the Export attribute on top of the class?  This is where MEF comes in.  When this source code is compiled we will use MEF to load the compiled assembly at runtime and inject it in our code.  The IExpression interface is just a simple interface with the two properties in it.

But how do we compile this at runtime?  We use the CSharpCodeProvider:

 var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var csc = new CSharpCodeProvider(new Dictionary<stringstring>() { { "CompilerVersion""v4.0" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll""System.Core.dll""System.ComponentModel.Composition.dll""ConsumerContracts.dll" },
                                                    location + "\\Extensions\\" + Path.GetRandomFileName() + ".dll",
                                                    true);
 
            CompilerResults results = csc.CompileAssemblyFromSource(parameters, sourceCode);

In the CompilerParameters we have to tell the CSharpCodeProvider which assemblies to use to be able to build our class.  If we leave these out it will return the TypeNotFound exception.

The result of the CompileAssemblyFromSource method will be a dll file located in the Extensions folder of my running assembly.
 
So the next step is to load in the assemblies located in the Extensions folder:
 
private void LoadExtensions()
{
    var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    var catalog = new DirectoryCatalog(location + "\\Extensions\\");
    var container = new CompositionContainer(catalog);
    var batch = new CompositionBatch();
    batch.AddPart(this);
    container.Compose(batch);
}

All classes that implement IExtension will then be injected into the following member.

[ImportMany(typeof(IExpression))]
public ICollection<IExpression> Expressions = new List<IExpression>();

The only thing we need to do now is evaluate the users input against the loaded expressions.

private void EvaluateExpression()
{
    Console.WriteLine("Please say something and I will try to answer.");
    var userInput = Console.ReadLine();
    var matchingExpression = Expressions.FirstOrDefault(e => e.Expression(userInput));
    if (matchingExpression == null)
    {
        Console.WriteLine("Could not answer you.");
    }
    else
    {
        Console.WriteLine(matchingExpression.Answer);
    }
    Console.ReadKey();
    Console.Clear();
}


90% of readers won’t read this part

I probably lost 90% of you by now and my feedburner statistics will be dropping to an all-time low but, for the few diehard people that are interested in the full source code, you can find it on github.  Be aware that this was created in an hour or so, so don’t expect the source code to be all that.

Have fun!

zondag 11 maart 2012

Calling a stored procedure with Entity Framework Code First


Currently I’m doing a project that uses Entity Framework Code First for data access.  Though I’m not 100% convinced that this technology is mature enough, a coworker of mine recommended it.  For the read side of our project we want flattened dto’s that are made to fit our view’s need.  Since some of the views were a bit too complex to write with linq to entities we thought it would be best to write stored procedures for them.

The problem here is that Entity Framework Code First does not support Stored Procedures out of the box.  Well… it actually does, but in such a way that it is indistinguishable from plain ADO.NET.  Yet I wanted a more type safe solution.  I’m still not sure if this is the best solution for this problem but I thought I would share the code with you.

Imagine we have a stored procedure:

DECLARE @Iets int
DECLARE @NogIets bit

SET @Iets = 5
SET @NogIets = 1

EXECUTE [dbo].[sp_TestProcedure]
   @Iets
  ,@NogIets
GO

The standard way of calling the stored procedure in EF Code First would be something like this:

var ietsParameter = new SqlParameter("@Iets",5);
var nogIetsParameter = new SqlParameter("@NogIets",true);
DbContext.Database.SqlQuery<ProcedureResult>("sp_TestProcedure @Iets @Nogiets", ietsParameter, nogIetsParameter);

After creating the database extension you can write a more typesafe solution:

var testProcedureStoredProcedure = new TestProcedureStoredProcedure() { Iets = 5, NogIets = true };
var result = DbContext.Database.ExecuteStoredProcedure(testProcedureStoredProcedure);

The typed stored procedure looks like the following:

public class TestProcedureStoredProcedure : IStoredProcedure<ProcedureResult>
{
    public int Iets { getset; }
    public bool NogIets { getset; }
}

Notice that you have to inherit from a generic IStoredProcedure and supply the type of the result of the stored procedure.  The stored procedure class contains properties that are used as the parameters for the execution of the stored procedure.  The extension will use the name of the class to determine which stored procedure to execute.  The default behavior is ‘sp_’+classname but you can edit the source to your own naming convention.

You can download the database extension class here, or get it from github.  Just add a reference to the project and import the namespace to start using the extension method.

There is a drawback however.  The execution time is slower because before it can call the query it has to reflect the properties of the stored procedure class.  It’s still a work in progress but it can be undoubtedly be executed faster by adding some kind of cache for the stored procedure names into it.  If you have any improvements then I would be happy to hear about them!

A small note: if you have any questions about my blog posts or if there are any links broken then please add a comment to the blog post in question.  Mails often get lost in my mailbox and it can take a couple of weeks before I can answer them.



I've created a new extensions project for Entity Framework Code First.  You can read all about it here!

woensdag 22 februari 2012

Three Windows Phone Apps in a day


A couple of months ago I followed a course on windows phone 7 development.  After attending the course, we were told that we could get a free phone if we developed 3 WP7 apps by the end of February. Me being myself, I of course waited until the middle of February to start developing these apps. 

Then I started to come up with 3 apps that I could build in a day (to be honest it took me 5 hours).  So I came up with the following.

A Fart application: I think everyone knows what this app does.  You shake your phone and farting noises will come out of your speakers.

A grenade app: This one took me the longest because I had to photoshop a grenade so I could flip the pin and move the handle.  It basically turns your phone into a grenade.

A card deck app:  Just a simple application that shows you a deck of card where you can pick one card at a time.

I was a bit scared of the certification process at first but it wasn’t that much of a hassle as I thought it would be.  The submission itself took a small 15 minutes because you need to upload some Icons for your application and a proper screenshot.  The screenshot must be taken in the emulator and of a certain size and format, this is what rejected my fart application the first time.  A colleague of mine also told me that his app got rejected because the NeutralResourceLanguage attribute in de AssemblyInfo.cs wasn’t set properly.  I deployed my app worldwide so I had to set it to:
[assemblyNeutralResourcesLanguage("en"UltimateResourceFallbackLocation.Satellite)] 

It basically tells the marketplace which language your app supports.  The attribute is taken into account in the certification process since the mango release.

Something that struck me when trying to certify my apps is how buggy the apphub site is.   The loading time to view an application is very long and when trying to edit my application details I had to switch to chrome because in Firefox and IE the page just wouldn’t load!

To sum it up, I was pleasantly surprised when I found out my apps got certified.  Hopefully they show up in the marketplace soon so I can collect my new windows phone.  I’ll post an update when the app is available for download.

I’ve been busy moving into a new home the last couple of weeks so that’s why you’ve might have noticed it’s been a bit quiet here.  Don’t fear, I have a couple of interesting blog posts coming up so stay tuned! ;-)