Using Html Label element with a fixed width

You may want to use Label juxtaposed with input element and want those label to be with a fixed width. This can be the case if have some column done with division and you want to have all label to be aligned on the left and having all their input control aligned left but at the same distance and not depending of the text’s size. For that, you want a fixed width for all label. This can be done by setting the width but also setting the display to block instead of inline. Also, you will need to make it floats.

label {
    display: block;
    float: left;
    width: 200px;
}

CSS and the selector nth-child

You may want to have special style for specific position. Maybe you want to have the first division different or having every 3 rows something different.

This can be done with nth-child selector of CSS.

Let’s start with a small example :

ul>li:nth-child(3) {  
  color: red;
}

This example will take the third li element that is directly under an ul element and make it’s font color to red.

The parameter, when specified with an integer, represent the position of the occurrence of the element. In the example above, 3 is specified, so the third element will be red.

nth-child is power full because you can use the variable “n” to specify the index of the element.

ul>li:nth-child(2n+1) {  
  background-color: red;
}

This second example of nth-child has 2n+1 has parameter. That mean that it will start at the position 1 (every sequence start at 1 not 0) and 2n mean 2 multiply by the index. So if we have the following code:

<ul>
  <li>n=0</li>
  <li>n=1</li>
  <li>n=2</li>
  <li>n=3</li>
  <li>n=4</li>
  <li>n=5</li>
</ul>

2n+1 will be for the first line : 2×0+1 = 1. So the first li will have the style, the first one will be 1. Then we have 2×1+1 = 3. The second row won’t have any style, the third one yes and so on.

To conclude, you have to remember that n start at 0 but the first element is 1. As we have seen with the ul/li example, the n=0 was coloured because n=0+1 = one, which is the first li of the ul collection.

How to use DateTime in Select with Linq to Entity (Entity Framework 4.3)

If you want to create in your SELECT a new DateTime within your Linq to Entity query, you will reach an exception telling you that you cannot use parameterless class.

To solve this problem, you need to use a special function that only Linq to Entity can use. Entity Framework has some methods that will convert C# code into Sql function. In our case, the method is called “EntityFunctions.CreateDateTime(…)“.

Instead of having something like this:

