Tuesday, 17 December 2013

Variable scope in ASPX page

When you declare a variable in a Web Forms .aspx file, you’re actually declaring a local variable inside an auto-generated rendering method. ASP.NET generates separate rendering methods for all tags marked runat="server". So for example if you have a variable declared in <head> with runat=server its scope is limited to the <head>.

Read more>>

Tuesday, 3 December 2013

Dealing with Bugs in Test Driven Development(TDD)

Although defect rates can be lower when using TDD, you will still create bugs. These should be corrected with the same three-phase iterations, Red, Green and Refactor. First you create one or more tests that demonstrate the bug by validating the correct behaviour. These tests should fail. Next you fix the code to make the test pass, performing regression testing by executing all of the tests. Once the bug is fixed, you should perform any appropriate refactoring to keep the code clean and readable.

Related articles

What is TDD?

TDD Process

Dealing with bugs in TDD

Test Driven Development (TDD) Process

The TDD process uses very short iterations, each adding a tiny amount of functionality to your software. Each iteration has three phases, described by the TDD mantra, "Red, Green, Refactor". The three phases are:

  • Red. The colour red refers to the colour shown in many automated test runners when a test fails. The idea is that before you write any production code you should write a failing test for that functionality. This often means writing test code that exercises classes or methods that have yet to be created. It is very important that every new test fails. New tests that pass immediately suggest that either the code they test is already present or that the test itself is defective. New tests should be small, aiming to test only a single aspect of the software being developed.
  • Green. The second phase of each iteration is writing code to make the new test pass. The smallest amount of code possible to make the test pass, without causing any existing tests to fail, is added to the project. This may mean creating dummy return values. For example, when creating a method that adds two values, the first test may check that adding two and three returns five. To make this test pass the method could return the fixed value of five, rather than performing an addition. Later tests will ensure that the method works correctly in all situations.
  • Refactor. A very important, though often overlooked, phase is refactoring. After creating a new test and making it pass you should consider the design of the code. Sometimes no refactoring is required. Other times you might change method or property names, or extract methods for a cleaner design. In some cases you may perform major refactoring of the code for an improved design. This is made easier because the existing tests can be run to ensure no bugs are introduced during the changes.

On completion of an iteration you simply start the process again. Usually an iteration is over in minutes, so most of the time you have working, if incomplete, code.

Related articles

What is TDD?

TDD Process

Dealing with bugs in TDD

What is Test Driven Development (TDD)?

  • Test-driven development (TDD) is an iterative development process.
  • The process relies on writing unit tests before creating the code that they validate.
  • The TDD process uses very short iterations, each adding a tiny amount of functionality to your software.
  • Each iteration has three phases, described by the TDD mantra, "Red, Green, Refactor".
  • TDD assists in creating high quality, well designed, loosely coupled and maintainable code that can be refactored with confidence.

Some development practices and methodologies lead to code that grows in complexity over time, with a corresponding decrease in maintainability. You may find that some projects are hard to modify, as adding new features might break existing functionality or cause subtle bugs that are difficult to rectify without introducing further defects. When you encounter such projects it may be difficult to incorporate small changes. Large refactoring operations can be near impossible.

If a project includes a high level of unit test coverage, meaning that most or all of the source code has tests to validate their functionality, it is likely to be easier to maintain. The key reason for this is that, in order to perform high quality testing, the code must be loosely coupled and is more likely to have a better design. In addition, you can confidently make changes to code that has a full set of tests, knowing that those tests will fail if you introduce errors.

Test-driven development (TDD) is an iterative development process that aims to achieve high standards of design, excellent testability of source code and high test coverage for your projects. As the name suggests, the process is driven by the creation of automated unit tests.

Related articles

What is TDD?

TDD Process

Dealing with bugs in TDD

Thursday, 28 November 2013

Accessibililty of "Protected Internal" members of a class

When a class member is declared as Protected Internal it means Protected OR Internal NOT Protected and Internal.

The behaviour of the internal access modifier for class members can be changed by using protected internal. Methods and properties marked as protected internal are hidden from other assemblies except where a class is derived from the class in question. For derived classes in other assemblies, internal methods are still hidden but protected internal methods are visible.

