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 >>