Friday, July 27, 2012

Map SqlReader to Bussiness Entity Collection using Reflection C#

Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information

Map Data To Business Entity Collection

MapDataToBusinessEntityCollection is a generic Reflective method. We pass in the data-type for the objects to be mapped as a generic parameter along with a data reader. We use reflection to find the properties in this type and we use the meta data in the DataReader to find the fields.

Whenever we find a field from the data reader that has a matching writable property in the generic type, we pull the value from the DataReader and assign it to a newly created object. Regardless of how many properties are in T, this method will map every property that has a matching field in the DataReader. Any properties that are not in the DataReader will be unmapped. Any fields in the data reader that do not have a matching property will be ignored. The validation logic is handled in the implementation of the properties in T.

public static List<T> MapDataToBusinessEntityCollection<T>(IDataReader dr) 
where T : new()
  Type businessEntityType = typeof (T);
  List<T> entitys = new List<T>();
  Hashtable hashtable = new Hashtable();
  PropertyInfo[] properties = businessEntityType.GetProperties();
  foreach (PropertyInfo info in properties)
      hashtable[info.Name.ToUpper()] = info;
  while (dr.Read())
      T newObject = new T();
      for (int index = 0; index < dr.FieldCount; index++)
          PropertyInfo info = (PropertyInfo)
          if ((info != null) && info.CanWrite)
              info.SetValue(newObject, dr.GetValue(index), null);
  return entitys;

Wednesday, July 25, 2012

Working With Cookies In Javascript

Cookies are variables of temporary data which is stored on the visitors computers. They are normally used for things like remember my username on a login form. This can be a useful way to store information about your returned visitors without them having to log in to store information on a database.

It's worth noting that cookies should not be used to store secure information as they are just files stored on your visitors computer.

You can set a cookie on both the server side and the client side in this article we are going to look at the process you would set-up a cookie on the client side using Javascript.

Raw Javascript

Working with cookies in Javascript is not the best feature of Javascript, there is no easy way of dealing with setting and getting cookies.

All Values

To get all the cookies which are set for the current document you need to use the following.
                var allCookies = document.cookie;

Setting Values In Javascript

To set a cookie you need to use the Javascript variable document.cookie, to add values to this you need to setup the data as a query string and add onto the end of the document.cookie.
document.cookie = "website=weblink";
// cookie is website=weblink

If you want to add extra data to the cookie then you just need to repeat the above step.
document.cookie = "secondwebsite=second-site-demo";
// cookie is website=weblink;secondwebsite=second-site-demo;

Now this seems easy to set data but this will not deal with expiring the cookie or domain for the cookie. To set the expiry of the cookie you need to add the expiry on the end of the document.cookie.
document.cookie += "; expires="+date.toGMTString();

To set the domain path of the cookie you then need to set the path on the end of the document.cookie.
            document.cookie += "; path=/";

With these factors you can add to just setting data on the cookie it can be difficult to handle you need to write a function to handle the setting of the cookie.
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        var expires = "; expires="+date.toGMTString();
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";

Getting Values

As you can see there is a lot you need to do to set the values on the document.cookie but you will need to do even more to get values out of the document.cookie.
If you want to get a certain value you have set you can't just call the key of the data to get the value you have to use a function which will do a reg ex search to get the value of a key.

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    return null;

Easier Way Of Working With Cookies In Javascript

There must be an easier way of handling the cookie data then having to create you own functions to deal with the different scenarios of setting, getting, all cookies, remove cookies, empty all cookies, testing if cookies are enabled.
There is an easier way of working with cookies there is a Github project called cookie.js, this is a simple javascript file which when included on your web page you can easily handle the cookie data.


To use cookie.js all you have to do is download it from Github and include it on your page, download it from here. Then you can include it on the page by doing using the following code.

            <script src="cookie.min.js" > </script >

When this file is included there will be a new cookie object to use to set and get the data.

Setting Cookie

To set a cookie with cookie.js all you have to do is use the method set().

cookie.set( 'key', 'value' );

