RestSharp with Async Await

RestSharp is an excellent open source project to use in a Windows Phone app if you want make http calls to a json api. However it doesn’t have any inbuilt support for the async await syntax. Thankfully with C#’s extensions methods we can add this support in our app.

namespace RestSharpEx
{
    public static class RestClientExtensions
    {
      public static Task<IRestResponse> ExecuteTaskAsync(this RestClient @this, RestRequest request)
      {
        if (@this == null)
            throw new NullReferenceException();
     
        var tcs = new TaskCompletionSource<IRestResponse>();
     
        @this.ExecuteAsync(request, (response) =>
        {
            if (response.ErrorException != null)
                tcs.TrySetException(response.ErrorException);
            else
                tcs.TrySetResult(response);
        });
     
        return tcs.Task;
      }
    }
}

This will add a new function to the RestSharp client type called ExecutreTaskAsync. Inside the method it will call the ExecuteAsync function as you normally would, but has also implemented returning a Task and setting it’s results when its complete.

To use the function would be as follows

var client = new RestClient("http://www.YOUR SITE.com/api/");
var request = new RestRequest("Products", Method.GET);
var response = await client.ExecuteTaskAsync(request);

Convert string or int to enum

Enum’s a great, but you may be wondering how you can turn an integer or string value into the corresponding enum. For example you may have an api that’s being sent XML or JSON, and then you need to turn one of the values within that into an enum to set on an object in your code.

Well it’s very simple. If you have a string do this:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

