Sunday, May 24, 2009

.Net C# Data Types

Data is physically stored inside cells of memory. This memory could be physical memory (Hard disk) or logical memory (RAM). Any cell of memory is represented with a unique address. This address is more than some combination of numbers or symbols.

C# language provides for practically all the data types. These types can be divided in three categories: value types, reference types and pointer types.

There are some more basic concepts to be learnt before the discussion of the data types. This is about variables and constants. A Variable is a named cell of memory used for data storage. A Variable value can be changed anytime. Every variable must have a type and this type must be set before it is used. Qualifying a variable with a type is called as declaration of variable. The type of a variable is the most important aspect and it defines the behavior of variable. All variables can be divided into seven main categories depending on the context of usage:

  • Static variables

  • Variable of instance

  • Array's elements

  • Parameters given by reference

  • Parameters given by value

  • Returned values

  • Local variables
  • .


    Static Variables will be alive throughout the life of a program. It can be declared using static modifier.

    An Instance variable is a variable declared without static modifier. Usually it is declared inside a class or structure definition.

    Parameter Values can be viewed as input parameters into methods:

    public static void Sum(int a, int b)
    {
    Console.WriteLine("The sum of elements {0} and {1} is {2}",a,b,a + b);
    }

    This code writes in console values of variables a, b and their summary value. Now if the values of these parameters are modified inside the method, this change will not be reflected inside the main function. It is because the compiler creates copies of them when it passes them as value types. This ensures that their original values are not modified.

    Instead if one wants to modify the parameter variables inside the function, C# has something called Reference variables. Reference variables also have a modifier out which can be used before their type. Look at the following example:

    public static void SumRef(ref int a, ref int b)
    {
    a = 4;
    b = 6;
    Console.WriteLine("The sume of elements {0} and {1} is {2}",a,b,a + b);
    }

    Now this method modifies the value of variables a and b with values 4 and 6. These values are retained even after the execution of the function gets completed.
    If the parameters need to be returned then they can be qualified with out modifier or as returned parameter in method definition. Here is an example of both of them, in which both of them return the same value:

    public static int SumOut(int a, int b, out int sum1)
    {

    sum1 = a+b;
    Console.WriteLine("The sum1 of elements {0} and {1} is {2}",a,b,a+b);
    return sum1;

    }


    In main function it must be called in the next manner:

    int sume ;
    sume = SumeOut(2,2, out sume);

    Constants in C#:
    Constant type of data cannot be changed. To declare a constant the keyword const is used. An example for the constant declaration is: const double PI = 3.1415;

    Values types in C#:
    Value type stores real data. When the data are queried by different function a local copy of it these memory cells are created. It guarantees that changes made to our data in one function don't change them in some other function. Let see at a simple example:

    public class IntClass
    {
    public int I = 1;
    }

    Here we have simple class that contains only one public data field of integer type. Now have a look on its usage in main function:

    static void Main(string[] args)
    {
    // test class
    int i = 10;
    int j = i;
    j = 11;
    IntClass ic1 = new IntClass();
    IntClass ic2 = ic1;
    ic2.I = 100;

    Console.WriteLine("value of i is {0} and j is {1}",i,j);
    Console.WriteLine();
    Console.WriteLine("value of ic1.I is {0} and ic2.I is {1}",ic1.I,ic2.I);
    Console.WriteLine();
    }


    Reference Types in C#:
    In the above example, assume that First we have two value type i and j. Also assume that the second variable is initialized with the value of the first one. It creates new copy in memory and after it the values of these variables will be next:

    i = 10;
    j = i;

    There are a few more things written in the above example for explaining the Reference Types in C#. At first, the variable ic1 of IntClass is created using dynamic memory allocation. Then we initialize the variable ic2 with value of ic1. This makes both the variables ic1 and ic2 referring to the same address. If we change a value of ic2, it automatically changes the value of ic1.

    Now, over to the discussions about the important value types used in C#. The category simple types contains some predefined or system types that also are commonly used in other programming languages. It contains integer types: byte, Sbyte, Long, Ulong, Short, Ushort, int, Uint. These common types differs only range of values and sign.

    Next simple type is character type. To declare a variable of this type need use keyword char. It can take values of characters or numbers as 16-digit symbol of the type Unicode.

    The Boolean type has only two values: true, false. But these values cannot be assigned with a 0 or 1 as in C++ language.

    Next category of simple types is floating point types. It contains two types float and double. Float type can get values in range from 1.5*10-45 to 3.4*1038. Double type has range of values from 5.0*10-324 to 1.7*10308.

    A structural value types are struct and enum. Struct is a the same as class but it uses real values not references. The following code snippet contains the definition for struct:

    struct Point3D
    {

    public float m_x;
    public float m_y;
    public float m_z;

    public float [] GetArray()
    {

    float [] arr = new float[3];
    arr[0] = m_x;
    arr[1] = m_y;
    arr[2] = m_z;
    return arr;

    }

    }


    The above is declaration for a simple structure of real 3D point. As you see a class declaration looks very similar to the struct except that the class also has a constructor.

    Enumerated types can be used to create some set of identifiers that can have values of simple type. Let us see at example of enum type:

    public enum Days
    {

    Monday,
    Tuesday,
    Wensday,
    Thursday,
    Friday,
    Saturday,
    Sunday

    }


    In example there are enum that has days of week names. The values of days by default are in range from 0 to 6.

    Common types in C#:
    Object in C# language is universal; it means that all supported types are derived from it. It contains only a couple of methods: GetType() - returns a type of object, ToString() returns string equivalent of type that called.

    Next type is class. It is declared in the same manner as structure type but it has more advanced features.

    Interface is an abstract type. It is used only for declaring type with some abstract members. It means members without implementations. Please, have a look at piece of code with a declaration for a simple interface:

    interface IRect
    {
    int Width
    {
    get;
    set;
    }

    int Height
    {
    get;
    set;
    }

    int CalculateArea();
    }

    The members of interface can be methods, properties and indexers.

    Next reference type to be dealt is delegate. The main goal of delegate usage is encapsulation of methods. It most like at pointers to function in C++.

    String is common type that is used in almost all programming languages of high level. An example of string declaration and initialization:

    string s = "declaration and init";

    The last very used reference type is array. Array it is set of elements that have the same type. Array contains list of references on memory cells and it can contain any amount of members. In C# there are three types of arrays: one-dimensional, two-dimensional and jagged array.

    So, this covers almost all types used in C#. All these types can be cast to another type using special rules. An implicit casting can be done with types when values of variables can be converted without losing of any data. There is special type of implicit casting called boxing. This enables us to convert any type to the reference type or to the object type. Boxing example:

    // boxing
    char ch = 'b';
    object obj = ch;
    Console.WriteLine("Char value is {0}",ch);
    Console.WriteLine("Object value is {0}",obj);
    Console.WriteLine();


    This piece of code prints the same values of integer type variable and object type variable. The opposite process to the boxing is un-boxing. An example for un-boxing is as follows.

    // unboxing
    float q = 4.6f;
    object ob = q;
    Console.WriteLine("Object value is {0}",ob);
    float r = (float)ob;
    Console.WriteLine("Float value is {0}",r);

    Tuesday, May 19, 2009

    Cloud Computing

    Cloud computing is still evolving, adding that "its definitions, use cases, underlying technologies, issues, risks, and benefits will be refined in a spirited debate by the public and private sectors. These definitions, attributes, and characteristics will evolve and change over time."

    what is cloud computing?

    Cloud computing is a pay-per-use model for enabling available, convenient, on-demand network access to a shared pool of configurable computing resources (e.g., networks, servers, storage, applications, services) that can be rapidly provisioned and released with minimal management effort or service provider interaction. This cloud model promotes availability and is comprised of five key characteristics, three delivery models, and four deployment models.

    Those five key characteristics are:

    On-demand self-service.
    Ubiquitous network access.
    Location-independent resource pooling.
    Rapid elasticity.
    Pay per use.

    And the three delivery models?

    Cloud Software as a Service (SaaS).
    Cloud Platform as a Service (PaaS).
    Cloud Infrastructure as a Service (IaaS).

    Cloud software takes full advantage of the cloud paradigm by being service oriented with a focus on statelessness, low coupling, modularity, and semantic interoperability

    And finally, the deployment models:

    Private cloud.
    Community cloud.
    Public cloud.
    Hybrid cloud.

    Each deployment model instance has one of two types: internal or external. Internal clouds reside within an organizations network security perimeter and external clouds reside outside the same perimeter.

    Details on all of these characteristics and models are available here.

    Microsoft Visual Studio 2010 and .Net Framework 4.0 Beta 1 Finally Arrived

    After a long silence since the last CTP (Community Technology Preview), Microsoft released the Visual Studio 2010 Beta 1 that comes with the new .Net Framework 4.0. This new release will bring new promising features that empower parallel programming using the supported languages.

    I must say that the Visual Studio 2010 CTP was not very useful to test the new multi-core performance improvements. It was available as a Virtual PC image and it expired on January 1 2009 (a few months ago).

    In the meantime, there were many interesting changes in the Task Parallel Library, now included as part of .Net Framework 4.0. However, it was difficult to test their performance because Virtual PC 2007 was limited to using a single core. Testing multi-core programming in a single core virtual machine was not really useful. This first beta version will bring us the truth about the performance improvements.

    I'm especially interested in the improved garbage collector and the last changes in the Parallel Extensions. The new features offered by .Net 4.0 are very promising and it is very important to begin measuring the performance that can be achieved with the new ThreadPool and the new task-based approach.

    The new debugger will simplify the debugging process for multi-core development. Besides, a multi-monitor support in the IDE makes things easier when you have to work with more than eight threads and watch them. As a Core i7 with Hyper-Threading offers 8 logical cores, it is very probable to work with applications with more than 8 threads with Visual Studio 2010.
    View Source for details..
    Get the Visual Studio 2010 datasheet (PDF File)
    Microsoft Visual Studio® 2010 First Look

    Sunday, May 17, 2009

    Spiral Model

    The spiral model is similar to the incremental model, with more emphases placed on risk analysis. The spiral model has four phases: Planning, Risk Analysis, Engineering and Evaluation. A software project repeatedly passes through these phases in iterations (called Spirals in this model). The baseline spiral, starting in the planning phase, requirements are gathered and risk is assessed. Each subsequent spirals builds on the baseline spiral.


    Requirements are gathered during the planning phase. In the risk analysis phase, a process is undertaken to identify risk and alternate solutions. A prototype is produced at the end of the risk analysis phase.

    Software is produced in the engineering phase, along with testing at the end of the phase. The evaluation phase allows the customer to evaluate the output of the project to date before the project continues to the next spiral.

    In the spiral model, the angular component represents progress, and the radius of the spiral represents cost.


    Advantages

    * High amount of risk analysis
    * Good for large and mission-critical projects.
    * Software is produced early in the software life cycle.

    Disadvantages

    * Can be a costly model to use.
    * Risk analysis requires highly specific expertise.
    * Project’s success is highly dependent on the risk analysis phase.
    * Doesn’t work well for smaller projects.

    Waterfall Model

    History
    The "waterfall model", documented in 1970 by Royce was the first publicly documented life cycle model. The model was developed to help cope with the increasing complexity of aerospace products. The waterfall model followed a documentation driven paradigm.

    This is the most common and classic of life cycle models, also referred to as a linear-sequential life cycle model. It is very simple to understand and use. In a waterfall model, each phase must be completed in its entirety before the next phase can begin. At the end of each phase, a review takes place to determine if the project is on the right path and whether or not to continue or discard the project. Unlike what I mentioned in the general model, phases do not overlap in a waterfall model.

    Here these following phases are followed in order:

    1. Requirements specification
    2. Design
    3. Construction (AKA implementation or coding)
    4. Integration
    5. Testing and debugging (AKA Validation)
    6. Installation
    7. Maintenance

    Advantages

    * Simple and easy to use.
    * Easy to manage due to the rigidity of the model – each phase has specific deliverables and a review process.
    * Phases are processed and completed one at a time.
    * Works well for smaller projects where requirements are very well understood.

    Disadvantages
    The waterfall model however is argued by many to be a bad idea in practice, mainly because of their belief that it is impossible to get one phase of a software product's lifecycle "perfected" before moving on to the next phases and learning from them (or, at least, the belief that this is impossible for any non-trivial program). For example, clients may not be aware of exactly what requirements they want before they see a working prototype and can comment upon it; they may change their requirements constantly, and program designers and implementers may have little control over this. If clients change their requirements after a design is finished, that design must be modified to accommodate the new requirements, invalidating quite a good deal of effort if overly large amounts of time have been invested into "Big Design Up Front". (Thus, methods opposed to the naive waterfall model--such as those used in Agile software development--advocate less reliance on a fixed, static requirements document or design document). Designers may not (or, more likely, cannot) be aware of future implementation difficulties when writing a design for an unimplemented software product. That is, it may become clear in the implementation phase that a particular area of program functionality is extraordinarily difficult to implement. If this is the case, it is better to revise the design than to persist in using a design that was made based on faulty predictions and that does not account for the newly discovered problem areas.
    * Adjusting scope during the life cycle can kill a project
    * No working software is produced until late during the life cycle.
    * High amounts of risk and uncertainty.
    * Poor model for complex and object-oriented projects.
    * Poor model for long and ongoing projects.
    * Poor model where requirements are at a moderate to high risk of changing.

    Software Development Life Cycle

    Software development life cycle (SDLC) is a process to develop the software systematically. SDLC is also known as software life cycle and software process. SDLC have the following stages:
    1) Information Gathering
    In this phase, information is gathered from the customer. If some information is missing then we need to go to customer and take the required information. Mainly this is done by the Business Analyst as they are the one who are completely involved in Software Development life Cycle.
    The Document Prepared during this phase is: Business Requirement Specification (BRS) or Customer Required Specification (CRS) Or User Requirement Specification (URS).
    Entry Criteria: BRS OR CRS or URS.
    2) Analysis Phase
    In this stage the project architect team determines the features and the functions that need to be developed in the project.
    Entry Criteria: BRS (Business Requirement Document)
    Exit Criteria: SRS (Software Requirement Specification)

    3) Design Phase
    The actually flow of the project is designed here. System architects, team leads prepares the logical functionality, ER diagram, Data Flow etc. Document prepared during this phase are HLD, LLD
    HLD (High Level Design): Gives the overall Hierarchy of the function.
    Example: Login into Net Banking. From the root level to the least level is determined in HLD.
    LLD (Low Level Design): Internal logic of the project is architect here. Focus is on the internal functionality of the program. Each and every module’s logic is defined.
    Entry Criteria: SRS
    Exit Criteria: Design Document.
    Coding
    The coding stage is a widely followed step in software development. Here the design is reduced to code for better understandability. Based on the design document, small-small modules are prepared. All the modules are summed together to form an application.

    Testing
    The coding stage is followed by the testing phase. This is one of the most important stages of any software development life cycle where extensive testing is done to ensure that coding done by different software developers work together in harmony and adhering to the agreed quality with the client.
    Release and Maintantence
    In this phase the malignance team will change the software if necessary based on customer end issues.
    The are different types of Software Development Life Cycle (SDLC) models existing such as:
    • RAD Model
    • The General Model
    • Spiral Model
    • Incremental Model
    • V-Shaped Model
    • Waterfall Model

    What is Web Gardening? How would using it affect a design?

    The Web Garden Model
    The Web garden model is configurable through the section of the machine.config file. Notice that the section is the only configuration section that cannot be placed in an application-specific web.config file. This means that the Web garden mode applies to all applications running on the machine. However, by using the node in the machine.config source, you can adapt machine-wide settings on a per-application basis.
    Two attributes in the section affect the Web garden model. They are webGarden and cpuMask. The webGarden attribute takes a Boolean value that indicates whether or not multiple worker processes (one per each affinitized CPU) have to be used. The attribute is set to false by default. The cpuMask attribute stores a DWORD value whose binary representation provides a bit mask for the CPUs that are eligible to run the ASP.NET worker process. The default value is -1 (0xFFFFFF), which means that all available CPUs can be used. The contents of the cpuMask attribute is ignored when the webGarden attribute is false. The cpuMask attribute also sets an upper bound to the number of copies of aspnet_wp.exe that are running.
    Web gardening enables multiple worker processes to run at the same time. However, you should note that all processes will have their own copy of application state, in-process session state, ASP.NET cache, static data, and all that is needed to run applications. When the Web garden mode is enabled, the ASP.NET ISAPI launches as many worker processes as there are CPUs, each a full clone of the next (and each affinitized with the corresponding CPU). To balance the workload, incoming requests are partitioned among running processes in a round-robin manner. Worker processes get recycled as in the single processor case. Note that ASP.NET inherits any CPU usage restriction from the operating system and doesn't include any custom semantics for doing this.
    All in all, the Web garden model is not necessarily a big win for all applications. The more stateful applications are, the more they risk to pay in terms of real performance. Working data is stored in blocks of shared memory so that any changes entered by a process are immediately visible to others. However, for the time it takes to service a request, working data is copied in the context of the process. Each worker process, therefore, will handle its own copy of working data, and the more stateful the application, the higher the cost in performance. In this context, careful and savvy application benchmarking is an absolute must.
    Changes made to the section of the configuration file are effective only after IIS is restarted. In IIS 6, Web gardening parameters are stored in the IIS metabase; the webGarden and cpuMask attributes are ignored.

    Why should you avoid the excessive use of ViewState in Asp.Net web page?

    Automatic state management is a feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field.

    Since the view state data resides in a hidden form field (__VIEWSTATE); ViewState increases the size of page and results in slow loading of page at browser. You should be aware of when ViewState is helping you and when it is not.

    For example, if you are binding a control to data on every round trip , then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false, as in the following example:
    < asp:datagrid EnableViewState="false" datasource="..." runat="server"/>
    You can also turn ViewState off at the page level. This is useful when you do not post back from a page at all, as in the following example:
    < %@ Page EnableViewState="false" %>
    Note that this attribute is also supported by the User Control directive.

    ASP.Net

    Web Form Life Cycle
    Every request for a page made to a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser. The life cycle of a page is marked by the following events, each of which you can handle yourself or leave to default handling by the ASP.NET server:

    1. Initialize
    Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized.

    2. Load ViewState
    The ViewState property of the control is populated. The ViewState information comes from a hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the ViewState property is set. This can be modified via the LoadViewState( ) method. This allows ASP.NET to manage the state of your control across page loads so that each control isn't reset to its default state each time the page is posted.

    3. Process Postback Data
    During this phase, the data sent to the server in the posting is processed. If any of this data results in a requirement to update the ViewState, that update is performed via the LoadPostData( ) method.

    4. Load
    CreateChildControls( ) is called, if necessary, to create and initialize server controls in the control tree. State is restored, and the form controls contain client-side data. You can modify the load phase by handling the Load event with the OnLoad() method.

    5. Send Postback Change Modifications
    If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent( ) method.

    6. Handle Postback Events
    The client-side event that caused the postback is handled.

    7. PreRender
    This is your last chance to modify the output prior to rendering using the OnPreRender( ) method.

    8. Save State
    Near the beginning of the life cycle, the persisted view state was loaded from the hidden variable. Now it is saved back to the hidden variable, persisting as a string object that will complete the round trip to the client. You can override this using the SaveViewState( ) method.

    9. Render
    This is where the output to be sent back to the client browser is generated. You can override it using the Render method. CreateChildControls( ) is called, if necessary, to create and initialize server controls in the control tree.

    10. Dispose
    This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections. You can modify it using the Dispose( ) method.


    What is the purpose of Server.MapPath method in Asp.Net?
    In Asp.Net Server.MapPath method maps the specified relative or virtual path to the corresponding physical path on the server. Server.MapPath takes a path as a parameter and returns the physical location on the hard drive. Syntax

    Suppose your Text files are located at D:\project\MyProject\Files\TextFiles

    If the root project directory is MyProject and the aspx file is located at root then to get the same path use code

    //Physical path of TextFiles
    string TextFilePath=Server.MapPath("Files/TextFiles");

    What is the use of Master Pages in Asp.Net?
    A master page in ASP.Net provides shared HTML, controls, and code that can be used as a template for all of the pages of a website.
    Every master page has asp:contentplaceholder control that will be filled by the content of the pages that use this master page.
    You can create a master page that has header and footer i.e. a logo, an image, left navigation bar etc and share this content on multiple pages. You need not to put these things on every aspx page.

    What are the different state management techniques used in asp.net for web applications?
    In ASP.Net the state can be maintained in following ways
    Server-side state management
    Application objects
    Session Variables
    Database
    Client-side state management
    Cookies
    Hidden input fields
    Query String
    ViewState

    What is the use of XSLT?

    XSLT stands for Extensible Stylesheet Language Transformations. This language used in XSL style sheets to transform XML documents into other XML documents.

    XSLT is based on template rules which specify how XML documents should be processed. An XSLT processor reads both an XML document and an XSLT style sheet. Based on the instructions the processor finds in the XSLT style sheet, it produce a new XML document. With XSLT we can also produce HTML or XHTML from XML document. With XSLT we can add/remove elements and attributes, rearrange and sort elements, hide and display elements from the output file. Converting XML to HTML for display is probably the most common application of XSLT today.

    What is the difference between .Net Remoting and Asp.Net Web Services?

    • ASP.NET Web Services Can be accessed only over HTTP but .Net Remoting Can be accessed over various protocols like TCP, HTTP, SMTP etc.

    • Web Services are based on stateless service architecture but .Net Remoting support for both stateful and stateless environment.

    • Web Services support heterogeneous environments means interoperability across platforms but .Net remoting requires .Net on both server and client end.

    • .NET Remoting provides the fast communication than Web Services when we use the TCP channel and the binary formatter.

    • Web services support only the objects that can be serialized but .NET Remoting can provide support to all objects that inherit MarshalByRefObject.

    • Web Services are reliable than .Net remoting because Web services are always hosted in IIS.

    • Web Services are ease to create and deploy but .Net remoting is bit complex to program.

    Static Class

    We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We can not create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.

    Here are some more features of static class
    • Static classes only contain static members.
    • Static classes can not be instantiated. They cannot contain Instance Constructors
    • Static classes are sealed.

    What is static member of class?
    A static member belongs to the class rather than to the instances of the class. In C# data fields, member functions, properties and events can be declared static. When any instances of the class are created, they cannot be used to access the static member.
    To access a static class member, use the name of the class instead of an instance variable
    Static methods and Static properties can only access static fields and static events.

    Like: int i = Car.GetWheels;
    Here Car is class name and GetWheels is static property.

    Static members are often used to represent data or calculations that do not change in response to object state.

    What is the basic functionality of Garbage Collector in Microsft.Net?

    The Common Language Runtime (CLR) requires that you create objects in the managed heap, but you do not have to bother with cleaning up the memory once the object goes out of the scope or is no longer needed. The Microsoft .NET Framework Garbage Collector provides memory management capabilities for managed resources. The Garbage Collector frees objects that are not referenced and reclaims their memory. You should set your references to Nothing(null) as soon as you are done with them to ensure your objects are eligible for collection as soon as possible.
    Here are the list of some tasks performed by the Garbage collector:
    • Garbage collector reserves a piece of memory as the application starts for the managed heap.
    • Garbage collector controls the managed heap memory currently used and available to an application.
    • Garbage collector allocates memory for new objects within the application.
    • The Garbage Collector attempts to reclaim the memory of objects that are not referenced.

    What is a Strong Name in Microsoft.Net?

    In Microsoft.Net a strong name consists of the assembly's identity. The strong name guarantees the integrity of the assembly. Strong Name includes the name of the .net assembly, version number, culture identity, and a public key token. It is generated from an assembly file using the corresponding private key.
    Steps to create strong named assembly:

    To create a strong named assembly you need to have a key pair (public key and a private key) file. Use sn -k KeyFile.snk
    Open the dot net project to be complied as a strong named assembly. Open AssembyInfo.cs/ AssembyInfo.vb file. Add the following lines to AssemblyInfo file.
    [Assembly: AssemblyVersion("1.0.*")]
    [assembly: AssemblyDelaySign(false)]
    [assembly: AssemblyKeyFile("..\\..\\KeyFile.snk")]
    Compile the application, we have created a strong named assembly.

    What is the difference between classes and structs in Microsoft.Net?

    • A struct is a value type, while a class is a reference type.
    • When we instantiate a class, memory will be allocated on the heap. When struct gets initiated, it gets memory on the stack.
    • Classes can have explicit parameter less constructors. But structs cannot have this.
    • Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
    • We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
    • We can declare a destructor in class but can not in struct.

    What is the purpose of connection pooling in ADO.NET?

    Connection pooling enables an application to use a connection from a pool of connections that do not need to be re-established for each use. Once a connection has been created and placed in a connection pool, an application can reuse that connection without performing the complete connection creation process.

    By default, the connection pool is created when the first connection with a unique connection string connects to the database. The pool is populated with connections up to the minimum pool size. Additional connections can be added until the pool reaches the maximum pool size.

    When a user request a connection, it is returned from the pool rather than establishing new connection and, when a user releases a connection, it is returned to the pool rather than being released. But be sure than your connections use the same connection string each time. Here is the Syntax

    conn.ConnectionString = "integrated Security=SSPI; SERVER=192.168.0.123; DATABASE=MY_DB; Min Pool Size=4;Max Pool Size=40;Connect Timeout=14;";

    Delegates in C#

    Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.
    Here are some features of delegates:
    • A delegate represents a class.
    • A delegate is type-safe.
    • We can use delegates both for static and instance methods
    • We can combine multiple delegates into a single delegate.
    • Delegates are often used in event-based programming, such as publish/subscribe.
    • We can use delegates in asynchronous-style programming.
    • We can define delegates inside or outside of classes.
    Syntax of using delegates

    //Declaring delegate
    delegate void SampleDelegate(string message);

    // declare method with same signature:
    static void SampleDelegateMethod(string message) { Console.WriteLine(message); }

    // create delegate object
    SampleDelegate d1 = SampleDelegateMethod;

    // Invoke method with delegate
    d1("my program");

    Abstract classes, Sealed Classes, and Interfaces in C#

    Using sealed classes is a new concept added in C#. It is difficult to say when we should use an abstract class and when we should use an interface. In general defining an abstract class without any implementation means with abstract members has the same effect as defining an interface; however there are a lot more differences than similarities between an abstract class and an interface.

    What is an Abstract class?
    An abstract class only allows other classes to inherit from it and cannot be instantiated. When we create an abstract class, it should have one or more completed methods but at least one or more uncompleted methods and these must be preceded by the key word abstract. If all the methods of an abstract class are uncompleted then it is the same as an interface, but there is a restriction that it cannot make a class inherit from it, which means it can not work as a base class.
    E.g.
    public abstract class Product
    {
    //fields
    protected string id;
    protected double price;
    //properties
    public abstract string ID
    {
    get;
    set;
    }

    public abstract double Price
    {
    get;
    set;

    }
    public abstract double CalculatePrice();
    }


    What is an Interface?
    An interface is defined by the key word interface. An interface has no implementation; it only has the definition of the methods without the body. When we create an interface, we are basically creating a set of methods without any implementation. A class implementing an interface must provide the implementation of the interface members. All the methods and properties defined in an interface are by default public and abstract.

    E.g.
    public interface Iproduct
    {
    string ID
    {
    get;
    set;

    }

    double Price
    {
    get;
    set;

    }
    double CalculatePrice();
    }

    Abstract Class vs. Interface
    An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.
    • An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property's signature but no implementation.
    • An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.
    • A class implementing an interface has to implement all the methods of the interface, but the same is not required in the case of an abstract Class.
    • Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.
    • Abstract classes are faster than interfaces.


    Sealed Class

    Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition. For example:

    public sealed class classSealed
    {
    // Class members here.
    public string ID;
    public double Price;
    }
    In the following code listing the implementation of a sealed class has been tested.

    classSealed sc=new classSealed();
    sc.ID=”C1”;
    sc.Price=500.00;
    double Samt=sc. CalculatePrice();
    Response.Write(“Total Net Price of Product : “ +” “+sc.ID +” “+ “is”+” “+Samt);
    Response.Write(“
    ”);
    A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one can not derive from it. Sealing a method means one can not override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing).

    public class TestClass : classSealed
    {
    }
    In C# a method can not be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

    public class testClass
    {
    public int x;
    public int y;
    public virtual void testMethod(){

    }

    }

    public class TestClass: testClass
    {
    public override sealed void testMethod(){

    }
    }

    So Which One Should I Use?
    Abstract classes can add more functionality without destroying the child classes that were using the old version. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. In an interface, creation of additional functions will have an effect on its child classes due to the necessary implementation of interface Methods in classes. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. Say there are two classes, bird and airplane, and both of them have methods called fly. It would be ridiculous for an airplane to inherit from the bird class just because it has the fly() method. Rather, the fly() method should be defined as an interface and both bird and airplane should implement that interface. If we want to provide common, implemented functionality among all implementations of component, we should use an abstract class. Abstract classes allow us to partially implement classes, whereas interfaces contain no implementation for any members. So the selection of interface or abstract classes depends on the needs and design of our project. We can make an abstract class, interface, or combination of both depending on our needs.
    The most likely situation in which we make a class or method sealed will be if the class or method is internal to the operation of the library, class, or other classes that we are writing. Because any attempt to override some of its functionality will cause problems. We can mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending our classes. For example, in the .NET base class library string is a sealed class.
    We should not use the sealed key word on a method unless that method is itself an override of another method in some base class. If we are defining a new method and we don’t want anyone else to override it, we should not declare it as virtual in the first place. If however, we have overridden a base class method, the sealed keyword provides a way of ensuring that the override supplied to a method is a “final” override that means no one else can override it again.

    Sealed Modifier

    When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.

    class A {}
    sealed class B : A {}
    You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties. In the following example, C inherits from B but C cannot override the virtual function F that is declared in A and sealed in B.

    class A
    {
    protected virtual void F() { Console.WriteLine("A.F");}
    protected virtual void F2() { Console.WriteLine("A.F2");}
    }
    class B : A
    {
    sealed protected override void F() { Console.WriteLine("B.F");}
    protected override void F2() {Console.WriteLine("A.F3");}
    }
    class C : B
    {
    // Attempting to override F causes compiler error CS0239.
    // protected override void F() { Console.WriteLine("C.F"); }

    // Overriding F2 is allowed.
    protected override void F2() { Console.WriteLine("C.F2"); }
    }
    Note:

    When you define new methods or properties in a class, you can prevent deriving classes from overriding them by not declaring them as virtual.

    It is an error to use the abstract modifier with a sealed class, because an abstract class must be inherited by a class that provides an implementation of the abstract methods or properties.
    When applied to a method or property, the sealed modifier must always be used with override.
    Because structs are implicitly sealed, they cannot be inherited.
    For more information, see Inheritance (C# Programming Guide).
    Example
    Copy Code
    // cs_sealed_keyword.cs
    using System;
    sealed class SealedClass
    {
    public int x;
    public int y;
    }

    class MainClass
    {
    static void Main()
    {
    SealedClass sc = new SealedClass();
    sc.x = 110;
    sc.y = 150;
    Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
    }
    }
    Output
    x = 110, y = 150
    In the previous example, you might try to inherit from the sealed class by using the following statement:
    class MyDerivedC: SealedClass {} // Error
    The result is an error message:
    'MyDerivedC' cannot inherit from sealed class 'SealedClass'.

    Abstract Modifier

    The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
    In this example, the class Square must provide an implementation of Area because it derives from ShapesClass:

    abstract class ShapesClass
    {
    abstract public int Area();
    }
    class Square : ShapesClass
    {
    int x, y;
    // Not providing an Area method results
    // in a compile-time error.
    public override int Area()
    {
    return x * y;
    }
    }
    For more information about abstract classes, see Abstract and Sealed Classes and Class Members.

    Remarks
    Abstract classes have the following features:
    • An abstract class cannot be instantiated.
    • An abstract class may contain abstract methods and accessors.
    • It is not possible to modify an abstract class with the sealed (C# Reference) modifier because sealed prevents the class from being inherited.
    • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
    Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
    Abstract methods have the following features:
    • An abstract method is implicitly a virtual method.
    • Abstract method declarations are only permitted in abstract classes.
    • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. For example:

    public abstract void MyMethod();
    • The implementation is provided by an overriding methodoverride (C# Reference), which is a member of a non-abstract class.
    • It is an error to use the static or virtual modifiers in an abstract method declaration.
    Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
    • It is an error to use the abstract modifier on a static property.
    • An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
    An abstract class must provide implementation for all interface members.
    An abstract class that implements an interface might map the interface methods onto abstract methods. For example:

    interface I
    {
    void M();
    }
    abstract class C: I
    {
    public abstract void M();
    }
    Example
    In this example, the class DerivedClass is derived from an abstract class BaseClass. The abstract class contains an abstract method, AbstractMethod, and two abstract properties, X and Y.

    // abstract_keyword.cs
    // Abstract Classes
    using System;
    abstract class BaseClass // Abstract class
    {
    protected int _x = 100;
    protected int _y = 150;
    public abstract void AbstractMethod(); // Abstract method
    public abstract int X { get; }
    public abstract int Y { get; }
    }

    class DerivedClass : BaseClass
    {
    public override void AbstractMethod()
    {
    _x++;
    _y++;
    }

    public override int X // overriding property
    {
    get
    {
    return _x + 10;
    }
    }

    public override int Y // overriding property
    {
    get
    {
    return _y + 10;
    }
    }

    static void Main()
    {
    DerivedClass o = new DerivedClass();
    o.AbstractMethod();
    Console.WriteLine("x = {0}, y = {1}", o.X, o.Y);
    }
    }

    x = 111, y = 161

    Comments
    In the preceding example, if you attempt to instantiate the abstract class by using a statement like this:
    Copy Code
    BaseClass bc = new BaseClass(); // Error
    you will get an error saying that the compiler cannot create an instance of the abstract class 'BaseClass'.

    Saturday, May 16, 2009

    Sealed Classes And Methods In C#

    The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.
    The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.
    In C# structs are implicitly sealed; therefore, they cannot be inherited.
    using System;
    sealed class MyClass
    {
    public int x;
    public int y;
    }

    class MainClass
    {
    public static void Main()
    {
    MyClass mC = new MyClass();
    mC.x = 110;
    mC.y = 150;
    Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
    }
    }
    In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:
    class MyDerivedC: MyClass {} // Error
    You will get the error message:
    'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.
    In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.
    using System;
    class MyClass1
    {
    public int x;
    public int y;

    public virtual void Method()
    {
    Console.WriteLine("virtual method");
    }
    }

    class MyClass : MyClass1
    {
    public override sealed void Method()
    {
    Console.WriteLine("sealed method");
    }
    }

    class MainClass
    {
    public static void Main()
    {
    MyClass1 mC = new MyClass();
    mC.x = 110;
    mC.y = 150;
    Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
    mC.Method();
    }
    }