If you want to add extra parameters to the cookie you can set these up as the third argument on the method.
cookie.set( 'key' , 'value', {
   expires: 7,
   domain: "",
   path: "/",
   secure: false

Getting Cookie

To get the values from the cookie it is as easy as using the get() method, this will return string of the value of the key.

cookie.get( 'key1' );

Or you can even use a shorthand version of this by just doing.
cookie( 'key1' );

Get All Cookies

To get all the cookies available it is very simple by using the all() method.

var allCookies = cookie.all();

Removing Cookies

It is also easy to remove the cookies by referring to the key you have setup on the cookie, by using the remove() method.

cookie.remove( 'key1' );

You can even remove all cookies available on the domain by using the empty method.


Cookies Enabled

Visitors can turn cookies off on the browser so you will not be able to store data on the visitors computer, for this reason you will need to check if cookies are enabled before you try setting up new cookies.
With cookie.js you can do this easily by using the enabled() method.

if (cookie.enabled()) {
   // Cookies are on you can setup cookies
} else {
   // Cookies are turned off you can not use cookies


Friday, July 6, 2012

Converts a virtual path to an application absolute path - Extension Methods

Converts the provided app-relative path into an absolute Url containing the full host name

   /// App-Relative path
    /// Provided relativeUrl parameter as fully qualified Url
    /// ~/path/to/foo to
    public static string GetAbsoluteUrl(string relativeUrl)
        if (String.IsNullOrEmpty(relativeUrl))
            return String.Empty;

        if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            return relativeUrl;

        if (HttpContext.Current == null)
            return relativeUrl;

        HttpContext context = HttpContext.Current;

        if (relativeUrl.StartsWith("/"))
            relativeUrl = relativeUrl.Insert(0, "~");

        Page page = context.Handler as Page;
        if (page != null)
            relativeUrl = page.ResolveUrl(relativeUrl);
            if (!relativeUrl.StartsWith("~/"))
                relativeUrl = relativeUrl.Insert(0, "~/");

            relativeUrl = VirtualPathUtility.ToAbsolute(relativeUrl);

        var url = context.Request.Url;
        var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

        return String.Format("{0}://{1}{2}{3}",
               url.Scheme, url.Host, port, relativeUrl);

Compares to DateTimes and converts the result to an easy human readable

Take this:2012-07-13 17:47:33

and turn it into this:5 minutes 16 seconds ago

    /// Compares to DateTimes and converts the result to an easy human readable format.
    /// A past or future DateTime.
    /// Relative to this time.
    public static string ToRelativeTime(this DateTime time, DateTime relativeTo)
        TimeSpan ts = relativeTo.Subtract(time).Duration();
        string DateFormat = "d MMMM";
        string dir = (relativeTo > time) ? "Ago" : "To go";

        if (relativeTo.Year != time.Year)
            DateFormat += " yyyy";

        if (ts.Days < 360)
            if (ts.Days >= 30)
                return string.Format("{0} ({1} Months {2})", time.ToString(DateFormat), (int)(ts.Days / 30), dir);

            if (ts.Days > 0)
                return string.Format("{0} ({1} Days {2})", time.ToString(DateFormat), ts.Days, dir);

            if (ts.Hours > 0)
                return string.Format("{0} Hours {1} Minutes {2}", ts.Hours, ts.Minutes, dir);

            if (ts.Minutes > 0)
                return string.Format("{0} Minutes {1} Seconds {2}", ts.Minutes, ts.Seconds, dir);

            return string.Format("{0} Seconds {1}", ts.Seconds, dir);

        return time.ToString(DateFormat);

Extension Methods (C# Programming)

Another cool feature of C# is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class.However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

public static class Helpers
    public static bool isNumber(this object inputvalue)
        if (inputvalue == null) return false;
        Regex isnumber = new Regex("[^0-9]");
        return !isnumber.IsMatch(inputvalue.ToString());

    public static bool isNumeric(this string s)
        float output;
        return float.TryParse(s, out output);

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the isNumber() method directly on strings, like this:

     string test = "4";
     if (test.isNumber())