Category Archives: C# .Net

globalization

Definition:

            Globalization is the process of designing and developing an application that supports localized user interfaces and regional data for users in multiple cultures. In the .NET Framework, the CultureInfo class represents information about a specific culture. This information includes the writing system, calendars in use, date and time formatting conventions, numeric and currency conventions, and sorting rules.

 

The System.Globalization namespace contains classes that define culture-related information, including

*      Language

*      Country/region

*      Calendars in use,

*      Format patterns for dates,

*      Currency, and numbers,

*      And the sort order for strings.

Use these classes to simplify the process of developing a world-ready application. By passing a CultureInfo object representing the current culture to methods in this namespace, you can initiate the correct set of rules and data for the current user’s culture.

Web site globalization refers to enabling a web site to deal with non-English speaking visitors, i.e. internationalizing the site’s back-end software, designing a multi-lingual architecture, and localizing the site’s static or dynamic content.

 

What is the difference between globalization and localization?

 

  • Globalization is the process of making a product multi-lingual. All language-related aspects of the program are separated from the code, and all aspects, which vary with target country, are handled in a country-independent way.
  • Localization is the process of adapting a global product for a particular language and country. Localization includes translations and other conversion, and takes into account local practices and culture, providing a product, which is comfortable to use in the target country.
  • Translation is involved in most aspects of localization. Accuracy and appropriateness of translation are key to overall product quality.
  • Retrofitting is an informal term for localization of a product, which was not designed to be global. It is the first step taken by most companies entering the global marketplace.
Advertisements

dot Net Framework

Definition:

            This is the environment for building, deploying and running Web Services and other applications. It contains three main parts

·          CLR

·          Framework Classes

·          unified class libraries

 

Common Language Runtime (CLR):

            The common language runtime is the execution engine for .NET Framework applications. It provides a number of services, including the following:

o    Code management (loading and execution)

o    Application memory isolation

o    Verification of type safety

o    Conversion of IL to native code

o    Access to metadata (enhanced type information)

o    Managing memory for managed objects

o    Enforcement of code access security

o    Exception handling, including cross-language exceptions

o    Interoperation between managed code, COM objects, and pre-existing   DLLs (unmanaged code and data)

o    Automation of object layout

o    Support for developer services (profiling, debugging, and so on)

       CLS and CTS are there in CLR.

 

Common Language Specification (CLS):

            It is the set of guidelines for the language supporting the CLS to follow, so that it can communicate with other .NET languages in a seamless manner. The CLS is a set of constructs and constraints that serves as a guide for library writers and compiler writers.

 

Common Type System (CTS): 

            The common type system is a rich type system, built into the common language runtime that supports the types and operations found in most programming languages.

 

Types of Application in .Net Frame work

o    Console application

o    Windows Application

o    Web application

o    Class library

User control

C# Glassaries

Meta Data:

            Definition:

                        It contains the data about the object that is the Name of an object, the bases, interfaces implemented in that object and also the types and members of an object etc. 

Manifest:

            Definition:

                        It contains the information about the assembly like identity of an assembly, Scope of the assembly and also contains the security permissions.

 JIT Compiler:

            Definition:

                        During Run Time, the CLR invokes the JIT compiler to convert the MSIL into Native code (i.e. Executable Binary Code). When the Function is called, the IL of the function’s body is converted to Native code Just In Time.

            Types:

    • PreJIT
    • EconoJIT
    • Standard JIT

Class:

Definition:

            Class is the collection of object and it will contain member variables and member functions.

List of Classes available:

            Static class: Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state

            Sealed class: Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.

            Abstract class: Abstract class can simply defined as incomplete class. It contains one or more incomplete methods called abstract methods. It leaves the implementation of these methods to derived or sub classes. Since abstract classes are incomplete, they can not be instantiated        

Polymorphism:

Definition:

            It means “Ability to take more than one form”. An operation may exhibit different behavior and different instances. Behavior is depends upon the operation.

 

Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name.

Types:

1.       Compile Time Polymorphism

2.       Runtime Polymorphism

Implementation:

            Compile time polymorphism is done by functions and operators overloading.

            Runtime time polymorphism is done using inheritance and virtual functions.

