Bootstrapping your new project using crane

Get the code

Visit us on github https://github.com/ewilde/crane

Or install the app

crane-5

But what does it do?

crane is a command line tool the I developed with Kevin Holditch. It kick starts development of a new project by templating the boring bits.

crane init ServiceStack.Plugin

Running this command creates the following items

  • Solution file
  • Project
  • Unit test project
    • Example test based on xbehave
  • VERSION.txt
  • Nuspec file for project
  • Build script
    • Downloads nuget.exe if missing
    • Performs nuget restore on solution
    • Builds solution in debug or release mode
    • Runs unit tests
    • Updates assembly info with correct version numbers
    • Packages project into nuget package
    • Publishes to nuget repository

In action

First initialize a new project using the syntax crane init {project name}
crane-1

It creates a directory using the the project name given in the init command
crane-2

You can immediately build the project. Just run .\build.ps1 from the project directory
crane-3

Here’s what it looks like in Visual Studio if you open the solution file:
crane-4

adb (android debug bridge) not showing device using Moto G and Android 4.3

I’ve been developing Android applications for awhile now. However not owning an actual device I’ve only ever used the emulator. Recently I shelled out for a Moto G and found it wasn’t obvious how I could get it hooked up to my mac.

This was a case of RTFM (http://developer.android.com/tools/device.html), step 2 eluded me until I stumbled across it on a stackoverflow post..:

To enable USB debugging:

1. Launch the settings application -> about

Image

2. Click build number 7 times

Screenshot_2013-12-28-18-23-19

3. Developer options should now be available from the main settings menu:

Screenshot_2013-12-28-18-23-15-2

4. Enable USB debugging

Screenshot_2013-12-28-18-27-41

Tagged , ,

How does Xamarin.IOS aka monotouch work?

Xamarin is a software development framework that allows developers to build applications for iOS and Android platforms using c# and the .Net framework. The SDK has separate requirements for developing iOS and Android application. The part of the SDK targeting iOS development is referred to as Xamarin.iOS or monotouch (the original name of the project)

Requirements for developing iOS applications using Xamarin.iOS
Apple Macintosh Computer Running OSX Lion or greater (10.7 >)
Apple Developer Program membership $99 per year, allows downloading of iOS SDK and publication of applications to the Apple app store
iOS SDK and Xcode Required during compilation, and optionally can be used to design graphical user interfaces using it’s inbuilt graphical designer
iOS Device Simulator Part of the SDK allows running of applications during the development process
Xamarin studio or Visual Studio Not strictly necessary, however does automate the build process
Knowledge of c# c# is the main language supported by Xamarin.iOS

Table 1 (Xamarin, Inc)

Mono is an open source implementation of the .NET Framework which can run across multiple operating systems, Windows, Linux and OSX. Mono is based on ECMA standards and is ABI (application binary interface) compatible with ECMA’s Common language infrastructure (CLI).

Xamarin.iOS compiles c# source code against a special subset of the mono framework. This cut down version of the mono framework includes additional libraries which allow access to iOS platform specific features. The Xamarin.iOS compiler, smsc, takes source code and compiles it into an intermediate language, ECMA CIL (common intermediate language), however it does not produce ECMA ABI compatible binaries unlike the normal mono compiler, gmcs or dmsc. This means any 3rd party .Net libraries you want to include in your application will need to be recompiled against the Xamarin.iOS subset of the mono framework using smsc.

Once a Xamarin.iOS application has been compiled into CIL it needs to be compiled again into native machine code that can run on an iOS device. This process is carried out by the SDK tool ‘mtouch’, the result of which is an application bundle that can be deployed to either the iOS simulator or an actual iOS device, such as an iPhone or iPad.

Diagram showing how monotouch aka xamarin.ios works?

Due to restrictions placed by Apple, the iOS kernel will not allow programs to generate code at runtime. This restriction has severe implications for software systems that run inside a virtual machine using just-in-time compilation. Just-in-time compilation takes the intermediate code, for example mono CIL and compiles it at runtime into machine code. This machine code is compatible for the device it is running on at the time of execution.

To work around this restriction the mtouch tool compiles the CIL ahead of time. A process that the mono team describe as AOT, ahead of time compilation. See: http://docs.xamarin.com/guides/ios/advanced_topics/limitations

Tagged , ,

.Net Interview Questions

General Questions

Explain what a process is?

In general a process consists of or ‘owns’ the following:

  • A program image to execute, in machine code (think exe on disk)
  • Memory, typically some block of virtual memory
    • Executable code
    • Data (input / output
    • Call stack
    • Heap, to hold intermediate data

General CLR Questions

1. Explain garbage collection in .Net?

Garbage collection will occur under one of the following conditions:

  • The system is running low on physical memory
  • The heap surpasses an acceptable threshold. (This threshold is continuously adjusted as the process runs)
  • GC.Collect is called

The managed heap

There is a managed heap for each managed process, the heap is initialized by the garbage collector. The garbage collector calls win32 VirtualAlloc to reserve memory and VirtualFree to release memory.

The heap is comprised of the large object heap (objects greater than 85k, normally only arrays) and the small object heap

Generations

The heap is split into generations to manage long-lived and short-lived objects. Garbage collection generally occurs with the reclamation of short-lived objects which normally account for a small portion of the heap

Generation 0: Contains short-lived objects, i.e. temporary variables. Collection occurs most here
Generation 1: Contains short-lived objects, is a buffer between 0 & 2 generations
Generation 2: Contains long-lived objects, i.e. static instances, stateful instances

Types of garbage collection

Workstation mode

More suitable for long-running desktop applications, adds support for concurrent garbage collection which should mean that the application is more responsive during a collection.

Server mode

Best suited for asp.net, only supported on multi-processor machines

References

MSDN: Garbage Collection

2. What is boxing / unboxing?

Boxing occurs when a value type is passed to a method which expects an object or a value type is implicitly cast to an object.

ArrayList x = new ArrayList();
x.Add(10); // Boxing
int x =  10;
Object y = x; // Boxing

Unboxing is the reverse of this process, taking an object and casting it back to the value type.

int x = 10;

Object y = x; // Boxing

x = (int) y; // Unboxing

Problem?

Yes there is a performance cost when an item is boxed a new item must be created and allocated on the heap, 20x as long as a simple reference assignment. 4x penalty for unboxing.

Now with generics some use cases for boxing/unboxing go away. However in silverlight/WPF value convertors and dependency objects can cause lots of boxing to occur

3. What is a struct, when should you use one?

A struct is a value type and should be choosen instead of class if:

  • It logically represents a single value
  • Has an instance size smaller than 16 bytes
  • It is immutable
  • It will not be boxed frequently

4. What are weak references, why do you need them?

Enables you to take out a reference to an object without stopping the garbage collector from reclaiming that object.

Useful if you have very large objects, which are easy to recreate.

5. What is the dispose pattern?

The dispose pattern is used only for objects that access unmanaged resources. The garbage collector is very efficient in reclaiming memory of managed objects but has no knowledge of memory used by unmanaged native objects.

6. What is the difference between a Dictionary<TKey, TValue> and Hashtable?

Dictionary<TKey, TValue> Hashtable
Minimizes boxing/unboxing boxes value types: Add(object,object)
Needs synchronization Provides some sychronization via Hashtable.Synchronized(Hashtable) method
Newer >.net 2.0 Older Since 1.0
If key not found throws KeyNotFoundException If key not found returns null

Note that internally dictionary is implemented as a hashtable.

7. What is the cost of looking up an item in a Hashtable?

Retrieving the value of a dictionary or hashtable using it’s key is very fast close to O(1) in big-o notation. The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey

Multi-threading Questions

1. How would you engineer a deadlock

  • Create two methods each acquiring a separate lock, that call each other say 5 times
  • Start two threads on separate methods
class Program
{
    private static int operations = 5;

    public static object lockA = new object();
    public static object lockB = new object();

    static void Main(string[] args)
    {
        Thread thread1 = new Thread(DoSomethingA);
        Thread thread2 = new Thread(DoSomethingB);

        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();
        Console.WriteLine(operations);
        Console.ReadKey();
    }

    public static void DoSomethingA()
    {
        lock (lockA)
        {
            Console.WriteLine("Lock DoSomething A " + Thread.CurrentThread.ManagedThreadId);
            if (operations > 0)
            {
                operations = operations - 1;
                Thread.Sleep(100);
                DoSomethingB();
            }
        }

        Console.WriteLine("Release DoSomething A " + Thread.CurrentThread.ManagedThreadId);
    }

    public static void DoSomethingB()
    {

        lock (lockB)
        {
            Console.WriteLine("Lock DoSomething B " + Thread.CurrentThread.ManagedThreadId);
            if (operations > 0)
            {
                operations = operations - 1;
                Thread.Sleep(100);
                DoSomethingA();                    
            }
        }

        Console.WriteLine("Release DoSomething B " + Thread.CurrentThread.ManagedThreadId);
    }
}

2. What are race conditions, how to stop them

Occur when more than one thread attempts to update shared data:

int x = 10;

…..

// Thread 1

x = x – 10;

// Thread 2

x = x + 1

To stop race conditions from happening you need to obtain exclusive locks, use semaphor, mutex, readwriterslim lock mechanism

3. What are some lock-less techniques for avoiding race conditions?

You can use volatile or Thread.MemoryBarrier() or the Interlocked class

4. What is does the keyword Volatile mean or do?

It ensures that the value of the field is always the most up-to-date value. Commonly used in multi-threaded applications that do not use locks to serialize access to shared data. When using a lock it causes the most up-to-date value to be retrieved.

Values can become stale when threads run on different processors asynchronously.

5. What is differenct between ManualResetEvents and AutoResetEvents?

When signaled via ‘Set’ threads waiting can all proceed until Reset() is called. With auto reset event only one waiting thread is unblocked when signalled ‘Set’ and the wait handle goes back to blocking other waiting threads until the next ‘Set’ message is sent.

Reactive Extensions (RX)

1. What are the IObservable<T> and IObserver<T> interfaces

IObservable<T> is a collection of things that can watched and defines a provider for push-based notification. And must implement a subscribe method.

IObserver<T> is essentially the listener to the collection and needs to implement OnNext, OnError, OnCompleted

Collections

1. What is the difference between IEnumerable<T> and IEnumerator<T>

IEnumerable<T> is a thing which can be enumerated over. Returns an IEnumerator

IEnumberator<T> is the thing that can do the enumeration, knows how to navigate the collection

Software design

1. List some design patterns

Creational patterns

Abstract factory

Provide an interface for creating families of related or dependent objects without specifying their concrete classes

http://en.wikipedia.org/wiki/Abstract_factory_pattern

Builder Pattern

Defines abstract interfaces and concrete classes for building complex objects

http://en.wikipedia.org/wiki/Builder_pattern

Singleton Pattern

Ensure a class only has one instance, and to provide a global point to access it.

Structural Patterns

Façade Pattern

A facade is an object that provides a simplified interface to a larger body of code

Pasted from <http://en.wikipedia.org/wiki/Facade_pattern>

Decorator

Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.

Pasted from <http://en.wikipedia.org/wiki/Design_pattern_(computer_science)>

2. What is SOLID?

Initial

Stands for(acronym) Concept
S SRP
Single responsibility principle
an object should have only a single responsibility.
O OCP
Open/closed principle
“software entities … should be open for extension, but closed for modification”.
L LSP
Liskov substitution principle
“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”. See also design by contract.
I ISP
Interface segregation principle
“many client specific interfaces are better than one general purpose interface.”[5]
D DIP
Dependency inversion principle
one should “Depend upon Abstractions. Do not depend upon concretions.”[5]Dependency injection is one method of following this principle.
Tagged ,

Running nuget on mono

Well the documentation states that the nuget command-line tool does indeed work with mono

Does NuGet support Mono?

The command-line application (nuget.exe) builds and runs under Mono and allows you to create packages in Mono.

So I merrily install nuget to my home directory ~/. Run the command mono ~/nuget and get the error message:

Problem

WARNING: The runtime version supported by this application is unavailable.
Using default runtime: v2.0.50727

Screen Shot 2012-05-06 at 11.04.32

Solution

Turns out the simple solution is to specify the absolute .net version:

mono –runtime=v4.0.30319 NuGet.exe

 and voila!

Screen Shot 2012-05-06 at 11.11.57

Tagged ,

Setting up a new project, from scratch on a blank machine as of 2012/02

  • Install loads of crap useful applications

Chocolatey packages

cinst 7zip

cinst console2

cinst ilspy

cinst kdiff3

cinst gitextensions

cinst resharper

cinst nuget.commandline

cinst machine.specifications.tools

Configure git

http://stackoverflow.com/questions/2143956/gitignore-for-visual-studio-projects-and-solutions

Install stuff not yet on Chocolatey

image

image

Orchard CMS blogging with an iPhone

I’ve recently been evaluating the Orchard CMS project for an upcoming website I’m building for my award winning London diving club Smile . I thought it would be really useful to be able to blog to the website straight after a days diving whilst the excitement and pictures were still fresh off the press.

 

Step 1: Create your Orchard blog if it doesn’t exist already

 

Step 2: Turn on remote blog publishing

image

 

Step 3: Retrieve your blog id

Ochard’s remote blogging interface implements the MetaWeblog API. Whilst some clients such as windows live writer support self discovery using the real simple discovery mechanism. Your blog id is required by some iphone clients

 

Simple navigate to the following url: http://[path_to_your_blog]/rsd for my local development orchard install that was: http://localhost:30320/OrchardLocal/blog/rsd

image

Take a note of the blog id which in this case was 24

 

Step 4: Configure your iphone app

I was very surprised to find out how few generic iPhone blogging clients there are.  Whilst investigating this task I paid for and tried two apps:

  1. BlogPress – (very buggy, does not seem to work with Ochard)
  2. BloggerPlus – Does work!

Step 5: Configuring blogger plus to work with orchard

photo

Step 6: Patching Orchard is required if v.1.3.10 or <

As of today 07/02/2012 my patch has not made it to the main Orchard code base, so if you are running Orchard v.1.3.10 or < you need to download this change set http://orchard.codeplex.com/SourceControl/network/Forks/ewilde/18414/changeset/changes/1bda35a0f8f8 and rebuild orchard

Tagged , , ,

What is the current state of REST frameworks in .Net 4.0

WCF WebHttp Services in .NET 4

Part of the official .Net 4.0 framework release.

WCF WebHttp Services is the flavor of WCF that is most appropriate for developers who need complete control over the URI, format, and protocol when building non-SOAP HTTP services— services that may or may not subscribe to RESTful architectural constraints.

Documentation

http://msdn.microsoft.com/en-us/library/bb412169.aspx

Example

Introducing WCF WebHttp Services in .NET 4: http://blogs.msdn.com/b/endpoint/archive/2010/01/06/introducing-wcf-webhttp-services-in-net-4.aspx

WCF WebApi

This project focuses on allowing developers to expose their apis for programmatic access over HTTP by browsers and devices.

Essentially this is a continuation of work done on the WCF Rest starter kit, and could be considered as a preview of wcf http services for .net 5.0?

WCF REST Starter Kit (depreciated)

The new WCF Web Api’s recently announced at PDC replace the REST Starter Kit and provide significant enhancements including better access to HTTP, more flexibility with representations and support for jQuery. Please go to http://wcf.codeplex.com/ for more information.

Source: http://aspnet.codeplex.com/wikipage?title=WCF%20REST&ProjectName=aspnet

Open Rasta

OpenRasta is a development framework targeting the Microsoft .NET platform for building web-based applications and services, and distributed under an Open-Source MIT License.

By focusing development around resources and HTTP methods, OpenRasta simplifies the creation of ReST-friendly interfaces.

Example

How to create a rest service using Open Rasta: http://blogs.7digital.com/dev/2011/02/02/rest-in-practice-and-openrasta/

RestSharp

http://restsharp.org/ A client only api for consuming rest services

RestSharp is a simple, open source REST client for .NET designed primarily for consuming third-party HTTP APIs. RestSharp is NOT:

  • A REST server framework
  • A SOAP client
Tagged , ,

SQL Server Express 2008 R2 – Installing on Windows 7 with Visual Studio 2010

Today I was trying to install the latest management tools for SQL Server using SQL Server Express 2008 R2 on a Windows 7 machine with Visual Studio 2010 running the setup up file I got the follow error message:

System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for userSettings/Microsoft.SqlServer.Configuration.LandingPage.Properties.Settings: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.

Solution: surprisingly easy just press Continue!

Tagged

How to add custom validators to the SharePoint ListFieldIterator

Requirements

Today I had the requirement to add custom validation logic to a SharePoint edit form. The edit form is being displayed using a ListFieldIterator. The requirement was to make sure the Date field could not be set to a date in the past.

The solution (Other solutions are available and are most probably better!) I came up with involved subclassing ListFieldIterator and attaching ASP.NET validators at run-time.

Challenge 1

How do you attach a ASP.NET validation control at run-time.

  • Attach the validator at the correct stage of the page/control life-cycle. In the case of the ListFieldIterator I wanted to attach it after the control had build it’s control tree. Override CreateChildControls, call base, then attach.
  • Find the FormField associated with the SharePoint field (SPField) you want to validate.I have an extension method that I use to parse the control hierarchy of a ListFieldIterator as follows:

Usage:

FormField formField = listFieldIterator.GetFormField("MyInternalFieldName");

public static class ListFieldIteratorExtensions
{
    public static FormField GetFormField(this ListFieldIterator listFieldIterator, string fieldName)
    {
        return GetFormField(listFieldIterator, GetFormFields(listFieldIterator), fieldName);
    }


    public static FormField GetFormField(this ListFieldIterator listFieldIterator, List<FormField> formFields, string fieldName)
    {
        FormField formField = (from form in formFields
                               where form.FieldName.Equals(fieldName, StringComparison.InvariantCultureIgnoreCase)
                               select form).FirstOrDefault();

        if (formField == null)
        {
            throw new GeneralApplicationException("Could not find form field: " + fieldName);
        }

        return formField;
    }

    public static List<FormField> GetFormFields(this ListFieldIterator listFieldIterator)
    {
        if (listFieldIterator == null)
        {
            return null;
        }

        return FindFieldFormControls(listFieldIterator);
    }        

    private static List<FormField> FindFieldFormControls(System.Web.UI.Control root)
    {
        List<FormField> baseFieldControls = new List<FormField>();

        foreach (System.Web.UI.Control control in root.Controls)
        {
            if (control is FormField && control.Visible)
            {
                FormField formField = control as FormField;
                if (formField.Field.FieldValueType == typeof(DateTime))
                {
                    HandleDateField(formField);
                }

                baseFieldControls.Add(formField);
            }
            else
            {
                baseFieldControls.AddRange(FindFieldFormControls(control));
            }
        }

        return baseFieldControls;
    }

    private static void HandleDateField(FormField formField)
    {
        if (formField.ControlMode == SPControlMode.Display)
        {
            return;
        }

        Control dateFieldControl = formField.Controls[0];
        if (dateFieldControl.Controls.Count > 0)
        {
            DateTimeControl dateTimeControl = (DateTimeControl) dateFieldControl.Controls[0].Controls[1];
            TextBox dateTimeTextBox = dateTimeControl.Controls[0] as TextBox;
            if (dateTimeTextBox != null)
            {
                if (!string.IsNullOrEmpty(dateTimeTextBox.Text))
                {
                    formField.Value = DateTime.Parse(dateTimeTextBox.Text, CultureInfo.CurrentCulture);
                }
            } 
        }
    }
}
  • Find the Control that is rendered by the FieldControl.Field.FieldRenderingControl. In my specific case a DateTimeField will render a DateTimeControl. Now that we have the form field we grab the rendering control:

Usage:

Control renderedControl = GetControl(formField);

private static Control GetControl(FieldMetadata formField)
{
    return formField.FindControlRecursive(x => x.GetType() == GetChildControlBasedOnFieldType(formField.Field.FieldRenderingControl));
}

private static Type GetChildControlBasedOnFieldType(object field)
{
    if (field is TextField)
    {
        return typeof(TextBox);
    }

    if (field is DropDownChoiceField)
    {
        return typeof(DropDownList);
    }

    if (field is DateTimeField)
    {
        return typeof (DateTimeControl);
    }

    return null;
}

public static Control FindControlRecursive(this Control control, Func<Control, bool> evaluate)
{
    if (evaluate.Invoke(control))
    {
        return control;
    }

    foreach (Control childControl in control.Controls)
    {
        Control foundControl = FindControlRecursive(childControl, evaluate);
        if (foundControl != null)
        {
            return foundControl;
        }
    }

    return null;
} 

  • Now we have found the control we want to validate, we can add the ASP.NET to it’s parent’s control collection

renderedControl.Parent.Controls.AddAfter(control, validator as Control);

Uses another little extension method:

public static void AddAfter(this ControlCollection collection, Control after, Control control)
{
    int indexFound = -1;
    int currentIndex = 0;
    foreach (Control controlToEvaluate in collection)
    {
        if (controlToEvaluate == after)
        {
            indexFound = currentIndex;
            break;
        }

        currentIndex = currentIndex + 1;
    }

    if (indexFound == -1)
    {
        throw new ArgumentOutOfRangeException("control", "Control not found");
    }

    collection.AddAt(indexFound + 1, control);
}

Tagged ,
Follow

Get every new post delivered to your Inbox.