:::: MENU ::::

Thursday, July 26, 2012

Introduction:

Application performance is the very important factor for an application success. Yahoo's Best Practices for Speeding Up Your Web Site is a great resource for increasing your application performance. Out of these practices, 'Putting Stylesheets at the Top','Putting Scripts at the Bottom' and 'Minifying(external and inline) JavaScript and CSS' are very important practices. Minifying inline css and js is also very important. From Yahoo Best Practices page 'In addition to minifying external scripts and styles, inlined <script> and <style> blocks can and should also be minified. Even if you gzip your scripts and styles, minifying them will still reduce the size by 5% or more. As the use and size of JavaScript and CSS increases, so will the savings gained by minifying your code '. So, in this article, I will show you how to minify and bundle(combine all css/js) your inline css/js.

Description:

Open your ASP.NET application(WebForm or MVC) and install BundleMinifyInlineJsCss nuget package.

                    Then register the response filter. If you are using WebForm, you can register response filter in a master page and if you are MVC, you can use register response filter in an action filter.  

   1:  public partial class SiteMaster : System.Web.UI.MasterPage
   2:  {
   3:      protected void Page_Load(object sender, EventArgs e)
   4:      {
   5:          Response.Filter = new BundleAndMinifyResponseFilter(Response.Filter);
   6:      }
   7:  }
   8:   
   9:  public class BundleMinifyInlineCssJsAttribute : ActionFilterAttribute
  10:  {
  11:      public override void OnActionExecuting(ActionExecutingContext filterContext)
  12:      {
  13:          filterContext.HttpContext.Response.Filter = new BundleAndMinifyResponseFilter(filterContext.HttpContext.Response.Filter);
  14:      }
  15:  }
  16:   
  17:  [BundleMinifyInlineCssJs]
  18:  public class HomeController : Controller
 


Now just run your application. If a page view-source is,


After using the above response filter, it will become,

.

Note in the above screen the inline css moved to top, inline javascript moved to bottom and inline javascript/css is minified and bundled. 

Summary:

In this article, I showed you how to you quickly and easily put all your inline css at the top, put all your js at bottom and minifying/bundle all your inline  javascript/css using a response filter. Hopefully you will enjoy this article too.

More

Tuesday, July 24, 2012

I’ve been doing more JavaScript lately than I have in the past and am starting to take a closer look at semantics. In particular, the strange looking exactly equal operator with the three equal signs, ===. Someone who’s been working a career of C, C++, Java, and C# might not be familiar with exactly equalbecause equality in these languages is already strongly typed.

The point is that JavaScript is not strongly typed, so the development experience is different. The subject of this post addresses the typing issue associated with equality and the meaning of the JavaScript exactly equal operator.

The primary difference between the equal, ==, and exactly equal, ===, operator is typing. They both test for equality, but exactly equal tests for type too.  Here’s an example:

var fiveInt = 5;
var fiveString = "5";

var equal = fiveInt == fiveString;
var exactlyEqual = fiveInt === fiveString;


In the code above, fiveInt is a integer type and fiveString is a string type.  The equal operator expression sets the equal variable to true.  However, the exactly equal operator expression sets the exactlyEqual variable tofalse.  The exactly equal operator expression in the example above results in false because it’s comparing two variables that are different types.

Most of the time, it seems like exactly equals is what you should do because it’s safer and avoids errors through false positives. However, I can see where equals would be useful for when reading screen input that is read as a string and being able to make a quick comparison without the extra conversion/validation code that would be required in C#.

More

Monday, July 16, 2012

There are many times in .NET where we have an instance of a value type that we need to treat as optional.  That is, we may want to consider its value as being supplied or missing.

The System.Nullable<T> structure in the .NET Framework can be used to represent these situations in a consistent and meaningful way.

Why Do We Use Nullable<T>?

With instances of reference types, you can easily denote an optional item by simply leaving the reference as null, but this isn’t really possible with a value type (that is, not directly), because the instance of a value type always has a value.

For example, if you had an Person class with some basic data:

   1: public class Person
   2: {
   3:     public string FirstName { get; set; }
   4:     public string LastName { get; set; }
   5:     public int YearsRetired { get; set; }
   6:  
   7:     // ...
   8: }

We could have a person with no first name (Sting, Madonna, etc… or is that no last name?), simply by setting the string property FirstName tonull:



   1: aPerson.FirstName = null;

But in the case of YearsRetired, if the person hasn’t retired yet, we can’t set a simple int to null, because an int is a value type, which must always have a value (strictly speaking):



   1: // compiler error
   2: aPerson.YearsRetired = null;