Assemblies:

            Definition:

                        It is the building block of an application which provides all required execution information to “CLR” and also the Assembly is physical grouping of logical units.

  Types:

  •  Public Assembly

This is used by multiple applications and this is stored in Global Assembly Catch (GAC). We have to give cryptographically Strong Name for these shared assemblies.

  • Private Assembly:

This is used by a single application and this assembly is stored in that application installation folde

See more Here

 

 

Find whether the class inherited from a particular interface

/* interface and ‘is’ operator*/

Definition:
By using ‘is’ operator we can find that, whether the class is inherited from a particular interface/class.

EXAMPLE 1:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace LearningConcepts
{

interface INode
{

string Text
{
get;
set;
}

object Tag
{
get;
set;
}

int Height
{
get;
set;
}

int Width
{
get;
set;
}

float CalculateArea();

}

public class Node : INode
{

public Node()
{ }
public string Text
{
get {return m_text;}
set {m_text = value;}
}

private string m_text;
public object Tag
{

get{return m_tag;}
set{m_tag = value;}

}

private object m_tag = null;
public int Height
{

get {return m_height;}
set {m_height = value;}

}

private int m_height = 0;
public int Width
{
Get {return m_width;}
Set {m_width = value;}

}

private int m_width = 0;
public float CalculateArea()
{

if ((m_width < 0) || (m_height < 0))
return 0;

return m_height * m_width;

}

}
class ClonableNode :ICloneable
{
public object Clone()
{
return null;
}

// INode members
}

class Program
{
static void Main(string[] args)
{
Node nodeC=new Node();
if (nodeC is INode)
Console.WriteLine(“nodeC is object of INode type”);
//this will be displayed
else
Console.WriteLine(“nodeC isn’t object of INode type”);
}
}
}

Reflection

10. Reflection

 

Definition:

            We can access some data about object at runtime by using Reflection.

That information contain

·          Data of the class

·          Names of the Methods that are inside the class

·          Constructor of that Object.

To write a C# .Net program this uses reflection,

                        The program should use the namespace System.Reflection.

To get type of the object,

                         The typeof operator can be used.                                

             There is one more method GetType ().

          uses to get data about object’s type

By using Reflection we can do the following

·         Can get all methods from a class

·         Can get all Fields and Properties from a class

·         Can get information about assembly

·         Can create instance for a class

·         Can execute a class method indirectly

·         Can get type information: base type, is abstract, is com object, is sealed, is class

·         Can get all implemented interfaces and inherited base classes 

Oops Concepts

7. Oops Concepts

ABSTRACT CLASS:

            Abstract class can simply defined as incomplete class. It contains one or more incomplete methods called abstract methods. It leaves the implementation of these methods to derived or sub classes. Since abstract classes are incomplete, they can not be instantiated.

They must be sub-classed in order to use their functionality. So the abstract class can not be sealed. We can declare a reference of the type of abstract class and it can point to the object of the class that has inherited the abstract class.

We can add more functionality in abstract class without destroying child classes that were using old class.

Abstract class class_name

{                              

                                 // Constructor, constructor overloading and static constructor definition

                                 // Abstract method declaration;

                                 // Variable declaration;

                                 // Ordinary method declaration with their definition;

                                 // Static and virtual method declaration with their definition;

}

Few things about abstract class

*    Abstract class having declaration for abstract method.

*    You should define the abstract method using override keyword.

*    Abstract class support ordinary constructor, static constructor and constructor overloading.

*    Except private, all the access modifiers are allowed.

*    Ordinary methods will be having the definition part.

*    To declare the variables.

*    Static and virtual methods also to allow.

*    You can declare the interface inside the abstract class.

*    You should inherit the abstract class in derived class.

*    You can’t inherit more than one abstract class in derived class.

*    You can’t create the object for the abstract class, but you can create the reference for the abstract class.

SEALED CLASS:

            Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.

STATIC CLASS:

The main features of a static class are:

·         They only contain static members.

·         They cannot be instantiated.

·         They are sealed.

·         They cannot contain Instance Constructors

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state

