Thursday 24 October 2013

Exception Handling in ASP.NET MVC

Here is an interesting article about exception Handling in ASP.NET MVC. It talks about

  1. HandleErrorAttribute
  2. Limitations of HandleError
  3. HandleError vs Application_Error
  4. Extending HandleError
  5. Returning views from Application_Error
  6. ELMAH (Error Logging Modules and Handlers)

Click here to read more>>

4 ways to handle exceptions in ASP.NET MVC

Clear the output when returning error view

Global HandleErrorAttribute in ASP.net MVC3

Stacking Up Error Handlers in ASP.NET MVC

ASP.NET MVC4 CustomErrors DefaultRedirect Ignored

t-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx?wa=wsignin1.0">Using HandleError in ASP.NET MVC3

ELMAH: Error Logging Modules and Handlers for ASP.NET

Good Exception Management Rules of Thumb

Wednesday 23 October 2013

Catching WCF FaultException in ASP.NET Web Application

If you are making WCF method calls from your app it will be handy if your code give error details when something goes wrong with the WCF call. This can be done by adding a catch(System.ServiceModel.FaultException){} block within your code.
ServiceClient serviceClient;

try
{

//create ServiceClient 

//Service method call

}
catch (System.ServiceModel.FaultException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
if (serviceClient != null)
serviceClient.close()
}
With this code you can put a break point within the catch(System.ServiceModel.FaultException ex) block and inspect the fault exception as seen in the image below.

Disabling custom errors using TrySkipIisCustomErrors

HttpResponse.TrySkipIisCustomErrors Property can be used to enable / disable custom errors on IIS 7.0

The TrySkipIisCustomErrors property is used only when your application is hosted in IIS 7.0. When running in Classic mode in IIS 7.0 the TrySkipIisCustomErrors property default value is true. When running in Integrated mode, the TrySkipIisCustomErrors property default value is false.

HTTP Errors

The <httpErrors> element allows you to configure custom error messages for your Web site or application. Custom error messages let you provide a friendly or a more informative response by serving a file, returning another resource, or redirecting to a URL when visitors to your site cannot access the content they requested. For example, you might want to customize each of the error message pages for your Web site to have the same look and feel as the rest of your site.

The <httpErrors> element contains a collection of elements, each of which defines an error message that IIS uses to respond to specific HTTP errors. You can add custom error messages to IIS by adding an <error> element to the <httpErrors> element in the Web.config file for your site, application, or URL. Each element uses the responseMode attribute to specify whether IIS serves static content, dynamic content, or redirects to a separate URL in response to an error.

Example HTTP Errors configuration

<system.webServer>
<httpErrors>
<error statusCode="404" prefixLanguageFilePath="" 
path="/404Error" responseMode="ExecuteURL" />
<error statusCode="410" path="/410Error" 
responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>

Read more >>

Tuesday 22 October 2013

jQUery - read textbox value using its name

This can be done using jQuery's Attribute Equals Selector [name="value"] syntax. For example if name of the textbox is "email" then below script can be used to read the value.

$('input[name="email"]').val()

Monday 21 October 2013

ASP.NET 4.5 ScriptManager Improvements in WebForms

The ScriptManger control has undergone some key changes in ASP.NET 4.5 which makes it easier to register, manage and combine scripts using the ASP.NET weboptimizationfeature.

ASP.NET Web optimization framework

The ASP.NET Web optimization framework provides services to improve the performance of your ASP.NET Web applications.

Current services provided by the framework include:

  • bundling - combining multiple scripts or style resources together into a single resource, and thereby requiring browsers to make fewer HTTP requests
  • minification - making scripts or styles smaller using techniques such variable name shortening, white space elimination, etc.

Easy Integration with JQuery and JQueryUI

The default templates for WebForms ship with the following packages “AspNet.ScriptManager.jQuery” and “AspNet.ScriptManager.jQuery.UI.Combined”. These packages make it easier to bring in jquery and jqueryUI libraries and also register them with the ScriptManager. Here is how it works.

<asp:ScriptManager runat="server">
        <Scripts>
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="jquery.ui.combined" />            
        </Scripts>
    </asp:ScriptManager>
Read more>>

ASP.NET Web optimization

Friday 18 October 2013

Learn ASP.NET MVC