That said, we could use a sentinel value (-1), or have a separate bool field (IsRetired) to say whether we should use this field or not, but these get messy and harder to maintain.  Consider that if you use a sentinel value, everyone who uses this field must know what that value would be and to test for it.


Alternatively, if you use a bool field to tell you if the value field is usable, they aren’t encapsulated, so again there could be usage issues or consistency issues in naming, etc.


This is why Nullable<T> exists, to allow you to easily mark value type instances as optional (“nullable”) by providing a mechanism that gives values types something like null semantics in an encapsulated and uniform way.


In this way, anyone who looks at your interface and sees Nullable<int> (can also be abbreviated int?) will know how to test whether it has a valid value or not.


How the Nullable<T> struct Works


When you have a Nullable<T> wrapped type in the .NET Framework, it doesn’t give you a reference which you can make null.  It actually is a simple struct (value type) that wraps your value type.  This is an important distinction because it clears up some common misconceptions on what the Nullable<T> type does and does not do.


For example, let’s say you have:



   1: // or int? for short…
   2: Nullable<int> yearsRetired = null;

What really is yearsRetired?  Is it a reference that points to nothing?  No, it’s actually an instance of a value type with two fields: HasValue, and Value.  Note: for you C++ boost library users out there, this is much like how boost::optional<T> works.


The HasValue field is a bool that tells you whether or not Value contains a valid value, and the Value field contains the value set by the user.  Also, to make sure that you use the type correctly, if you attempt to access Value directly when HasValue is false, you will get anInvalidOperationException.


So as you can see, this mimics the behavior of a reference type in some ways, but not others.  For example, you won’t save any space having an “empty” Nullable<BigHonkingStruct>.  The Value field still has the space for a BigHonkingStruct, it’s just inaccessible (that is, it always has a value, it just may not be a valid – i.e. user assigned -- value).


This may be confusing, because while you think you are setting a field to a null, it’s really just compiler magic.  For example, you can do this:



   1: int? yearsRetired = null;
   2:  
   3: if (yearsRetired == null)
   4: {
   5:     Console.WriteLine(“Active Employee”);
   6: }

But this is just syntactical sugar that actually just converts the usage of null to mimic calls against HasValue and Value:



   1: int? yearsRetired = default(int?);     // creates with HasValue = false, Value = default(int)
   2:  
   3: if (yearsRetired.HasValue == false)
   4: {
   5:     Console.WriteLine(“Active Employee”);
   6: }