STATIC CONSTRUCTOR:

            It is possible to write a static no-parameter constructor for a class. One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used. It will be called automatically before the first instance is created.

Use of Static constructors:

*    Static constructor is used to initialize static data.

*    To perform particular action that needs performed once only

*    Another use of static constructor is, when the class is using a log file and the constructor is used to write entries to this file.

PRIVATE CONSTRUCTOR:

            A class can have private constructor also. It prevents the class from being instantiated by callers.

There are some cases where the private constructors can be useful:

*    Class containing only static utility methods

*    To implement singleton class.

POLYMORPHISM:

Definition:

It means “Ability to take more than one form”. An operation may exhibit different behavior and different instances. Behavior is depends upon the operation.

Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name.

Types:

1.      Compile Time Polymorphism

2.      Runtime Polymorphism

Compile Time Polymorphism:

            Compile time polymorphism is functions and operators overloading.

Runtime polymorphism:

            Runtime time polymorphism is done using inheritance and virtual functions.

Overloading:

               Two or more methods within the same class can share the same name, as long as their parameter declarations are different.
*    number of parameters
*    type of parameters
Overriding:

            Mainly the overriding is to achieve Runtime Polymorphism. It allows a subclass to re-define a method it inherits from its super class

·If the super class method is public, the overriding method must be public
·If the super class method is protected, the overriding method may be protected or public
·If the super class method is package, the overriding method may be package, protected, or public
·If the super class methods is private, it is not inherited and overriding is not an issue

 

Overloading Vs. Overriding:

*    Overloading is nothing but static binding.

*    Overriding is dynamic binding which will be resolved at run-time.

 

*    Overloading deals with multiple methods in the same class with the same name but different signatures.

*    Overriding deals with two methods, one in a parent class and one in a child class, which have the same signature.

 

*    Overloading lets you define a similar operation in different ways for different data.

*    Overriding lets you define a similar operation in different ways for different object types.

Dynamic Binding/Late Binding:

                        It means that the code associated with a given procedure Call at Runtime.

Static Binding:

               It means that the code associated with a given procedure call during compile time itself.

VIRTUAL FUNCTION:

A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class according to the requirement. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods (polymorphism).

The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.

Comparison of interface with class (interface vs. class):

  • An interface cannot inherit from a class.
  • An interface can inherit from multiple interfaces.
  • A class can inherit from multiple interfaces, but only one class.
  • Interface members must be methods, properties, events, or indexers.
  • All interface members must have public access (the default).
  • By convention, an interface name should begin with an uppercase I.

Using and Using Alias

6. Using & Using Alias

 

The using directive has two uses:

  • To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

Using System.Text; // Using Directives

All of the members defined within name of a Namespace are brought into view and can be used without qualification.

  • To create an alias for a namespace or a type. This is called a using alias directive.

Using Project = PC.MyCompany.Project; //Using Alias

The using keyword is also used to create using statements, which help ensure that IDisposable objects such as files and fonts are handled correctly.

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Using has a second form that is called the using statement.

It has these general forms:

Using (obj) {//Using Statement

    // use obj

    }   

    Using (type obj = initializer) {

    // use obj

    }

 

Obj is an object that is being used inside the using block. In the first form, the object is declared outside the using statement. In the second form, the object is declared within the using statement. When the block concludes, the Dispose () method (defined by the System.IDisposable interface) will be called on obj. The using statement applies only to objects that implement the System.IDisposable interface.

Example

Font font2 = new Font (“Arial”, 10.0f);

Using (font2) // not recommended

{

    // use font2

}

// font2 is still in scope

// but the method call throws an exception

Float f = font2.GetHeight ();

Notes:

*    The scope of a using directive is limited to the file in which it appears.

*    Create a using alias to make it easier to qualify an identifier to a namespace or type.

*    Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.

*    Namespaces come in two categories: user-defined and system-defined. User-defined namespaces are namespaces defined in your code. For a list of the system-defined namespaces, see .NET Framework Class Library Reference.

C# Namespaces

C# .Net Namespaces

Namespace:

          Namespace is logically group’s classes. Namespace can span in multiple assemblies.