What is the use of a private constructor?

A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

Private constructors are used


When you have a class that should only be created through factory methods. 

When you have overloads of the constructor, and some of them should only be used by the other constructors. 

When you want to prevent the users of your class from instantiating the class directly, Singletons for example

When you want to use it from a static factory method inside the same class

When you want to prevent the runtime from adding an empty constructor automatically.
  public class Complex
    {
        public double real;
        public double imaginary;
 
        public static Complex FromCartesianFactory(double real, double imaginary)
        {
            return new Complex(real, imaginary);
        }
 
        public static Complex FromPolarFactory(double modulus, double angle)
        {
            return new Complex(modulus * Math.Cos(angle), modulus * Math.Sin(angle));
        }
 
        private Complex(double real, double imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }
    }
 
Complex product = Complex.FromPolarFactory(1, Math.PI);
What is the need of private constructor in C#?

When should I use a static constructor?

  • A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
class SimpleClass
{
    
    // Static variable that must be initialized at run time.
    static readonly long baseline;
       
    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed. 
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

MSDN >> Static constructors

MSDN >> C# Language specification >> Static constructors

Static Classes and Static Class Members in C#

Main features of a static class:

  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed and therefore cannot be inherited
  • Cannot contain Instance Constructors. Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.
  • It can contain a static constructor.

Main features of a static member:

  • A non-static class can contain static methods, fields, properties, or events.
  • The static member is callable on a class even when no instance of the class has been created.
  • The static member is always accessed by the class name, not the instance name.
  • Only one copy of a static member exists, regardless of how many instances of the class are created.
  • Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
  • Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
  • Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
  • Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.
  • C# does not support static local variables (variables that are declared in method scope).
  • Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.
  • To access a static class member, use the name of the class instead of a variable name to specify the location of the member.
  • If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
  • A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
Read more>>

How to stop console applications closing automatically?

Your console application will be closed after it finishes executing the last line in your Main() method. So if you want the application to wait until you press enter then add a Console.ReadLine() statement at the end. If you want the app to be closed for any keystroke then use Console.ReadKey()

Simple console that application waits until user presses a key

To run this code create a console application using Visual Studio and replace Program.cs file's contents with below code.

using System;

namespace SimpleConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Type-in some text and press Enter");
            string yourText = Console.ReadLine();
            Console.WriteLine("You entered: {0}", yourText);

            Console.WriteLine("Press any key to continue");

            ConsoleKeyInfo input = Console.ReadKey();

            Console.WriteLine();

            Console.WriteLine("Character pressed: {0}", 
                                                 input.KeyChar);
            Console.WriteLine("Modifiers Used: {0}", 
                                                 input.Modifiers);
            Console.WriteLine("Key Used: {0}", input.Key);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}

Create a Simple Console Application

Console applications are ideal for small tools and utilities where a graphical user interface is unnecessary. With console applications primary input is via the keyboard, either by requesting lines of text or detecting individual key presses.

For testing purposes it’s helpful to create a simple application that can read from or write to a console window.

You create a console application using Visual Studio by selecting the Console Application template when creating a new project.

Console class

The Console class contains a set of static methods and properties that allow you to interact with the user in a console application.

Reading a line of text

To receive this type of input, you can use the ReadLine method. ReadLine creates a buffer that can receive up to 254 characters. As the user types, the buffer is updated. When the user presses Enter, the buffer's content is returned as a string. At this point the program continues from the command following the ReadLine.

Reading a single character

Sometimes you'll only want the user to provide a single key press. For example, you might ask a Yes/No question and wait for the user to press either Y or N in response. For this type of operation you can use the ReadKey method. ReadKey waits for the user to press a key, or a key combination including one or more of the control, alt and shift keys. The user does not need to press Enter afterwards for the method to return.

ReadKey returns a value of the ConsoleKeyInfo structure. This structure includes several properties that permit you to understand which key was pressed. For simple operations you can check the KeyChar property. This returns the character that the single key or keyboard combination produces. If you need more control, you can use the Key and Modifiers properties.

