Release of Botox v1.2

Release of Botox v1.2, a lightweight dependency injection framework for portable class libraries.

New overload for CreateInstanceOf. You can now return interface generic type given an implemented parameter type.

public ISomeInterface CreateSomeType(Type theType)
{
    return Botox.CreateInstanceOf<ISomeInterface>(theType);
}

Check out the code on github if you want more insight to how it works.

Link to botox at Nuget: https://nuget.org/packages/Botox/
(
Or search for Botox)

Project home page at GitHub: https://github.com/projecteon/Botox

Release of Constant

Now announcing the release of Constant, a component that enables developers to create smart enums in C# and is implemented using .NET portable class libraries.

Creating constants:

private class Producttype : Constant<Producttype>
{
    [DefaultKey]
    public static readonly Producttype Default = new Producttype("default", false);
    public static readonly Producttype Box = new Producttype("box", true);

    private TestableConstant(string key, bool isValid)
    {
        this.Add(key, this);
        IsValid = isValid;
    }

    public bool ValidType { get; private set; }
}

Using constants:

public class Product
{
    private Producttype producttype;

    public Product(string type)
    {
        producttype = ProductType.GetOrDefaultFor(type);
    }

    public void Validate()
    {
        if(prodtuctype.IsValid)
        {
            return true;
        }

        // Just to illustrate that it can be used as a normal enum as well
        if(producttype == Producttype.Default)
        {
            return true;
        }

        return false;
    }
}

Link to botox at Nuget: https://nuget.org/packages/Constant
(Or search for Botox)

Project home page at GitHub: https://github.com/projecteon/Constant

New release of Botox

Announcing new release of Botox, a lightweight dependency injection framework for portable class libraries.

The algorithm for creating new instances has been improved. It used to be dumb,  just picking the first constructor with zero parameters and then trying to resolve that. If it failed, the creation failed.

It will now sort the constructors by parameters in a descending order. For each constructor it will try to resolve the parameters. If it succeeds, that constructor is cached for that type and then resolved (future creates will use the cache for better performance). If all fails, exception will be thrown.

Check out the code on github if you want more insight to how it works.

Link to botox at Nuget: https://nuget.org/packages/Botox/
(
Or search for Botox)

Project home page at GitHub: https://github.com/projecteon/Botox

Consuming REST service async in PCL

With arrival of HttpClient in .Net 4.5 one would think that consuming rest services with async should be a breeze in portable class libraries. Unfortunately, HttpClient was not added for PCL (nor for windows phone). We are left with using WebClient and HttpWebRequest.

Preparing HttpWebRequest for async
We start off with creating an interface for abstracting our service like this:

public interface IServiceClient where T : class
{
    Task Get(string id);
    Task<IList> GetAll();
    Task Post(T dto);
    Task Put(T dto);
}

Consuming REST Get
We start off by implementing the GetAll method. I prefer using Json.Net due it handling object trees better than MS own implementation.

public async Task<IList> GetAll()
{
    var response = await this.MakeAsyncRequest();
    var result = JsonConvert.DeserializeObject<IList>(response);
    return result;
}

This method does little more than converting the string callback from MakeAsyncRequest into a valid object. MakeAsyncRequest accepts an url appending parameter and returns a Task. The method makes use of the Task.Factory.FromAsync to call the REST service asynchronously, returning the Task followed by a continuation to read the WebResponse.

private Task MakeAsyncRequest(string urlAppend = "")
{
    var request = (HttpWebRequest)WebRequest.Create(this.url + urlAppend);
    request.ContentType = "application/Json";
    return Task.Factory.FromAsync(request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), null)
                        .ContinueWith(t => this.ReadFromStreamResponse(t.Result));
}

Implementing getting a single item by id is then simple:

public async Task Get(string id)
{
    string response = await this.MakeAsyncRequest(id);
    var result = JsonConvert.DeserializeObject(response);
    return result;
}

We can now use a REST service from the view model without locking the UI thread by using the await keyword.

Consuming REST Post/Put
Writing the post/put requires a bit more plumbing. Trying to keep the code clean our intitial Post method looks like this:

public async Task Post(T dto)
{
    var postData = JsonConvert.SerializeObject(dto);
    var request = (HttpWebRequest)WebRequest.Create(this.url);
    request.ContentType = "application/Json";
    request.Method = "POST";
    return await CreatePostWebRequestTask(request, () => Encoding.UTF8.GetBytes(postData));
}

It creates a string presentation of our Dto, creates the web request object and then ships it off async. The Put method would look exactly the same, but we would use “PUT” as request method:

    request.Method = "PUT";

Our CreatePostWebRequestTask starts off by sending the async request, waits for the result to come back and then de-serialize it.

public static Task CreatePostWebRequestTask(HttpWebRequest request, Func<byte[]> dataGetter)
{
    var task = CreatePostWebRequestTask(request, dataGetter);
    task.Wait();
    return Task.Factory.StartNew(() => DeserializeObjectFromResult(task));
}

