Saturday, February 9, 2013

HTML productivity booster: zen-coding

Over the last week I've written an API for my business and needed to created some documentation for it. Using Twitter bootrap, some of it looks like this:

Which looks like this in HTML:
subscription_startdate
Startdate of the subscription
subscription_enddate
Enddate of the subscription ( nullable )
subscription_typeid
Type ID of the subscription
subscription_type
Subscription type. Typically 'Business' or 'Compleet'
profile_id
The Business Compleet User ID
profile_initials
Profile initials
...
Which is formatted by Twitter Bootstrap. What I did was copy-paste a bunch of
and filled those out. What I should have done was get a zen-coding plugin for my environment ( NetBeans at the time, but it's also available for Visual Studio and Sublime text ) and use that. Zen-coding allows you to quickly generate HTML in your favorite IDE. With the plugin installed in Sublime, I type:
dl.dl-horizontal>(dt+dd)*5
Hit TAB and it results in:
BOOM! Done.

So you start out by defining you element type ('dl' in my case). The '.horizonal' sets the class very intuitively ( for id - use '#' ... obviously ). The '>' denotes the child elements. The I want a 'dt' with a 'dd' sibling - hence the '+', and that 5 times.


Monday, February 4, 2013

Using Ninject to inject session variables into controller properties

According to our JAVA developer, JAVA spring can inject session variables into controller properties. So - I was triggered to see if I could hack something together that resembles this behavior in C#, using Ninject. So here's a quick thing that I put together:
    internal class StandardKernelWithSessionResolution : StandardKernel
    {
        public override IEnumerable Resolve(Ninject.Activation.IRequest request)
        {
            if (request.Target != null && HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session[request.Target.Name] != null)
            {
                Log.Debug("Property {0} is being injected from session", request.Target.Name);
                return new List() { HttpContext.Current.Session[request.Target.Name] };
            }
            return base.Resolve(request);
        }
    }
In your MVC application, you will need to use StandardKernelWithSessionResolution() as opposed to the StandardKernel() call. Also, you will need to instantiate the session variable once, but after that you're good:
    public class HomeController : Controller
    {
        [Inject]
        public Person SessionInjectedPerson { get; set; }

        public ActionResult Index()
        {
            this.SessionInjectedPerson = new Person();
            return View(this.SessionInjectedPerson);
        }

        public ActionResult UpdatePerson()
        {
            this.SessionInjectedPerson.Name = this.SessionInjectedPerson.Name + " > ";
            return this.View("Index",this.SessionInjectedPerson);
        }
It's not very well tested and you it works on the fact that the session entry name is the same as the property, however - it might save you some time.

Sunday, February 3, 2013

Zero implementation PHP API Wrapper in C#

The MoneyMedic API wrapper NuGet package that I wrote in December doesn't actually implement the methods of the API. All the methods actually look something like this:

    internal class MoneyMedicAPI : IMoneyMedicApi
    {
        ...
        public get_invoices_response get_invoices(string api_key, 
                                                  MoneyMedicEnum.SortInvoicesBy sortby, 
                                                  MoneyMedicEnum.SortDir sortdir)
        {
            throw new NotImplementedException();
        }
    }

When figuring out how to implement the wrapper I obseved:

  • All API calls result in a URL call with a query string that holds the method parameters and values. Like https://www.moneymedic.eu/api/[METHOD_NAME/?[PARAMETER_NAME]=[PARAMETER_VALUE]&....etc....
  • The JSON or XML response will need to be parsed into an instance of some response class


Therefore I decided to use the following setup:

  • A method call on the IMoneyMedicAPI interface is being intercepted
  • The intercepted method name matches the actual method name, the parameter names match the actual parameter names ( although StyleCop doesn't like this too much ).
  • The interceptor creates the MoneyMedic URL from intercepted method name + creates the query string from the parameter names and their corresponding values.
  • Using JSON.NET, the result is parsed to a result object, that corresponds to the information in the documentation and returns this to the caller.


And thus the actual implementation is never used or called - hence the NotImplementedExceptions that will never be thrown

Here's the interceptor:
// -------------------------------------------------------------------------------
// 
//   2012 Jochen van Wylick
// 
// -------------------------------------------------------------------------------

namespace MoneyMedicAPI
{
    using Ninject.Extensions.Interception;

    /// 
    /// The money medic API interceptor.
    /// Intercepts calls to the MoneyMedicAPI.
    /// 
    public class MoneyMedicApiInterceptor : IInterceptor
    {
        #region IMethodInterceptor Members

        /// 
        /// The MoneyMedic interceptor.
        /// 
        /// 
        /// The invocation.
        /// 
        public void Intercept(IInvocation invocation)
        {
            // Get the parameter collection
            var parameters = invocation.Request.Method.GetParameters();

            // Get the argument collection
            var arguments = invocation.Request.Arguments;

            // Invoke the API call and return the value
            invocation.ReturnValue = MoneyMedicApiHelper.InvokeApiCall(
                invocation.Request.Method.Name, parameters, arguments, invocation.Request.Method.ReturnType);
        }

        #endregion
    }
}

This made the wrapper very easy to implement. Furthermore I could use it for other wrappers if I wanted but still provide IntelliSense to the caller.

Thursday, January 24, 2013

Filling out PDF forms with iTextSharp

We're looking into ways to help SME's fill out our Dutch Chamber of Commerce forms. These are typically PDF forms and we want to help them out with filling out the form with as much info as possible, to save them the trouble. iTextSharp makes this a breeze ( NuGet site ):
            // Fill out PDF
            PdfReader.unethicalreading = true;          
            var inputFile = new PdfReader("Templates/bv_form.pdf");
            var outputStream = new FileStream("Exports/export.pdf", FileMode.Create, FileAccess.Write);           
            var pdfStamper = new PdfStamper(inputFile, outputStream);

            // Display form field names found in document
            foreach (var field in pdfStamper.AcroFields.Fields)
            {               
                var line = string.Format("[{0}]", field.Key);    
                Console.WriteLine(line);           
            }           

            pdfStamper.AcroFields.SetField("1.1", "This value is set by C#");
            pdfStamper.AcroFields.SetField("1.12", "12-12-2012");
            pdfStamper.AcroFields.SetField("3.8", "This value is set by C#");
            pdfStamper.AcroFields.SetField("2.11", "This value is set by C#");
            
     // close writers and clean up
            inputFile.Close();
            pdfStamper.Close();     
            outputStream.Close();
If an 'owner password' is set on the PDF, you need to set the 'unethicalreading' property to true. There are tools to remove the password from the file, but most also remove the form-fields. Setting checkboxes is a bit tricky - you need to use SetField() and provide the value of the checked box. This is typically "On" or "Off", but in the forms we were using, they used custom values. I found these values by checking the forms, saving the forms and then finding the field values in code. Anyways - good stuff, easy to use, check it out!

Saturday, January 19, 2013

JavaScript unit testing using QUnit

In one of the recent hanselminutes, Scott talks to one of the creators of SignalR, a real-time web library ( this episode ). Two things I found really interesting in this talk:

Microsoft allowed the creators to work on their 'garage project' using company resources

SignalR started out as a garage project from two guys at Microsoft, working on it in their own timem. However, after talking to their employer, the project was adopted by Microsoft and now they have a team of 6 or so, helping them on the project. Basically, now their working on their pet project in the boss's time.

SignalR is using Git, TeamCity, BrowserStack, TestSwarm and QUnit

During the podcast, their Continuouse Integration (CI) setup is mentioned. So apparently they use 
  • Git for source control
  • TeamCity for automated building and deployments - find it here: http://ci.signalr.net/
  • Testswarm for coordinating the JavaScript tests
  • QUnit for writing JavaScript unit tests
  • Browserstack for running the tests on all the different browser versions
Pretty cool setup there. Apparently their TeamCity server creates jobs for the Testswarm installation, to run the tests.
But, what I wanted to look into was QUnit for now, so I wrote a few lines to see how this thing works.

QUnit - A JavaScript unit testing framework

Honestly, I haven't tested much of my JavaScript code thusfar. However, There's no reason not to anymore, because QUnit makes it extremely simple.



You don't need to download anything, just get both style and JavaScript files from a CDN. A 'hello world' is quickly written like so:





  
  QUnit Example
  


  
Which will result in the following tests results:


There's no need to talk about this much longer. It works out-of-the box, no prerequisites and very helpful. We'll be using it!

Wednesday, January 16, 2013

Great tool: YUMI – Multiboot USB Creator (Windows)

I'm experimenting with VMWare ESXI and I needed to create a bootable USB stick for in order to get this onto one of our servers. My colleague pointed out this application: YUMI. Not only allows it to quickly create a bootable USB stick, but it also allows you to quickly download and place Linux distributions onto the USB stick.
On boot - a menu shows that allows you to select the ISO that will be used to boot. Sweet, quick and easy.




Monday, January 14, 2013

Scott Hanselmann and Rob Conery on Mid-life crisis

The latest 'hanselminutes' podcast by Scott Hanselman and Rob Conery talks about .... ehm ... well ... life. No techy stuff this time and I love it. I can sum up what it's about, but I recommend you just check it out:
http://www.hanselminutes.com/353/coneryminutes-2-the-mid-life-crisis