Key returns a ConsoleKey value. ConsoleKey is an enumeration containing constants for all of the keys on a standard keyboard that produce input normally. This includes all letters, numbers and symbols and some control keys such as delete, backspace and return. It doesn't include non-input keys such as control, alt and shift. However, you can check the state of these with the Modifiers property.

Modifiers returns a ConsoleModifiers value. This is another enumeration with values for Control, Alt and Shift. It is a bit field enumeration, so you can detect which of the three keys, if any, was used.

How to stop C# console applications closing automatically?

Your console application is closed when it finishes executing all lines in your program. So if you want the application to wait until you press enter then add a Console.ReadLine() statement at the end. If you want the app to be closed for any keystroke then use Console.ReadKey()

A simple console application

To run this code create a console application using Visual Studio and replace Program.cs file's contents with below code.

using System;

namespace SimpleConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Type-in some text and press Enter");
            string yourText = Console.ReadLine();
            Console.WriteLine("You entered: {0}", yourText);

            Console.WriteLine("Press any key to continue");

            ConsoleKeyInfo input = Console.ReadKey();

            Console.WriteLine();

            Console.WriteLine("Character pressed: {0}", 
                                                 input.KeyChar);
            Console.WriteLine("Modifiers Used: {0}", 
                                                 input.Modifiers);
            Console.WriteLine("Key Used: {0}", input.Key);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}

Wednesday, 27 November 2013

IsNumeric Regular Expression

  
using System.Text.RegularExpressions;
 ...

private bool IsNumeric(string s)
{
       Regex r = new Regex(@"^[0-9]+$");
       return r.IsMatch(s);
}

The regular expression defines a pattern and the IsMatch method checks the string to see if it matches the pattern. You can read the regular expression as follows:

^ – start of the string
[0-9] – single digit in the range 0-9
+ – repeat previous item one or more times (single digit)
$ – end of the string

If you are using below Regex for the same purpose

Regex regex = new Regex(@"^\d+$");

please remember that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9. It is explained here.

Regular Expression to check if a given string is alphabetic

  
using System.Text.RegularExpressions;
 ...

private bool IsAlphabetic(string s)
{
       Regex r = new Regex(@"^[a-zA-Z]+$");
       return r.IsMatch(s);
}

The regular expression defines a pattern and the IsMatch method checks the string to see if it matches the pattern. You can read the regular expression as follows:

^ – start of the string
[a..zA..Z] – single character that is a lowercase or uppercase letter
+ – repeat previous item one or more times (alphabetic character)
$ – end of the string

A string will therefore match if it is a single line of text containing at least one alphabetic character and is limited to alphabetic characters.

What is there in an Assembly?

Generally speaking, an assembly is created as a single project within Visual Studio, or a similar development environment, and compiled into an executable (EXE) file or a dynamic linked library (DLL). An assembly is a file that contains a program in its own right or a library of code, controls, resources or other information that can be utilised by a program.

Assemblies store four types of information. These are:

  1. Assembly Manifest
  2. Type Metadata
  3. Microsoft Intermediate Language (MSIL) Code
  4. Resources

Assembly Manifest

An assembly's manifest contains information that describes the assembly. The following key items are held:

Assembly Name. A simple text string that holds the name of the assembly. This is combined with the assembly's version number, culture and strong name to generate the assembly's identity.

Version Number. The version number is made up of major and minor version numbers and revision and build numbers. This information is used by the .NET framework to ensure that an appropriate version of the assembly is loaded when executing software.

Culture. The culture information for the assembly. This setting is used for globalised applications to determine the language or locale that the assembly supports.

Strong Name. Contains the public key from the software publisher when a strong name has been assigned. Signed assemblies are protected by a digital signature so that the .NET framework can prevent the execution of assemblies that have been modified after compilation. This reduces the risk that viruses and other malicious software could tamper with the contents of the files.

File List. Simple assemblies usually contain only a single file. However, you can create multiple file assemblies. In either case, the list of files within the assembly is hashed and held in this list.

Type Reference Information. Holds information used at run-time that maps a type reference to the file that contains the type declaration and code.

Referenced Assembly Information. Provides a list of other assemblies that are referenced by the current assembly.

Information Attributes. Additional information related to the assembly. These settings include data such as company details for the software vendor, copyright information and product and trademark details. This information is usually configured in the AssemblyInfo.cs file.