If you are new to ASP.NET MVC and looking for some articles which will give you a clear understanding of the ASP.NET MVC Framework here is an interesting list.

From ScottGu's blog @ weblogs.asp.net

ASP.NET MVC Framework (Part1)

URL Routing (Part2)

Passing ViewData from Controllers to Views (Part3)

Handling Form Edit and Post Scenarios (Part4)

Here is another set of articles from www.codeproject.com

Why MVC and What is MVC?, HTML Helper classes

Writing unit tests on MVC projects, Configure MVC routing, Validating MVC routes, Configure MVC outbound routes

Partial Views, Validation using data annotations, Razor, Authentication - Windows, Forms

JSON, jQuery, State Management

Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)

LINQ Sample - Group Products by Category

Following example orders List<Product> by Product.Category and saves the grouped result into a Dictionary<string, List<Product>>.

 public class Product
{
   public string Name { get; set; }
   public string Category { get; set; }
}

  List<Product> products = new List<Product>{
                new Product{ Name = "Beans", Category = "Veg" },
                new Product{ Name = "Apple", Category = "Fruit" },
                new Product{ Name = "Tomato", Category = "Veg" },
                new Product{ Name = "Orange", Category = "Fruit" },
            };

Dictionary<string, List<Product>> productCategories =
                (from p in products
                group p by p.Category into g
                select new { Category = g.Key, Products = g }
                )
.ToDictionary(categories => categories.Category, categories =>
categories.Products.ToList<Product>());    

Now you can order the result by Category name, that is the Key of Dictionary

var productCategoriesOrderd = 
productCategories.OrderBy(productCategory => 
productCategory.Key);

Generic Delegates in C# 3.0

With the introduction of generic delegates in C# 3.0 it is fairly easy to assign lambda expressions to generic delegates and pass those delegates to the extension methods.. Let's take a look at an example of using a few of those generic delegates:

        List<int> numbers = new List { 1, 2, 3, 4, 5, 6, 7 };
        Func<int, bool> where = n => n < 6;
        Func<int, int> select = n => n;
        Func<int, string> orderby = n =>  n % 2 == 0 ? "even" : "odd";
        var nums = numbers.Where(where).OrderBy(orderby).Select(select);

In the above example, we are using three different extension methods: where, orderby and select. The where extension method takes a generic delegate with int parameter and a return type of boolean to identity if a certain element be included in the output sequence. The select extension method takes an integer parameter and returns an integer, but it could return anything that you want the result to be transformed into — before being sent to the output sequence. In the orderby extension method, we are taking the integer parameter and using it to identify if it is even or odd. Based on that, we sort the results. With the introduction of generic delegates in C# 3.0, it is fairly trivial to assign our lambda expressions to generic delegates and pass those delegates to the extension methods.

Generic delegates allow you to define up to 4 parameters and 1 return type so you can have a delegate that may look something like this:
Func<int, bool, string, double, decimal> test;
Read more>>

Expression Lambdas vs Statement Lambdas

Lambda expression is an inline delegate introduced with C # 3.0 language. It’s a concise way to represent an anonymous method. Lambda expressions are particularly helpful for writing LINQ query expressions.

The => operator has the same precedence as assignment (=) and is right-associative.

Expression Lambda

A lambda expression with an expression on the right side is called an expression lambda.

Syntax
(input parameters) => expression

The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:

(x, y) => x == y

Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:

(int x, string s) => s.Length > x

Specify zero input parameters with empty parentheses:

() => SomeMethod()

Statement Lambda

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:

Syntax
(input parameters) => {statement;}

Below example uses expression lambda and statement lambda to find even numbers from a List<int>

        List<int> numbers = new List<int>{1,2,3,4,5,6,7};
        var evens = numbers.FindAll(n => n % 2 == 0);
        var evens2 = numbers.FindAll((int n) => { return n % 2 == 0; });
Read More>>

dotnetperls/lambda

Exploring-Lambda-Expression-in-C#

Expression Lambda example - Find customers in UK

MSDN says "a lambda expression with an expression on the right side is called an expression lambda." Here is an example of Assume you have a List<Customer> where Customer has the following properties.
Customer {
int CustomerId,
string Name, 
string Country, 
string Email,
string Phone
}