or if you have an int do this (you could also just do the first example with a ToString() on the end.

YourEnum foo = (YourEnum)yourInt;

Back to basics string vs StringBuilder

This is simple stuff but is something I see people easily miss by just not thinking about it.

A string is an immutable object, which means once created it can not be altered. So if you want to do a replace or append some more text to the end a new object will be created.

A StringBuilder however is a buffer of characters that can be altered without the need for a new object to be created.

In the majority of situations a string is a perfectly reasonable choice and creating an extra 1 or 2 objects when you appened a couple of other strings isn’t going to make a significant impact on the performance of your program. But what happens when you are using strings in a loop.

A few weeks ago one of my developers had written some code that went through a loop building up some text. It looked a little like this:

string foo = "";

foreach (string baa in someSortOfList)
{
    foo += " Value for " + baa + " is: ";

    var aValue = from x in anotherList
                 where x.name == baa
                 select x;

    foo += aValue.FirstOrDefault().value;
}

Everything worked apart from the fact it took 30seconds to execute!

He was searching through convinced that the linq expressions in the middle was what was taking the time, and was at the point of deciding it could not go any faster without a new approach.

I pointed out not only had he used strings rather than a StringBuilder, but the loop also created around 10 string objects within it. The loop which repeated a couple thousand times was therefore creating 20000 objects that weren’t needed. After we switched froms strings to a StringBuilders the loop executed in milliseconds.

So remember when your trying to work out why your code may be slow, remember the basic stuff.

Custom Validator Error from Server Side

The built in ASP.NET validators are amazing as we all know. You just drag them on the page, tell them what control to validate, give them a summary control to list the errors and they do it. But what if there’s something you need to add server side? Such as something that needs to check with the database before saving. You already have your validation summary control, so it would be nice to re-user that and have everything automatically looking the same. But it would appear there’s no easy way of doing it built in, so here’s an easy way of doing it… 

Creating a Custom Validation Error

First your going to need a class with some static class’s that you can pass your error message to. Here I have two functions one for simply adding the error to the page and the other for adding the error to the page with a specific validation group. I am using a CustomValidator object to make this all work, another option is to implement IValidator but it’s actually more effort than’s needed. The other section to note is that I’m setting the Error.Text to a non breaking space (this is what would normally go next to the form field you’re validating). This is because if you don’t then it will default to the ErrorMessage which we only want to go into the summary. If you try setting it to a normal space it will still also default to the summary text.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for Validator
/// </summary>
public class ValidationError
{

    public static void Display(string Message)
    {
        Display(Message, "");
    }

  public static void Display(string Message, string ValidationGroup)
    {
  CustomValidator Error = new CustomValidator();
        Error.IsValid = false;
        Error.ErrorMessage = Message;
        Error.ValidationGroup = ValidationGroup;
        Error.Text = "&nbsp;";

  Page currentPage = HttpContext.Current.Handler as Page;
        currentPage.Validators.Add(Error);
    }
}

Now to trigger the error you just need to called the function as below:

ValidationError.Display("Useful error message", "ValidationGroupName");

Creating Events in ASP.NET

Creating your own events on your own controls is something that is essential if you want you web app to work well and also provide you with reusable controls. It’s easy to skip past the problem and find another way to get your code to do what you want it to do and detect the change another way. But you end up with much nicer code if your controls can have proper events for a piece of action, and you web page can have proper event handlers on each. Not only that but the code you need to write in generally a copy and past job and not that hard.

The Code

While it’s not that hard, the amount of code that is needed is quite a lot more than you may expect. Fortunately though it’s code you going to just re-use again and again changing small bits as needed.

    //1 - Event args (use default, but eventually pass in data through here)
    public class SaveCompleteEventArgs : EventArgs
    {
        public SaveCompleteEventArgs(int inDataValue)
        {
            this.DataValue = inDataValue;
        } //end of con

        public readonly int DataValue;
    }



    //2 - define delegate
    public delegate void SaveCompleteEventHandler(object sender, SaveCompleteEventArgs e);

    //3 - define the event itself
    public event SaveCompleteEventHandler SaveComplete;

    //4 - the protected virtual method to notify registered objects of the request
    //	virtual so that it can be overridden.
    protected virtual void OnSaveComplete(SaveCompleteEventArgs e)
    {
        //if the UpdateData event is empty, then a delegate has not been added to it yet.
        if (SaveComplete != null)
        {
            //event exists, call it:
            SaveComplete(this, e);
        } //end of if
    }

    //5 - method that translates the input into the desired event
    public void TriggeringMethod(int strData)
    {

        // get new event args
        //EventArgs e = new EventArgs();
        SaveCompleteEventArgs e = new SaveCompleteEventArgs(strData);

        // call the virtual method
        OnSaveComplete(e);
    }

LINQ to SQL Inserts and Deletes

Inserting and Deleting records in a database using LINQ to SQL is just as easy as selecting information. What’s not so easy is actually finding out how to do it. There are lots of excellent blog posts around such as this one by Scott Guthrie http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx, however most of them we’re all written for the Beta version of LINQ to SQL which let you do a .Add() or .Remove() on your table, which was  changed on the final release. 

So to insert do something like this: 

DataClassesDataContext dataContext = new DataClassesDataContext(); 

//Create my new Movie record
Movie movie = new Movie();
movie.Name = "Tim's movie"; 

//Insert the movie into the data context
dataContext.Movies.InsertOnSubmit(movie); 

//Submit the change to the database
dataContext.SubmitChanges();

And to delete do something like this:

DataClassesDataContext dataContext = new DataClassesDataContext();

var movies = from m in dataContext.Movies
                  where m.Name == "Tim's movie"
                  select m;

dataContext.Movies.DeleteAllOnSubmit(movies);

dataContext.SubmitChanges();

System.Lazy

Lazy loading isn’t a new concept, it’s a pattern that been around for a while to improve the performance of your apps by only loading objects when they are going to be used. For example if you have an object that contains a property of a list of customers then you only really need to populate it when you access the property not when the object was initially created, as it may never be used. At the same time though you don’t want to be going off to the database every time access the property. So the simple solution is to have another private variable that stores if the customers property is populated or not and then check that in the property’s get to determine if the data needs to be loaded or not.

Well now in .NET 4, lazy loading has been built into the framework with System.Lazy. Instead of the above all you need to do now is write something like this…

Lazy<Customers> _customers = new Lazy<Customers>();

What this will do is create you a customers object but only run the constructor when you actually access the objects Value property which will be of type Customers. e.g.

_customers.Value.CustomerData 

It’s that simple, but can get even better. The constructor may not be the only thing you want to run when you access the property the first time. In this case you would write something like…

_customers = new Lazy<Customers>(() =>
        {
            // Write any other initialization stuff in here
            return new Customers();
        });

I must point out though while as great as this is, it does have some limitations so you probably won’t want to use it in all scenarios.

For more information check out the Lazy initialization page on MSDN

Introduction to Real Time Search

The Real Time Search this article relates to is a dll that comes included in the Web Client Software Factory one of Microsoft’s patterns and practices downloads. What it can do and what this example will demonstrate is adding the ability cause a post back that will refresh an update panel as the users types into a search box. This can give a great effect and make a web app really user friendly in scenarios like searching photo’s, emails or any general list.

First late me state though that this is in no way the most optimal way program. In most scenarios you could built a better result using something like JSON as their will be a lot less data transfer, which is also a general reason to avoid update panels. However this is also very quick and very easy to implement, not to mention if you’ve ever used update panels before you already know 90% of what’s needed. This can also only work in situations where you have a good search that is going to return the result quickly, rather than leaving the user sitting there trying to work out why nothing’s happening and where the search button has gone.

Implementing Real Time Search

For this example I will be filtering a table from a DB based on the search criteria and refreshing a Grid View with the results. I will be using a normal C# Web Site project with the Adventure Works sample DB from Microsoft. DB connection will be done using LINQ to EntityFramework, however there is no need to use this it is just my preference for the example.

First off set up you’re website and db and make sure both are working with no problems. As results will be displayed in an Update Panel, get one of these along with a script manager added to your page, so it looks something like this:

<form id=”form1″ runat=”server”>
<div>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate></ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

Next let’s get the search working in the normal method, so I’m going to create my Entity Model and add a textbox and gridview to show the results. Again you can connect and show your results however you want. You should now have something like this in your aspx file:

<form id=”form1″ runat=”server”>
<div>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>

<
asp:TextBox ID=”txtSearch” runat=”server” OnTextChanged=”TextChanged” Text=””></asp:TextBox>

<
asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate>

<
asp:LinqDataSource ID=”LinqDataSource1″ runat=”server” onselecting=”LinqDataSource1_Selecting”>
</asp:LinqDataSource>

<
asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataSourceID=”LinqDataSource1″>
<Columns>
<asp:BoundField DataField=”ProductID” HeaderText=”ProductID”
ReadOnly=”True” SortExpression=”ProductID” />
<asp:BoundField DataField=”Name” HeaderText=”Name”
ReadOnly=”True” SortExpression=”Name” />
<asp:BoundField DataField=”ProductNumber” HeaderText=”ProductNumber” ReadOnly=”True” SortExpression=”ProductNumber” />
<asp:BoundField DataField=”Color” HeaderText=”Color”
ReadOnly=”True” SortExpression=”Color” />
<asp:BoundField DataField=”SafetyStockLevel” HeaderText=”SafetyStockLevel”
ReadOnly=”True” SortExpression=”SafetyStockLevel” />
<asp:BoundField DataField=”ReorderPoint” HeaderText=”ReorderPoint”
ReadOnly=”True” SortExpression=”ReorderPoint” />
</Columns>
</asp:GridView>
</ContentTemplate>

</asp:UpdatePanel>
</div>
</form>

And this in your code behind:


protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
Model.AdventureWorks2008Entities AdventureWorkds = new Model.AdventureWorks2008Entities();
var products = from p in AdventureWorkds.Product
where p.Name.Contains(txtSearch.Text)
select p;
e.Result = products;
}

Next its time to add the Real Time Search. Make sure you have the dll downloaded (you may need to compile the download to get it) and add it to your bin folder. Add the following to your page in the relevant places:

<%@ Register Assembly=”RealTimeSearch” Namespace=”RealTimeSearch” TagPrefix=”cc1″ %>

<cc1:RealTimeSearchMonitor ID=”RealTimeSearchMonitor1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″>
<ControlsToMonitor>
<cc1:ControlMonitorParameter EventName=”TextChanged” TargetID=”txtSearch” />
</ControlsToMonitor>
</cc1:RealTimeSearchMonitor>

Important things to notice here are the AssociatedUpdatePanelId which tells the control what it has to refresh and the controls to monitor section which sets what the control to watch is called and the event name that will be fired when the post back is created. You will now need to corresponding control in your code behind like so:

protected void TextChanged(object sender, EventArgs e)
{
GridView1.DataBind();
}

Run the site and  you should find that the grid view now updates as you type (all be it with a slight delay).

To improve you can add other controls like update progress to show something happening which will help with any delays in displaying the results.