var data = (from i in Database.Users
       group i by new {y=i.InvoiceDate.Year,m = i.InvoiceDate.Month} into g
       select new UserStatistic{ Date = new DateTime(g.Key.y, g.Key.m, 1), Experience = g.Sum(o => o.Exp));

You need to use the EntityFunctions.CreateDateTime :

var data = (from i in Database.Users
       group i by new {y=i.InvoiceDate.Year,m = i.InvoiceDate.Month} into g
       select new UserStatistic{ Date = EntityFunctions.CreateDateTime(g.Key.y, g.Key.m, 1, 0, 0, 0), Experience = g.Sum(o => o.Exp));

Both code do the same thing, but the second work with Entity Framework. This is because it uses Linq to Entity which convert its statement into SQL and hence, doesn’t know how to create a .Net DateTime object.

You can find the complete exhaustive list of entity functions at Microsoft MSDN web site.

Microsoft .Net 4.5 Garbage collector

Microsoft have been working on the garbage collector since version 1 of the .Net framework. Nevertheless, since Framework 4, they have increased their effort to make this one more efficient. The version 4.5 (still in RC version at this moment), go a step further with a garbage collector that run concurrently from the user thread. This result to shorter time to recycle memory for large application. The new garbage collector is called “background server garbage collection“.

Heap balancing
Another improvement is that now, the garbage collector heap is balanced (small and large object). That mean that if a thread is using a lot of resource while others thread are not, the charge will be distributed evenly on all threads’ heap. This will reduce the time before cleaning memory.

Scheduler
A third improvement concern the time when the garbage collector can recycle its memory. It’s possible to activate a mode “SustainedLowLatency” which will let you set a schedule when it’s more appropriate to recycle memory. This let you have monster memory computer that will recycle only in a time frame or with exception within if the server run low in memory.

Large memory allocation
Also, it’s now possible with Microsoft Framework 4.5 to have large memory allocated without having the “OutOMemoryException”. Before, any allocation over 2gb would raise an out of memory exception. Now, if the physical machine have more than 2gb, than you can have more than 2gb memory allocation.

How to simplify comprehension of a complex Entity Framework Query

You may run into the case of where the Linq to Entity query is long and complex.

If you are using a layer of abstraction to access your database (DAL “Data Access Layer) that return IQueryable you may be surprise that you can divide your query into multiple IQueryable and to merge all Linq to Entity back into a single IQueryable.

The first step is to create your method into your DAL.

public IQueryable<MyModel> GetMyModel() {
   //Linq to Entity is returned here
}

The second step is to create query in logical group. Let say you desire to have all objects of your MyModel that is over 100$ and another condition is that you want also all those over 20$ if they have a discount.

You can do it with a single Linq to Entity, but in some situation (more complex than the one exposed here) you may found easier to cut the problem in sub query.

This can be done by using multiple IQueryable.

public IQueryable<MyModel> GetMyModel() {
   var query1 = //Linq to Entity with condition for > 100$
   var query2 = //Linq to Entity with condition for > 20$ && Discount > 0$
   //return query1 + query 2
}

The last step is to merge query 1 and query 2. You can do it in two differents way with Linq. The first one is to use the Union keyword and the second is with Concat.

The difference between the two is that union will merge only when not already present when concat will merge everything. Here is a small snippet of code that illustrate this theory.

var set1 = new int[] { 1, 2, 3 };
var set2 = new int[] { 3, 4, 5 };

var result= set1.AsQueryable().Concat(set2.AsQueryable());  // count == 6
var result2 = set1.AsQueryable().Union(set2.AsQueryable()); // count == 5

Our example could look with union like this:

public IQueryable<MyModel> GetMyModel() {
   var query1 = //Linq to Entity with condition for > 100$
   var query2 = //Linq to Entity with condition for > 20$ && Discount > 0$
   return query1.union(query2); //Both condition
}

Since we are using IQueryable, none of the query are executed until their execution. That mean that that Sql Server will receive a single query (with multiple sub query).

HttpCookie and web.config domain

You can set in your Asp.Net web.config file a domain for all your cookie. This is done by setting the httpcookies from the system.web.

  <system.web>
     <httpCookies domain=".domain.com"/>
  </system.web>

The main goal is to have all your cookies attached to the domain and not set to the subdomain. Also, notice that I have wrote .domain.com and not domain.com. This is important, otherwise, it won’t work with subdomain.

So what does it do behind the scene? It simply set the domain property of the cookie to the domain name. In fact you could have code it manually:

var cookie = new HttpCookie();
cookie.Domain = ".domain.com";

Instead you set it once in the web.config.
This is the constructor of HttpCookie. As you can see, it calls SetDefaultsFromConfig().

public HttpCookie(String name, String value) { 
     _name = name;
     _stringValue = value;
     SetDefaultsFromConfig(); 
     _changed = true;
} 

This method goes into the web.config to get the domain.

private void SetDefaultsFromConfig() {
    HttpCookiesSection config = RuntimeConfig.GetConfig().HttpCookies; 
    _secure = config.RequireSSL;
    _httpOnly = config.HttpOnlyCookies;

    if (config.Domain != null && config.Domain.Length > 0) 
          _domain = config.Domain;
} 

The variable _domain is changed by the configuration file value.

This variable is also setted by the domain property.

        public String Domain { 
            get { return _domain;}
            set {
                _domain = value;
                _changed = true; 
            }
        } 

How to kill current session in Asp.Net?

If you need to kill your current session, which is the case if a user logout, you need to kill cookies and sessions.

To kill cookies, you have to set the expiry to something already passed like the yesterday date. For the session, you can use the method “Abandon”.

The Abandon method destroys all the objects stored in a Session object and releases their resources. The resources are not deleted right away, which mean that you still have access to the data of the session until the page is generated.

     HttpContext.Current.Session.Abandon();

Session are stored in a cookie with the name “ASP.NET_SessionId”. You need to kill this cookie like you would do with any cookie.

                var sessionCookie = new HttpCookie("ASP.NET_SessionId", string.Empty);
                sessionCookie.Expires = DateTime.Now.AddDays(-1);
                sessionCookie.Domain = UrlInformation.GetHostDomain(HttpContext.Current.Request.Url.Host);
                HttpContext.Current.Response.Cookies.Add(sessionCookie);   

With those two snippets of code, the session should be killed for good.

Creating an Html Extension with the possibility to add Html Attribute with HtmlHelper.AnonymousObjectToHtmlAttributes

When you are building a Html Extension, it’s always a good idea to provide an overloaded of your extension that can have additional html attribute. This lead to the possibility to insert class, style or any other html attribute to the control that you are rendering.

First of all, you need to create the overload of your extension. You can also add at last parameter with default value with the default value to null because the type of this parameter should be object.

public static MvcHtmlString MyExtensionXZY<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, string anyThing)
{
   //...
}
public static MvcHtmlString MyExtensionXZY<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, string anyThing, object htmlAttributes)
{
   //...
}

Or this can be with a default value:

public static MvcHtmlString MyExtensionXZY<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, string anyThing, object htmlAttributes=null)
{
   //...
}

In both case, the next step is to transform the object into a Dictionary. Why do we accept an object if it’s to transform it into a Dictionary few lines after? The reason is to let anonymous object to be used. This way, it’s possible to call the html helper without having to declare the dictionary every time we want to use it.

@Html.MyExtensionXZY("Test", new {class= "MyClass"});

Last step is to assign the attributes values to the html control that we are building. This can be done with a single line of code if you use a HtmlHelper method that is available in its static class.

myControl.MergeAttributes(System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), true);

So, what it does is that it takes the object html Attribute and convert it into a dictionnary. The method AnonymousObjectToHtmlAttributes is available in System.Web.Mvc.HtmlHelper:

        public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) { 
            RouteValueDictionary result = new RouteValueDictionary(); 

            if (htmlAttributes != null) { 
                foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes)) {
                    result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
                }
            } 

            return result; 
        } 

Once this is converted, it will be used with the MergeAttributes method of your new control. This method is available if you are using the System.Web.Nvc.TagBuilder class which let you create html tag. Once done with the TagBuilder, you only need to call the .ToString() of the object and you will get the generated html. As you may have notice, the MergeAttributes has “True” at its second parameter. This let know the builder that if an attribute was already available to override it with the new one. This let you have the final control of the rendering of your control.