If you want to create a List<Customer> where customer country = UK then you can use the below syntax.

List<Customer> ukCustomers =
Customers.FindAll(customer => customer.Country.ToUpper().Equals("UK"))

If you want to do the same thing using LINQ

List<Customer> ukCustomers = from Customer customer in Customers 
                where customer.Country.ToUpper().Equals("UK") 
                select customer 

LINQ query to create Dictionary

Assume you have a List<Customer> where Customer has the following properties.
Customer {
int CustomerId,
string Name, 
string Country, 
string Email,
string Phone
}

If you want to create a Dictionary of all customers who has an email address, i.e. Dictionary then you can use the below syntax.

Dictionary customerEmails = (from Customer customer in customers
                            where string.IsNullOrEmpty(customer.Email)
 select new { customer.CustomerId, customer.Email})
.ToDictionary(customer => customer.CustomerId, customer => customer.Email);

Below example shows how this can be done using Lambda Expression

Dictionary customerEmails =
Customers.FindAll(customer => !string.IsNullOrEmpty(customer.Email))
.ToDictionary(customer => customer.CustomerId, customer.Email);

Tuesday 8 October 2013

C# Versions and features

These are the known versions of C#

  • Visual Studio 2013: No new C# and VB Language Features in VS 2013. But it has new versions of .NET Framework and ASP.NET i.e. .NET Framework 4.5.1 and ASP.NET 4.5.1. Click here to see what is new in VS 2013
  • C# 5.0 released with .NET Framework 4.5 and Visual Studio 2012 (August 2012). Major features: Asynchronous Programming with async and await, caller info attributes.
  • C# 4.0 released with .NET Framework 4 and Visual Studio 2010 (April 2010). Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments and optional parameters
  • C# 3.0 released with .NET Framework 3.5 and Visual Studio 2008 (November 2007). Major new features: LINQ (Language Integrated Query), lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), One-step object creation and initialization, One-step collection creation and initialization, Type Inference, Automatic properties, Func and Action generic delegates
  • C# 2.0 released with .NET Framework 2.0 and Visual Studio 2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks
  • C# 1.2 released with .NET Framework 1.1 and Visual Studio 2003 (April 2003).
  • C# 1.0 released with .NET Framework 1.0 and Visual Studio 2002 (January 2002)

Click here to read about ASP.NET MVC Versions and Features

New features in C# 6

New features in C# 5

Microsoft Visual Studio on Wiki

.NET Framework versions and Dependencies

http://csharpindepth.com/Articles/Chapter1/Versions.aspx

Friday 4 October 2013

Build XML Site Map online

www.xml-sitemaps.com helps you to create an XML sitemap that can be submitted to Google, Bing, Yahoo and other search engines to help them crawl your website better.

You can also generate an HTML site map to allow human visitors to easily navigate on your site.

Tuesday 1 October 2013

How to print part of rendered html page?

This can be done using CSS and JavaScript as well. See examples below.

Print part of the page using CSS

To do it using CSS you need to apply @media specific styles to page content which you want to print and non-printable stuff.

<html>
<head>
    <style type="text/css">

    #printable { display: none; }

    @media print
    {
     #non-printable { display: none; }
     #printable { display: block; }
    }
    </style>
</head>
<body>
    <div id="non-printable">
     Your normal page contents
    </div>

    <div id="printable">
     Printer version
    </div>
</body>
</html>

Print part of the page using JavaScript

To achieve the same functionality using JavaScript you need to use an iframe and set it's innerHTML based on what you want to print.
<html>
<head>
<title>Print Test Page</title>
<script>

function printDiv(divId) {
    window.frames["print_frame"].document.body.innerHTML=
       printDivCSS + document.getElementById(divId).innerHTML
    window.frames["print_frame"].window.focus()
    window.frames["print_frame"].window.print()
}
</script>
</head>
<body>
<b>Div 1:</b> <a href=javascript:printDiv('div1')>Print</a><br>
<div id=div1>This is the div1's print output</div>
<br><br>
<b>Div 2:</b> <a href=javascript:printDiv('div2')>Print</a><br>
<div id=div2>This is the div2's print output</div>
<br><br>
<iframe name=print_frame width=0 height=0 
frameborder=0 src=about:blank></iframe>
</body>
</html>