Namespaces and its usage:

     System is the basic namespace for .Net Framework. It is having the following Namespaces

  1. Collections: The .NET Framework provides specialized classes for data storage and retrieval.   These classes provide support for stacks, queues, lists, and hash tables.
  2. ComponentModel: The ComponentModel namespace provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components.
  3. Configuration: The Configuration namespace contains the types that provide the programming model for handling configuration data.
  4. Data: The Data namespace provides access to classes that represent the ADO.NET architecture. ADO.NET lets you build components that efficiently manage data from multiple data sources.
  5. Diagnostics: It Contains classes that enable you to debug and follow the execution of your applications.
  6. DirectoryServices: It Provides access to Active Directory services. Drawing Contains classes that enable you to use basic, graphical display interface (GDI) capabilities.
  7. EnterpriseServices: This Namespace Contains objects that enable you to control how components behave on a server.
  8. Globalization: This Namespace Contains classes that define culture-related information.
  9. IO: This Namespace Contains classes that enable you to read and write to data streams and files.
  10. Media: The Media namespace contains classes for playing sound files and accessing sounds provided by the system.
  11. Net: This Namespace Provides classes to work with network protocols.
  12. Reflection: This Namespace Contains classes that enable you to view information about other types in the .NET Framework.
  13. Resources: This Namespace Contains classes that enable you to manage culture specific resources.
  14. Runtime: This Namespace contains advanced types that support diverse namespaces.
  15. Security: The Security namespace provides the underlying structure of the common language runtime security system, including base classes for permissions.
  16. Text: The Text namespace contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String.
  17. Threading: This Namespace Contains classes that enable multi-threaded programming.
  18. Timers: This Namespace Contains classes to raise events on specified time intervals.
  19. XML: This Namespace contains the classes to work with XML file.

Just in time compiler

3. Just In Time Compiler (JIT)

 

               During Run Time, the CLR invokes the JIT compiler to convert the MSIL into Native code (i.e. Executable Binary Code). When the Function is called, the IL of the function’s body is converted to Native code Just In Time. So the part of code that is not used by the particular run is never converted to native code. If some IL is converted to native code, the next time it’s needed, the CLR reuses the same copy without re-compiling.

Types of JIT:

·   PreJIT

·   EconoJIT

·   Standard JIT

(1) PRE JIT: It Compiles complete source code to native code in a single Compilation.
(2) ECONO JIT: It compiles only those methods that are called at Runtime.
(3) NORMALE JIT: It compiles only those methods that are called at Runtime and are stored in cache.

ASSEMLIES

Definition:

            It is the building block of an application which provides all required execution information to “CLR”.

Functions of an Assembly:

à    It contains IL that gets executed by CLR

à    It forms the security boundaries

à    It allows the side – by –side execution of multiple version of same assembly.

Features of assemblies

·        Assemblies are self-describing.

·        Version dependencies are recorded inside an assembly manifest.

·        Assemblies can be loaded side-by-side.

·        Application isolation is endured using application domains.

·        Installation can be as easy as copying the files that belong to an assembly.
Assemblies can be private or shared.

Assembly Contains

1.      Manifest:

It contains the information about the assembly like identity of an assembly, Scope of the assembly and also contains the security permissions.

2.      Metadata

It contains the data about the object that is Name of an object, the bases, interfaces implemented in that object and also the types and members of an object.

3.      IL code

Compiled version of an application Program code

4.      Resources

Resources used by that Assembly.

Namespace and Assembly

                        Assembly is physical grouping of logical units but Namespace logically groups classes. Namespace can span in multiple assemblies.

Types of an Assembly          

            There are two types                 

1.      Private Assembly

This is used by a single application and this assembly is stored in that application installation folder.

2.      Shared Assembly

This is used by multiple applications and this is stored in Global Assembly Catch (GAC). We have to give cryptographically Strong Name for these shared assemblies.

Strong Name:

            A strong name is a .NET assembly name combined with its version number and other information to uniquely identify the assembly. This allows multiple versions of the same assembly to peacefully co-exist in the global assembly cache, where shared assemblies are typically stored.

       Three main goals for having strong name    