Type Metadata

The type metadata information held within an assembly contains details of all of the data types and members that are provided by the assembly. This allows the assembly to describe the compiled code that it contains. This is particularly useful when creating software that uses multiple .NET languages as each language can examine the type metadata and automatically understand the data types that are used. No custom language interoperability code needs to be written in this situation.

Microsoft Intermediate Language Code (MSIL)

The third element of an assembly is the program code. The C# classes that you develop are compiled into the Microsoft Intermediate Language (MSIL). This language is of a lower level than C# but is not fully compiled into machine instructions. The final compilation only occurs at run-time, giving the prospect that the MSIL code can be executed under the .NET Common Language Runtime (CLR) on various platforms including 32-bit and 64-bit Windows and, in some cases, non-Windows operating systems.

A second advantage of MSIL is that the code in an assembly can be utilised by any .NET language. This permits modules developed in C# to be used by Visual Basic and C++ developers for example.

There are disadvantages to the two-part compilation of .NET assemblies. The primary concern for many developers is performance. The additional run-time compilation does cause a noticeable pause when a large program starts and execution speed can be lower than with native code. For developers of packaged software, an additional problem of code security is introduced as code that is not protected can be "decompiled" to the original C# source code. This is alleviated somewhat by the use of code obfuscators. Thirdly, the use of MSIL requires that the appropriate version of the .NET framework be installed on all target systems.

Resources

The final section of an assembly holds its resources. Resources include all of the remaining items required by the assembly that are not included in the code. Examples include images, icons, sounds and localised text.

Read more>>

Google Analytics using C#, without using JavaScript

In case if you want to handle GA tracking using C# instead of using JavaScript here is a solution.

Click here to see the solution

The solution has C# code that does two things

  1. Formats http://www.google-analytics.com/__utm.gif url and querystring
  2. Make a request to www.google-analytics.com using System.Net.WebRequest

This can be handy in following scenarios.
  • When you want to log page views for things that normally' can’t – like web service calls, win forms application usage etc.
  • When you replace page views with Ajax calls, but still want to log the Ajax action as a second page view.
  • If you want to use Google analytics to log non-website information, such as offline transactions, product catalogue statistics or store purchases.

Tuesday, 19 November 2013

How to create a Generic Type Alias?

The using directive of the C# programming language is often used to create namespace aliases, allowing types with matching names that appear in separate namespaces to be easily accessed. A lesser known use of the directive is to create aliases for types.

NOTE: the using directive adds the alias for the scope of the file in which it appears. You cannot use a using directive to create global aliases that work across your projects or solutions.

Generic Type Aliases

You can create aliases for generic classes, as long as your provide specific types for the type parameters.

Example
using Foo = System.Collections.Generic.KeyValuePair<int, string>;

class Sample { Foo x; }

When you create an alias for a generic type, you cannot leave the type open. All of the type parameters must be resolved within the using directive. The following code breaks this rule by attempting to create an alias with a changeable type parameter.

Below code will not compile.
using Foo = System.Collections.Generic.KeyValuePair<T, K>

Type Aliases

Following code creates an alias for the StringBuilder class

using SB = System.Text.StringBuilder;

// Then you can create an instance of StringBuilder using below statement.

SB stringBuilder = new SB();

Useful links>>

using Directive - MSDN

Type Aliases

How to loop through characters in a string?

This can be done using a foreach loop.

Following example finds the count of letters in a given string.

int count = 0;

string str = "Welcome to C#!";

foreach(char c in str) {
  if(char.IsLetter(c)) {
    count++;
  }
}

Cosole.WriteLine(count.ToString());
There are additional static methods on char that will tell you if the character in question is punctuation, a digit, etc.

How to convert a char to lower case in C#?

Char.ToLower Method

The method returns lowercase equivalent of given character, or the unchanged value, if the char is already lowercase or not alphabetic.

Example
Char.ToLower('A')

Tuesday, 5 November 2013

Create your own helper functions in ASP.NET MVC

Razor’s @helper syntax has made it pretty easy to create your own helper functions for use in your views. For example open your ".cshtml" file and add the following code directly after the @model line.