private static T DeserializeObjectFromResult(Task<byte[]> task)
{
    var buffer = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, task.Result);
    var tempString = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
    return JsonConvert.DeserializeObject(tempString);
}

The async request itself looks like this:

private static Task<byte[]> CreatePostWebRequestTask(HttpWebRequest request, Func<byte[]> dataGetter)
{
    return Task<byte[]>.Factory.StartNew(
        () =>
            {
                //Exception exception = null;
                byte[] responseData = null;

                var getRequestStreamTask =
                    Task.Factory.FromAsync(request.BeginGetRequestStream,
                                                    request.EndGetRequestStream,
                                                    null)
                                                .ContinueWith(task => WriteDataToOutStream(dataGetter, task));

                getRequestStreamTask.Wait();

                Task requestTask =
                    Task.Factory.FromAsync(
                        request.BeginGetResponse,
                        request.EndGetResponse,
                        null,
                        TaskCreationOptions.AttachedToParent)
                        .ContinueWith(task => responseData = GetData(task.Result));

                requestTask.Wait();

                return responseData;
            },
        TaskCreationOptions.AttachedToParent);
}

private static void WriteDataToOutStream(Func<byte[]> dataGetter, Task task)
{
    var outStream = task.Result;
    var data = dataGetter();
    if (data == null || data.Length == 0)
    {
        return;
    }

    outStream.Write(data, 0, data.Length);
}

private static byte[] GetData(WebResponse response)
{
    using (response)
    {
        var inStream = response.GetResponseStream();

        if (inStream != null)
        {
            using (inStream)
            {
                return GetResponseData(inStream, response.ContentLength > 0 ? response.ContentLength : 1024);
            }
        }
    }

    return null;
}

private static byte[] GetResponseData(Stream inStream, long bufferSize)
{
    using (var output = new MemoryStream())
    {
        int count;
        do
        {
            var buf = new byte[bufferSize];
            count = inStream.Read(buf, 0, Convert.ToInt32(bufferSize));
            output.Write(buf, 0, count);
        }
        while (inStream.CanRead && count > 0);
        return output.ToArray();
    }
}

Summary

This should help you along to getting a nice re-usable library using REST services and async in the absence of HttpClient. Code with examples can be found here http://tinyurl.com/awwg9l3.

*Update* By the time I finished this blog, it seems MS finally got their act together and made HttpClient for Windows Phone and Portable Class Libraries as well. See  Portable HttpClient for .NET Framework and Windows Phone.Its still in beta, so those who want to stay away from beta code are free to use the example code above.

Release of Botox

Now announcing the release of Botox, a lightweight dependency injection framework for portable class libraries.

Following my last post on dependency resolving in PCL, I decided to make a small framework for others to use if they don’t want to make their own. I will continue to keep it updated and add functionality to it as the need arises.

Link to botox at Nuget: https://nuget.org/packages/Botox/1.0.0.0
(
Or search for Botox)

Project home page at GitHub: https://github.com/projecteon/Botox

Dependency resolving in portable class libraries (PCL)

With windows 8 coming out and the prospect of shared code between windows 8 and windows phone 8 I started looking into portable class libraries. Thinking this would be an easy way out for shared code, I was quickly turned from that assumption. The shared libraries between the two components does have its limitations (add WP7.1 support or Silverlight 4 and it shrinks to even less).

One of the issues I ran into was how to handle dependency resolution. Most frameworks (known at least) didn’t support PCL’s. I decided to write my own lightweight version which would also give me more insight into using the PCL framework.

Registering and resolving those are quite straightforward so Ill skip that. The issue was not having full access to .Net reflection or MEF for handling constructor injection and automatically handling that on object creation.

First issue was to locate any possible constructor with parameters. Luckily the implementation of reflection for my chosen PCL project (minimal except for XBOX) had access to some reflection methods for access public properties. This gave me the option to try and locate any constructor with that might need injection (fex just more than 0 parameters).

private static ConstructorInfo GetNoneConstructor(Type type)
{
   var constructorWithParameters = type.GetConstructors()
                                       .First(constructor => constructor.GetParameters().Length > 0);
   if (constructorWithParameters == null)
      throw new NotImplementedException("Non default constructor not implemented in :" + type);

   return constructorWithParameters;
}

Having that in place, I could use this method to create new instances with constructor injection.

public static T CreateInstanceOf<T>()
{
    var constructor = GetNoneConstructor(typeof(T));
    var list = new List<object>();
    foreach (var parameterInfo in constructor.GetParameters())
    {
        var typeName = parameterInfo.ParameterType.FullName + "," + parameterInfo.ParameterType.Assembly;
        var type = Type.GetType(typeName);
        list.Add(Resolve(type));
    }
    return (T)constructor.Invoke(list.ToArray());
}

The code resolves any interfaces and then invokes the constructor with the needed injections. This can of course be extended to handle more complex issues if needed.

I plan to release a small package to NuGet once I get the NuGet setup which should give easy access to an extreme lightweight DI resolver for those in need in their PCL’s.