1.      Name Uniqueness:

Name of shared assemblies should be unique globally.

2.      Prevent Name Spoofing:

Developer doesn’t want some one releasing the version of their assemblies. We can avoid this problem by using strong name.

3.      Provide identity on Reference:

 While resolving reference to an assembly, strong name guarantees that the loaded assembly came from the expected publisher.

Use of strong names

Strong names are required to store shared assemblies in the global assembly cache (GAC). This is because the GAC allows multiple versions of the same assembly to reside on your system simultaneously, so that each application can find and use its own version of your assembly. This helps avoid DLL Hell, where applications that may be compiled to different versions of your assembly could potentially break because they are all forced to use the same version of your assembly.

Another reason to use strong names is to make it difficult for hackers to spoof your assembly, in other words, replace or inject your assembly with a virus or malicious code.

Strong name key file

A strong name key file has a .snk extension and contains a unique public-private key pair. You use the strong name key file to digitally sign your assembly (see below). Note that this type of file is not secure, as the private key in a .snk file can be easily compromised.

For added protection, Visual Studio can encrypt a strong name key file, which produces a file with the .pfx (Personal Information exchange) extension. The .pfx file is more secure because whenever someone attempts to use the encrypted key, she will be prompted for the password.

Steps for Giving strong name to DLL

  1. Open .net command prompt.
  2. Go to the folder containing DLL.
  3. Type sn -k test.snk, you can use any file name instead of test. This will create test.snk file in that folder.
  4. Open the assemblyinfo.cs file of project.
  5. Type file path  in this tag [assembly:AssemblyKeyFile@”E:\hemant\practice\HP\bin\Debug\HP.snk”)]
  6. Build application, finally your strong name created for your DLL.

Signing an Assembly

The first thing that you need to do is create a public/private key pair that will be used to encrypt the assembly.

To create a key/pair you can use the strong name utility:

sn –k <file name>

This will create the file containing the keys defaulting to RSA encryption. You should keep this file save as you will need it for signing future assemblies if you wish to keep them authenticated.

Now, there are a few different methods for strongly naming an assembly, either from within Visual Studio or through the command line.

If you wish to give developers access to the private key you can simply add in an attribute to the project. This code should go within the AssemblyInfo.cs file.

[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile(“c:\\mykey.snk”)]

If you do not wish to give your developers access to your private key you can delay sign the assembly.

[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile(“c:\\mykey.snk”)]

Then the assembly must have verification turned off otherwise the assembly will not load on the developer’s machine:

c:\> sn -Vr myassembly.dll

Finally, when the code is ready to be released you can fully sign the assembly using the sn.exe tool.

c:\> sn -R myassembly.dll mykey.snk

 Signing and Delay Signing

            Delayed signing refers to a technique of partially signing assemblies while they are in development. Signing an assembly basically certifies that assembly by the manufacturer and prevents tampering and hi-jacking of that assembly. The signing is accomplished by using public key/private key encoding of parts of the assembly. The public key is embedded in the assembly and will be used by third-parties who want to reference the assembly. There are many more benefits to signing an assembly, but the main purpose of delayed signing is to allow a company to protect and control its private key and only use it during the packaging process. A delayed signed assembly can still be used like a signed assembly; you just can’t package and ship it.

Global Assembly Catch (GAC)        

            Shared assemblies must have globally unique names derived from their strong names (public keys generated to distinguish assemblies from other assemblies that may have the same names) which are Microsoft’s solution to DLL hell.

         The GAC, not the registry, is the store for this information. When an application loads the GAC is examined by the Common Language Runtime to determine if the version of a shared component exists that is compatible with the one referenced by the application.

          The gacutil.exe that ships with .NET can be used to add or remove a shared assembly from the GAC.

à    To add a shared assembly, from the command line enter:                           

                                    gacutil.exe /i myassembly.dll

à    To remove a shared assembly, from the command line enter:                         

                                     gacutil.exe /u myassembly.dll

                        When viewing the GAC in Windows Explorer shfusion.dll is used to provide the user interface. You can locate and rename this DLL to view the GAC like any other folder.