@helper Truncate(string
input, int length)
 {
    if (input.Length <= length) {
        @input
    } else {
        @input.Substring(0, length)...
    }
} 

This helper method takes a string and a maximum length to allow. If the text supplied is shorter than the length specified, the helper outputs it as-is. If it is longer, then it truncates the text and renders “…” for the remainder.

Now you can refer the Truncate method in your view. So if your Model has a Title property

@Truncate(Model.Title, 25)

Read more>>

Make the helper method accessible to all views by defining it in a CSHTML file under App_Code folder. Click here to read more >>

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>

Thursday, 1 August 2013

LINQ Basics

LINQ (Language Integrated Query, pronounced "link") is a Microsoft .NET Framework component that adds native data querying.)

Linq is the Microsoft's first attempt to integrate queries into language. We know, it is really easy to find data from sql objects simply writing a query while its somewhat hectic when we want to do the same thing in a DataTable or Lists. Generally we will have to loop through every elements to find the exact match, if there is some aggregation we need to aggregate the values etc. Linq provides an easy way to write queries that can run with the in memory objects.

Linq provides an easy way to write queries that can run with the in memory objects.

Example: (from item in itemlist where item.value = somevalue select item).toList();

Types of LINQ

    Linq comes with 3 basic types (Provided there are lots of more types of LINQ on different type of objects :

  1. LINQ (Linq to Objects)

    Linq To Objects - examine System.Linq.Enumerable for query methods. These target IEnumerable, allowing any typed loopable collection to be queried in a type-safe manner. These queries rely on compiled .Net methods, not Expressions.

  2. DLINQ (Linq to SQL)
  3. XLINQ (Linq to XML)

LINQ Operators

  • Restriction Operator
    Where
  • Projection Operator
    Select
  • Partition Operators
    Take, Skip, TakeWhile, SkipWhile
  • Ordering Operators
    OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
  • Grouping Operators
    GroupBy
  • Set Operators
    Distinct, Union, Intersect, Except
  • Conversion Operators
    ToArray, ToList, ToDictionary, OfType
  • Element Operators
    First, FirstOrDefault, ElementAt
  • Generation Operators
    Range, Repeat
  • Quantifiers
    Any, All
  • Aggregate Operators
    Count, Sum, Min, Max, Average, Aggregate
  • Miscellaneous Operators
    Concat, EquallAll
  • Custom Sequence Operators
    Combine
  • Query Execution
    Deferred, Immediate, Query Reuse
  • Join Operators
    Cross Join, Group Join, Cross Join with Group Join, Left Ounter join

101 LINQ Samples
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

LINQ to Objects

http://www.codeproject.com/KB/dotnet/LINQ.aspx

http://www.codeproject.com/KB/cs/InsideAnonymousMethods.aspx

What is Language-Integrated Query - LINQ?

LINQ Query Expressions

Wednesday, 31 July 2013

?? Operator in C#

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

int? x = null;
// y = x, unless x is null, in which case y = -1. 
int y = x ?? -1;

Useful links

Nullable Types

?? Operator

The C# ?? null coalescing operator (and using it with LINQ)

Wednesday, 24 July 2013

Windows Keyboard Shortcuts

Calculator Keyboard Shortcuts

Press this key To do this
Press this key

Alt+1

To do this

Switch to Standard mode

Press this key

Alt+2

To do this

Switch to Scientific mode

Press this key

Alt+3

To do this

Switch to Programmer mode

Press this key

Alt+4

To do this

Switch to Statistics mode

Press this key

Ctrl+E

To do this

Open date calculations

Press this key

Esc

To do this

Press the C button

Full list is available here
http://windows.microsoft.com/en-gb/windows/keyboard-shortcuts#keyboard-shortcuts=windows-7

Visual Studio Keyboard Shortcuts

A good collection of keyboard shortcuts for Visual studio is available @ http://www.shortcutworld.com/en/win/Visual-Studio_2010.html

Monday, 22 July 2013

Unit Testing JavaScript

What is QUnit?

QUnit is a powerful, easy-to-use JavaScript unit testing framework.

Getting Started

A minimal QUnit test setup:

<!DOCTYPE html>
<html:gt;
<head:gt;
<meta charset="utf-8">
<title>QUnit Example</title>
<link rel="stylesheet" href="/resources/qunit.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="/resources/qunit.js"></script>
<script src="/resources/tests.js"></script>
</body>
</html>

The contents of tests.js:

test( "hello test", function() {
  ok( 1 == "1", "Passed!" );
});
Useful links

qunitjs.com

http://qunitjs.com/intro/

Wednesday, 17 July 2013

How to open link in a new tab in iPad

To open a link in a new tab, long-press that link. Choose the command "Open in New Tab" from the menu that appears.

How to force links in Blogger to open In New Tab

By default, all links and hyperlinks in Blogger opens in your current window. To change this behavior follow these steps
  1. Login to your Blogger account
  2. Navigate to TEMPLATE > Edit HTML
  3. Search for the tag in your template’s code. Hint: Use Ctrl+F to find the code.
  4. Copy the code below and Paste it below the tag

    <base target='_blank'/>

  5. Hit the "save template" button and you are done.

Wednesday, 10 July 2013

Cookies: Frequently Asked Questions

What is a cookie?

A cookie is a piece of information in the form of a very small text file that is placed on an internet user's hard drive. It is generated by a web page server, which is basically the computer that operates a web site. The information the cookie contains is set by the server and it can be used by that server whenever the user visits the site. A cookie can be thought of as an internet user's identification card, which tell a web site when the user has returned.

History of cookies

Cookies for the internet were originally developed in 1995 by the Netscape Communications Corporation. The word 'cookie' comes from 'magic cookie,' a term in programming languages for a piece of information shared between co-operating pieces of software. The choice of the word cookie appears to come from the American tradition of giving and sharing edible cookies.

What is the purpose of cookies?

Cookies make the interaction between users and web sites faster and easier. Without cookies, it would be very difficult for a web site to allow a visitor to fill up a shopping cart or to remember the user's preferences or registration details for a future visit.

Web sites use cookies mainly because they save time and make the browsing experience more efficient and enjoyable.

Web sites often use cookies for the purposes of collecting demographic information about their users.

Cookies enable web sites to monitor their users' web surfing habits and profile them for marketing purposes (for example, to find out which products or services they are interested in and send them targeted advertisements).

Are there different types of cookies?

Cookies come in different flavours: Session, or transient cookies

Session cookies

Cookies that are stored in the computer's memory only during a user's browsing session and are automatically deleted from the user's computer when the browser is closed.

These cookies usually store a session ID that is not personally identifiable to users, allowing the user to move from page to page without having to log-in repeatedly. They are widely used by commercial web sites (for example, to keep track of items that a consumer has added to a shopping cart).

Session cookies are never written on the hard drive and they do not collect any information from the user's computer. Session cookies expire at the end of the user's browser session and can also become no longer accessible after the session has been inactive for a specified length of time, usually 20 minutes.

Permanent, persistent, or stored cookies

Cookies that are stored on the user's computer and are not deleted when the browser is closed. Permanent cookies can retain user preferences for a particular web site, allowing those preferences to be used in future browsing sessions.

Permanent cookies can be used to identify individual users, so they may be used by web sites to analyse users' surfing behaviour within the web site. These cookies can also be used to provide information about numbers of visitors, the average time spent on a particular page and generally the performance of the web site. They are usually configured to keep track of users for a prolonged period of time, in some cases many years into the future.

Find out more

Thursday, 4 July 2013

ASP.NET Javascript Encode on server side

NET Framework Version 4.0 and above and has a method called

HttpUtility.JavaScriptStringEncode()

which can be used to encode string values for JavaScript. It is a handy method which will take care of all special characters in the string including new line characters. http://msdn.microsoft.com/en-us/library/dd991914.aspx

http://itmeze.com/2011/03/21/javascript-encode-on-server-side-medium-trust-environment/

Underscore or this - C# best practices

Background

C# and .NET have been around for a long time now and the standards and abilities of the language just keep getting better and better. However there is no getting away that some of the more core principles of this language originated from C and C++ created many many years ago. When C and C++ was first created tools were basic and the IDEs around were not very advanced and often programs were coded in notepad or similar tools. For speed and productivity common conventions came about that allowed developers identify code easier.

  • Prefixing the type on to a variable e.g. intAge
  • Adding underscores to internal class variables to indicate they are as such

These were perfectly fine back in the day when working with poor tools but now with Visual Studio and all of the features we have in modern IDEs a lot of this has changed

Underscore vs this keyword

Now comes my main gripe of standards that seem to be lingering on and one, mostly from C and C++ developers and incorrect information. C# has a keyword that has been in it a long time call the ‘this’ keyword which has the following benefits/features

  • Indicates that something you are accessing is from the instance of the class you are using
  • As soon as you type it Intellisense is narrowed down to only instance level code constructs

This feature has been built in to the language and Visual Studio to support having a keyword to replace the need to use anything artificial.

But Microsoft use underscore argument

I have the above argument as a reason why we should be using underscores but here is my responses/reasons why they are wrong

  • Their argument is based upon underscore in the source code. If you look at newer source code (.NET4)
  • There is far less use of underscores
  • Coding everywhere uses ‘this’ keyword
  • Looking on forums you can find Microsoft employees stating that they do not use underscores but still some of the developers that have been around a long time do
  • http://msdn.microsoft.com/en-us/library/ms229045(v=vs.100) which shows .NET 4 suggest conventions lists
  • Do not use underscores, hyphens, or any other nonalphanumeric characters. as one of the standards, so Microsoft are most definitely not suggesting the use of underscores
  • Why the hell would they add the ‘this’ keyword if it wasn’t to be used
  • Stylecop the internal tool created by Microsoft to check code for standards compliance doesn’t like underscores but likes the ‘this’ keyword

Summary

As you can tell I hate underscores and developers trying to tell me it’s clever when it clearly isn’t. We aren’t in the coding dark ages anymore so there isn’t any reason to name things non logically with random crap characters all over the place. The ‘this’ keyword was added in to the language for a reason so use it. Basically if I see code with underscore I will assume your old or ignorant.

Thanks to http://scottreed.eu/csharp/underscore/

Wednesday, 6 March 2013

Cross-browser mouse positioning

Understanding differences between the mouse position event properties, and how to normalize them between browsers.

Mouse Event Properties

clientX, clientY

Standard: W3C Recommendation
Mouse position relative to the browser's visible viewport.

screenX, screenY
Standard: W3C Recommendation
Mouse position relative to the user's physical screen.

offsetX, offsetY
Mouse position relative to the target element. This is implemented very inconsistently between browsers.

pageX, pageY
Mouse position relative to the html document (ie. layout viewport).

Normalization

Calculating pageX, pageY

The only major browser that does not support these properties is IE8. If you are doing event handling with jQuery, it will automatically normalize pageX and pageY for you. If you are not using jQuery's normalized events but still have access to the jQuery, you can use jQuery.event.fix to normalize the event object. Example:

document.body.onclick = function(e) {
    e = e || window.event;
    e = jQuery.event.fix(e);
    console.log([e.pageX, e.pageY]);
};

Without jQuery, the clientX and clientY properties can be added to the viewports scrollLeft and scrollTop to calculate the pageX and pageY values.

document.body.onclick = function(e) {
    e = e || window.event;

    var pageX = e.pageX;
    var pageY = e.pageY;
    if (pageX === undefined) {
        pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    console.log([pageX, pageY]);
};

Calculating offsetX, offsetY

According to the W3C Working Draft, offsetX and offsetY should be relative to the padding edge of the target element. The only browser using this convention is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does not support the properties.

Normalizing to the border edge is easiest to do, thanks to the nifty element.getBoundingClientRect:

document.body.onclick = function(e) {
    e = e || window.event;

    var target = e.target || e.srcElement,
        rect = target.getBoundingClientRect(),
        offsetX = e.clientX - rect.left,
        offsetY = e.clientY - rect.top;

    console.log([offsetX, offsetY]);
};

If you wanted to normalize to the W3C draft spec, then the border width needs to be subtracted from the previously calculated offsetX and offsetY:

document.body.onclick = function(e) {
    e = e || window.event;

    var target = e.target || e.srcElement,
        style = target.currentStyle || window.getComputedStyle(target, null),
        borderLeftWidth = parseInt(style['borderLeftWidth'], 10),
        borderTopWidth = parseInt(style['borderTopWidth'], 10),
        rect = target.getBoundingClientRect(),
        offsetX = e.clientX - borderLeftWidth - rect.left,
        offsetY = e.clientY - borderTopWidth - rect.top;

    console.log([offsetX, offsetY]);
};

Read more about "Mouse Event Properties" here

Read more about view ports here

Friday, 15 February 2013

The challenges of supporting mobile devices today

Even though mobile browsers now almost universally support HTML, you will still face many challenges when aiming to create great mobile browsing experiences:

  • Screen size - Mobile devices vary dramatically in form, and their screens are often much smaller than desktop monitors. So, you may need to design completely different page layouts for them.
  • Input methods – Some devices have keypads, some have styluses, others use touch. You may need to consider multiple navigation mechanisms and data input methods.
  • Standards compliance – Many mobile browsers do not support the latest HTML, CSS, or JavaScript standards.
  • Bandwidth – Cellular data network performance varies wildly, and some end users are on tariffs that charge by the megabyte.

There’s no one-size-fits-all solution; your application will have to look and behave differently according to the device accessing it. Depending on what level of mobile support you want, this can be a bigger challenge for web developers than the desktop “browser wars” ever was.

Developers approaching mobile browser support for the first time often initially think it’s only important to support the latest and most sophisticated smartphones (e.g., Windows Phone 7, iPhone, or Android), perhaps because developers often personally own such devices. However, cheaper phones are still extremely popular, and their owners do use them to browse the web – especially in countries where mobile phones are easier to get than a broadband connection. Your business will need to decide what range of devices to support by considering its likely customers. If you’re building an online brochure for a luxury health spa, you might make a business decision only to target advanced smartphones, whereas if you’re creating a ticket booking system for a cinema, you probably need to account for visitors with less powerful feature phones.

http://www.asp.net/whitepapers/add-mobile-pages-to-your-aspnet-web-forms-mvc-application

Friday, 18 January 2013

Using back-references in IIS rewrite rules

Parts of rules or conditions inputs can be captures in back-references. These can be then used to construct substitution URLs within rules actions or to construct input strings for rule conditions.

Back-references are generated in different ways, depending on which kind of pattern syntax is used for the rule. When an ECMAScript pattern syntax is used, a back-reference can be created by putting parenthesis around the part of the pattern that must capture the back-reference. For example, the pattern ([0-9]+)/([a-z]+)\.html will capture 07 and article in back-references from this requested URL: 07/article.html. When “Wildcard” pattern syntax is used, the back-references are always created when an asterisk symbol (*) is used in the pattern. No back-references are created when “?” is used in the pattern. For example the pattern */*.html will capture contoso and test in back-references from this requested URL: contoso/test.html.

Usage of back-references is the same regardless of which pattern syntax was used to capture them. Back-references can be used in the following locations within rewrite rules:

  • In condition input strings
  • In rule actions, specifically:
    • url attribute of Rewrite and Redirect action
    • statusLine and responseLine of a CustomResponse action
  • In a key parameter to the rewrite map

Back-references to condition patterns are identified by {C:N} where N is from 0 to 9. Back-references to rule patterns are identified by {R:N} where N is from 0 to 9. Note that for both types of back-references, {R:0} and {C:0}, will contain the matched string.

For example, in this pattern:

^(www\.)(.*)$

For the string: www.foo.com the back-references will be indexed as follows:

{C:0} - www.foo.com

{C:1} - www.

{C:2} - foo.com

Within a rule action, you can use the back-references to the rule pattern and to the last matched condition of that rule. Within a condition input string, you can use the back-references to the rule pattern and to the previously matched condition.

The following rule example demonstrates how back-references are created and referenced:

<rule name="Rewrite subdomain">
<match url=”^(.+)” > 
<conditions>
<add input="{HTTP_HOST}" type=”Pattern” pattern="^([^.]+)\.mysite\.com$"> 
</conditions>
<action type=”Rewrite” url="{C:1}/{R:1}" /> 
</rule>

Click here to read more about IIS rewrite rules