So don’t be fooled into thinking Nullable<T> magically saves space for “null” instances of large value types.  In fact, if you have a struct so large that you are worried about wasted space, consider a class instead (see C# Fundamentals: The Differences between Struct and Class for more details).


Getting a Default Value


Many times while you are using a Nullable<T> instance, you may find yourself writing code like this:



   1: int cost = 0;
   2:  
   3: if (contractSize.HasValue)
   4: {
   5:     // you can do math on Nullable<int> directly, with caveats…
   6:     cost = contractSize * price;
   7: }
   8:  
Which you could shorten down using a conditional, of course:

   1: int cost = (contractSize.HasValue ? contractSize.Value : 100) * price;

That is, you want to use the value of a Nullable<T> in an expression, or a stand-in if the instance is “null”.  Either way so far, it looks a wee bit ugly, but there are a few ways we can clean this code up.


Nullable<T> has a method GetValueOrDefault() that allows you to retrieve the value if it exists, or the default specified if not.  It has two forms:



  • GetValueOrDefault()

    • Returns Value if HasValue is true, or default(T) if not.

  • GetValueOrDefault(T defaultValue)

    • Returns Value if HasValue is true, or defaultValue if not.

Thus, the code we wrote above could more concisely be written as:



   1: int cost = contractSize.GetValueOrDefault(100) * price;

Ah, much cleaner!  In addition, if you want the defaultValue to be whatever the default is for the given type, you can just call it without any parameter.



   1: // these evaluate to same value, because 0 is default for int.
   2: int cost1 = contractSize.GetValueOrDefault(0) * price;
   3: int cost2 = contractSize.GetValueOrDefault() * price;  

Nullable<T> and the Null-coalescing operator


Another nice thing C# did in .NET 2.0 was to add a null-coalescing operator (??) to get the value of a reference type if non-null, or a stand-in value if null.  They also performed some syntactical candy to allow this to work with Nullable<T> as well.  Basically, this behaves very similarly to using GetValueOrDefault():



   1: Console.WriteLine(“ The contract size is: {0}”, contractSize ?? 100);

The main thing to note here is that ?? is very low on the operator precedence, so if instead you had typed this:



   1: // compiler error, thinks you are trying to ?? between string and int
   2: Console.WriteLine(“The contract size is: “ + contractSize ?? 100);

You’d get an error, because it first tries to concatenate the string and contractSize, which results in a string, and then attempts to null-coalesce a string with an int value, which is invalid.  That is, it thought you wanted this:



   1: // + has higher precedence than ??
   2: Console.WriteLine((“The contract size is: “ + contractSize) ?? 100);

So when you use ?? in an expression, make sure you surround it in parenthesis where appropriate to make sure it is performed in the order you really mean:



   1: Console.WriteLine(“The contract size is: “ + (contractSize ?? 100));

Nullable Math Doesn’t Always Add Up


Finally, there are some interesting results when you attempt to use an arithmetic or logical comparison operator overload on a Nullable<T>wrapping a T that has those operators.  That is, if you have:



   1: int? x = null;
   2:  
   3: if ((x * 5) < 100)
   4: {
   5:     // ...
   6: }
   7:  

What will the result be?  It turns out false because the operator * between null and 5 returns null, and null has no meaningful order so <returns false.  In essence, this is modeled to behave much like SQL expressions with null values.  The long and the short of the matter is that math with a null numeric type yields null, and an ordered logical comparison with a null yields false.


For more details, I have a post titled C#/.NET Little Pitfalls: Nullable Math Doesn’t Always Add Up which you can dig into for more information on why this happens.


Summary


The Nullable<T> is a handy structure that was created to give us a consistent way to handle “optional” instances of value types. Nullable<T>instances can be assigned to null or compared with null, which really is syntactical sugar which creates a default instance or checks theHasValue property respectively.


In addition, you can use the GetValueOrDefault() method or the null-coalescing operator (??) to query the value, or provide a substitute if the value was never set.


 


More

Tuesday, July 10, 2012

When you are having different people working on one project remotely you will get some problem with web.config, as everybody was having different version of web.config. So at that time once you check in your web.config with your latest changes the other people have to get latest that web.config and made some specific changes as per their local environment. Most of people who have worked things from remotely has faced that problem. I think most common example would be connection string and app settings changes.

For this kind of situation this will be a best solution. We can divide particular section of web.config into the multiple files. For example we could have separate ConnectionStrings.config file for connection strings and AppSettings.config file for app settings file.

Most of people does not know that there is attribute called ‘configSource’ where we can  define the path of external config file and it will load that section from that external file. Just like below.

<configuration>

<appSettings configSource="AppSettings.config"/>

<connectionStrings configSource="ConnectionStrings.config"/>

</configuration>

And you could have your ConnectionStrings.config file like following.

<connectionStrings>

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication1-20120523114732;Integrated Security=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

Same way you have another AppSettings.Config file like following.

<appSettings>

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

</appSettings>

That's it. Hope you like this post. Stay tuned for more..

More

Monday, July 9, 2012

In previous blog posts I have discussed how to use XML files to store data in your applications. I showed you how to read those XML files from your project and get XML from a WCF service. One of the problems with reading XML files is when elements or attributes are missing. If you try to read that missing data, then a null value is returned. This can cause a problem if you are trying to load that data into an object and a null is read. This blog post will show you how to create extension methods to detect null values and return valid values to load into your object.

The XML Data

An XML data file called Product.xml is located in the \Xml folder of the Silverlight sample project for this blog post. This XML file contains several rows of product data that will be used in each of the samples for this post. Each row has 4 attributes; namely ProductId, ProductName, IntroductionDate and Price.

<Products>
  <Product ProductId="1"
           ProductName="Haystack Code Generator for .NET"
           IntroductionDate="07/01/2010"  Price="799" />
  <Product ProductId="2"
           ProductName="ASP.Net Jumpstart Samples"
           IntroductionDate="05/24/2005"  Price="0" />
  ...
  ...
</Products>

The Product Class

Just as you create an Entity class to map each column in a table to a property in a class, you should do the same for an XML file too. In this case you will create a Product class with properties for each of the attributes in each element of product data. The following code listing shows the Product class.

public class Product : CommonBase
{
  public const string XmlFile = @"Xml/Product.xml";

  private string _ProductName;
  private int _ProductId;
  private DateTime _IntroductionDate;
  private decimal _Price;

  public string ProductName
  {
    get { return _ProductName; }
    set {
      if (_ProductName != value) {
        _ProductName = value;
        RaisePropertyChanged("ProductName");
      }
    }
  }

  public int ProductId
  {
    get { return _ProductId; }
    set {
      if (_ProductId != value) {
        _ProductId = value;
        RaisePropertyChanged("ProductId");
      }
    }
  }

  public DateTime IntroductionDate
  {
    get { return _IntroductionDate; }
    set {
      if (_IntroductionDate != value) {
        _IntroductionDate = value;
        RaisePropertyChanged("IntroductionDate");
      }
    }
  }

  public decimal Price
  {
    get { return _Price; }
    set {
      if (_Price != value) {
        _Price = value;
        RaisePropertyChanged("Price");
      }
    }
  }
}

NOTE: The CommonBase class that the Product class inherits from simply implements the INotifyPropertyChanged event in order to inform your XAML UI of any property changes. You can see this class in the sample you download for this blog post.

Reading Data

When using LINQ to XML you call the Load method of the XElement class to load the XML file. Once the XML file has been loaded, you write a LINQ query to iterate over the “Product” Descendants in the XML file. The “select” portion of the LINQ query creates a new Product object for each row in the XML file. You retrieve each attribute by passing each attribute name to the Attribute() method and retrieving the data from the “Value” property. The Value property will return a null if there is no data, or will return the string value of the attribute. The Convert class is used to convert the value retrieved into the appropriate data type required by the Product class.

private void LoadProducts()
{
  XElement xElem = null;

  try
  {
    xElem = XElement.Load(Product.XmlFile);

    // The following will NOT work if you have missing attributes
    var products =
        from elem in xElem.Descendants("Product")
        orderby elem.Attribute("ProductName").Value
        select new Product
        {
          ProductId = Convert.ToInt32(
            elem.Attribute("ProductId").Value),
          ProductName = Convert.ToString(
            elem.Attribute("ProductName").Value),
          IntroductionDate = Convert.ToDateTime(
            elem.Attribute("IntroductionDate").Value),
          Price = Convert.ToDecimal(elem.Attribute("Price").Value)
        };

    lstData.DataContext = products;
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

This is where the problem comes in. If you have any missing attributes in any of the rows in the XML file, or if the data in the ProductId or IntroductionDate is not of the appropriate type, then this code will fail! The reason? There is no built-in check to ensure that the correct type of data is contained in the XML file. This is where extension methods can come in real handy.

Using Extension Methods

Instead of using the Convert class to perform type conversions as you just saw, create a set of extension methods attached to the XAttribute class. These extension methods will perform null-checking and ensure that a valid value is passed back instead of an exception being thrown if there is invalid data in your XML file.

private void LoadProducts()
{
  var xElem = XElement.Load(Product.XmlFile);

  var products =
      from elem in xElem.Descendants("Product")
      orderby elem.Attribute("ProductName").Value
      select new Product
      {
        ProductId = elem.Attribute("ProductId").GetAsInteger(),
        ProductName = elem.Attribute("ProductName").GetAsString(),
        IntroductionDate =
           elem.Attribute("IntroductionDate").GetAsDateTime(),
        Price = elem.Attribute("Price").GetAsDecimal()
      };

  lstData.DataContext = products;
}

Writing Extension Methods

To create an extension method you will create a class with any name you like. In the code listing below is a class named XmlExtensionMethods. This listing just shows a couple of the available methods such as GetAsString and GetAsInteger. These methods are just like any other method you would write except when you pass in the parameter you prefix the type with the keyword “this”. This lets the compiler know that it should add this method to the class specified in the parameter.

public static class XmlExtensionMethods
{
  public static string GetAsString(this XAttribute attr)
  {
    string ret = string.Empty;

    if (attr != null && !string.IsNullOrEmpty(attr.Value))
    {
      ret = attr.Value;
    }

    return ret;
  }

  public static int GetAsInteger(this XAttribute attr)
  {
    int ret = 0;
    int value = 0;

    if (attr != null && !string.IsNullOrEmpty(attr.Value))
    {
      if(int.TryParse(attr.Value, out value))
        ret = value;
    }

    return ret;
  }

  ...
  ...
}

Each of the methods in the XmlExtensionMethods class should inspect the XAttribute to ensure it is not null and that the value in the attribute is not null. If the value is null, then a default value will be returned such as an empty string or a 0 for a numeric value.

Summary

Extension methods are a great way to simplify your code and provide protection to ensure problems do not occur when reading data. You will probably want to create more extension methods to handle XElement objects as well for when you use element-based XML. Feel free to extend these extension methods to accept a parameter which would be the default value if a null value is detected, or any other parameters you wish.

NOTE: You can download the complete sample code at my website.http://www.pdsa.com/downloads. Choose “Tips & Tricks”, then "Read XML Files using LINQ to XML and Extension Methods" from the drop-down.

More