Monday, June 24, 2013

What is AppFabric Caching

AppFabric provides a distributed caching platform, used to develop highly scalable applications which require a cache to provide performance optimization. The caching platform can be scaled out by adding multiple cache servers to the architecture.

AppFabric caching platform takes care of sharing the cached objects across the cache servers automatically, and makes sure that the cache objects added to one of the instances is made available in all other instances.

Advantages of Distributed Caching

In general Caching improves performance of an application by storing frequently used information in the cache memory which is easily accessible when compared to the standard memory. Simple caching techniques can be used for smaller applications which get executed in a single server, however when it comes to larger applications which cannot run in a single server the simple caching techniques are not sufficient enough.

Larger applications required multiple servers, running in parallel to handle the huge volume of requests, hence we need Distributed Caching for large applications. The following are the advantages of using Distributed Caching.


Distributed Cache

Data is an important part of any application, in a conventions web application architecture which does not use any cache, data can be stored in 2 ways, using the database or using sessions, but both these options have their own limitations.

The database can store any amount of data, but fetching large amount of data from the database and displaying in the UI will bring performance of the application. Sessions are quick but there is a limitation on the amount of data that can be stored in session, adding more data to the session, consumes more memory and hence brings down the application performance.

Limitations of Asp.Net Cache

Asp.Net cache is a good approach to improve the performance of an application, frequently used data can be stored in the cache and re-used to avoid unwanted database hits. However Asp.Net cache has its limitations.

The following are the limitation of Asp.Net Cache.

Limitations of Asp.Net Cache

Asp.Net cache is a good approach to improve the performance of an application, frequently used data can be stored in the cache and re-used to avoid unwanted database hits. However Asp.Net cache has its limitations.

The following are the limitation of Asp.Net Cache.

Asp.Net Cache

Asp.Net provides a caching mechanism which can be used to store data in a key value format. The data stored in the Asp.Net Cache can be retrieved at any time by using the key against which the value is stored.

The following example stores the list of countries is a Cache variable “cacheCountryList”.

What is a Cache?

A Cache refers to an intermediate storage location which can respond quickly to requests, thereby helping in improving the performance of the applications which makes use of the Cache.

In Hardware we refer to Cache memory as an intermediate memory which stores frequently used data and responds quickly when the processor requests the data. For example RAM (Random Access memory) is a intermediate cache memory used to store and respond to frequently used data. Data stored in the cache memory is retrieved quickly as compared to the data stored in the hard disk. Similarly a cache in the software world in an intermediate storage location used to provide quick response to users requests. 

Monday, June 17, 2013

Assemblies and Side-by-Side Execution

Let us consider that we have 2 applications A & B in a system, where A is an old application using an older version (say x1) of an assembly, not B is a new application and wants to use a new version (say x2) of the same assembly, how can this be achieved?

If the Assemblies are private assemblies then we don’t have an issue as the applications A & B will contain their own version of the assembly in their application folder and use the assemblies independently. But what is the assembly is a shared assembly, how can be maintain and use 2 different versions of the same assembly? This is where side-by-side execution comes into play.

What is a Global Assembly Cache (GAC)

The Global Assembly Cache (GAC) is a common folder where the shared assemblies are placed. The GAC folder is placed in one of the following folders.

X:/Windows/assembly
(or)
X:/Winnt/assembly

Where X: is the driver where the .Net framework in installed, it might vary from machine to machine based on where the .Net Framework is installed.

For an Assembly to be placed in the GAC, it should be signed with a strong name key, generated using the sn.exe utility. Once the assembly is signed with the key and is ready for deployment, it can be deployed in the GAC in one of the following ways.

Delay signing an Assembly

Delay signing is the process of delaying the actual signing process, if we use the normal signing process then the details of the private and public key will be available to all the developers who are involved in developing the Assembly.

The organization might want to restrict access to the private key only to a set of key individuals and not to all, delay signing process can be used to achieve this.

Delay signing can be achieved by specifying the AssemblyDelaySignAttribute attribute to true in the assemblyInfo file, on doing so the runtime will not sign the Assembly, but will reserve space in the PE file for the strong name which can be specified later.

Signing an Assembly

Signing an Assembly requires generating a key file and mapping it to a Shared assembly. There are 2 types of assemblies, private and shared assemblies. Private assemblies are private to the application and are placed in the same folder as the application files. Shared assemblies are those which are shared across multiple applications in the same machine.

Before we could sign an Assembly we need to generate a key file which will be used for signing. To sign the assembly we can use the .Net Utility sn.exe

sn.exe -k MyPublicPrivateKeyFile.snk

The key file contains a combination of private and public keys which will later be used by the publisher and the consumer to the assembly to establish a secured relationship.

Once the assembly key file is generated, it can be linked to the assembly in 2 ways.

Assembly Versioning

Assembly version details are stored in a file called AssemblyInfo, this file gets automatically created when you create a new project in Visual Studio, the version information of the assembly is specified in this file.

A .Net Assembly version is a four part name, and contains the following 

Major Version
Minor Version
Build Version
Release Version.

The four parts of the Assembly version are organized as follows.

Dynamic Assemblies

As the name suggests, Dynamic Assemblies are those which are created dynamically at runtime. They are not stored in any file before execution, after execution we can optionally store them in files. The System.Reflection.Emit namespace contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) and optionally generate a PE file on disk.

The Reflection.Emit namespace provides builder classes which can be used to create assemblies at runtime, these classes allow you to define classes and methods at runtime. The AssemblyBuilder is the core class which allows you to create assemblies at runtime.

AssemblyBuilder assemblyBuilder = curAppDomain.DefineDynamicAssembly(
assemblyName,AssemblyBuilderAccess.Save);

Static Assembly

Static Assemblies are the normal assemblies which we create in .Net, they have physical class files and other related resource files like, images, sound files etc. These physical files are compiled into a single assembly file.

Static Assemblies can be private or public based on the type of target applications which use these assemblies. Private assemblies are used by individual applications, the assembly files are placed in the same folder/sub-folder of the application files. Shared assemblies are placed in the GAC and are shared across multiple applications in the system.

Satellite Assembly

Satellite Assemblies are used to create multilingual applications which needs to display information to the end users in multiple languages. Satellite assemblies do not contain any executable code, they contain only culture specific resource files which can be used by the main assembly to display details to the end user in their preferred language.

Language specific resources should be created and compiled into Satellite Assemblies using the Assembly Linker tool Al.exe.

Shared Assembly

As the name suggests a Public Assembly or Shared Assembly is one which is shared with various applications in the same system, hence these assembly files cannot be placed in the individual application folders, and these assembly files are placed in a common location in the machine called the Global Assembly Cache.

Public Assembly or Shared Assembly should have specific version information. All public / shared assemblies are placed in a common folder in the machine called the Global Assembly Cache. The GAC is usually located in the path C:\Windows\Assembly

Public Assembly

As the name suggests a Public Assembly or Shared Assembly is one which is shared with various applications in the same system, hence these assembly files cannot be placed in the individual application folders, and these assembly files are placed in a common location in the machine called the Global Assembly Cache.

Public Assembly or Shared Assembly should have specific version information. All public / shared assemblies are placed in a common folder in the machine called the Global Assembly Cache. The GAC is usually located in the path C:\Windows\Assembly

Private Assembly

A Private assembly is one which is used by an individual application; it is private to that application and is not shared with any other application in the system. Private assemblies are usually placed in the same folder or in a sub-folder where the application files reside.

Private Assemblies do not have specific version information, since the parent application is just going to refer the latest assembly file in its folder/sub-folder.

What are the types of Assemblies in .Net?

Assemblies can be categorized based on various factors like, based on how they are shared between applications, based on their physically state, based on how they are packed into files etc.

The following are the various types of assemblies based on the different classifications.

What does an Assembly contain?

An assembly is the core building block of .Net, assemblies are self-contained, they contain all the information required to process the assembly. Any .Net assembly contains the following details.

1. The MSIL code of the assembly
2. Assembly Manifest
3. Type Metadata
4. Resources

Now let us see these in detail.

What is an Assembly in .Net

An assembly is a collection of classes, namespaces and related information which together form a complete application. Every application which is developed in .Net is stored in an assembly.

Assembly can be either a self-executable file, with an extension of .EXE, or a library file with an extension of .DLL. Let us see more in details about both these types of assemblies.

Sunday, June 16, 2013

Performance Monitor – Detailed Report View

The Windows Performance Monitor is a performance monitoring tool, which comes along with the windows operating system. The Performance Monitor tool provides various performance counters and factors which can be used to analyze and determine the performance of a system on a whole or that of a specific process over a specific period of me.

The Performance Monitor displays the details captured by the counter is different formats like Line Graph, Histogram and a Detailed Report view.

To change the output view to detailed report view, click on the report menu and select the Report option as below.

Performance Monitor - Histogram Report View

The Windows Performance Monitor is a performance monitoring tool, which comes along with the windows operating system. The Performance Monitor tool provides various performance counters and factors which can be used to analyze and determine the performance of a system on a whole or that of a specific process over a specific period of me.

The Performance Monitor displays the details captured by the counter is different formats like Line Graph, Histogram and a Detailed Report view.

To change the output view to Histogram view, click on the report menu and select the Histogram bar as below.


Performance Monitor – Windows Application

The Windows Performance Monitor is a general purpose performance monitoring tool which can be used to monitor performance of windows and web applications. The tool can be customized to monitor specific parameters like Memory Utilization, CPU Utilization, Disk I/O etc of the system at any given point of time or over a specific time interval.

In this post we shall see on how to use the Performance Monitor tool monitor performance of a Windows application based on memory utilization of the application. This is just one of the counters, there a hundreds of such counters which can be used to measure various parameters of the application.

To measure the memory utilization of the application, use the following steps to configure the Performance Counter.

Performance Monitor – Asp.Net Requests profiling

The Windows Performance Monitor is a general purpose performance monitoring tool which can be used to monitor performance of windows and web applications. The tool can be customized to monitor specific parameters like Memory Utilization, CPU Utilization, Disk I/O etc of the system at any given point of time or over a specific time interval.

In this post we shall see on how to use the Performance Monitor tool monitor performance of an Asp.Net application based on the number of requests processed per second. This is just one of the counters, there a hundreds of such counters which can be used to measure various parameters of an Asp.Net application.

To measure the number of request processed by Asp.Net per second, use the following steps to configure the Performance Counter.

Advantages of Performance Monitor

The Windows Performance Monitor is the first and basic Performance Monitoring tool used by any developer or system admin, since is it part of the Windows operating system, needs to download or installation it is per-build when you install Windows.

The following are the advantages of the Performance Monitor Tool

What is a Performance Monitor?

The Windows Performance Monitor is a performance monitoring tool, which come along with the windows operating system. The Performance Monitor tool provides various performance counters and factors which can be used to analyze and determine the performance of a system on a whole or that of a specific process over a specific period of me.

Performance Monitor can be started by typing the command PerfMon in the Run window. The tool can also be opened from the control panel as follows.

PerfView – JIT Status Report

The PerfView is a performance analysis tool from Microsoft, the tool can be used to analyze application performance of both Windows and Web based applications. In this post we shall see on how to analyze the data about the runtime JIT compiler, to determine the code and utilization of the application. This report provides details about the size of the JIT and Native code for every function / method in the application. This will help us to determine any oversized methods and fix it by breaking them appropriately.

To analyze the JIT Status of an application follow the below steps.

PerfView – GC Heap Allocation Report

The PerfView is a performance analysis tool from Microsoft, the tool can be used to analyze application performance of both Windows and Web based applications. In this post we shall see on how to analyze the data about Heap, to determine the GC Heap Allocation of the application.

To analyze the GC Heap Allocation of an application follow the below steps.

PerfView – DISK I/O Stack Report

The PerfView is a performance analysis tool from Microsoft, the tool can be used to analyze application performance of both Windows and Web based applications. In this post we shall see on how to analyze the data about DISK I/O, to determine the Disk Utilization of the application.

To analyze the DISK I/O Utilization of an application follow the below steps.

PerfView – CPU Stack Report

The PerfView is a performance analysis tool from Microsoft, the tool can be used to analyze application performance of both Windows and Web based applications. In this post we shall see on how to analyze the data about CPU usage, to determine the CPU Utilization of the application.

To analyze the CPU Utilization of an application follow the below steps.

PerfView - Managed Stack Snapshot Report

The PerfView is a performance analysis tool from Microsoft, the tool can be used to analyze application performance of both Windows and Web based applications. In this post we shall see on how to analyze the data from the Managed Stack, to determine the memory utilization of the application.

To analyze the Memory utilization and Stack details of an application follow the below steps.

PerfView - Managed Heap Snapshot Report

The PerfView is a performance analysis tool from Microsoft, the tool can be used to analyze application performance of both Windows and Web based applications. In this post we shall see on how to analyze the data from the Managed Heap, to determine the memory utilization of the application.

To analyze the Memory Utilization and Heap details of an application follow the below steps.

Advantages of PerfView

PerfView is a performance analysis tool, developed by the Microsoft Performance Team to debug and analyze memory and CPU related performance issues.

PerfView has the following advantages.

What is PerfView

PerfView is a performance analysis tool, developed by the Microsoft Performance Team to debug and analyze memory and CPU related performance issues.  It is a light weight component that makes sure that running the tool is not an overhead to the server or workstation.

PerfView tool is very handy, it does not need any installation and configurations to be done, you can just download and start working on it with a single click.

PerfView uses the following sources of information to do its analysis.

Friday, June 14, 2013

CLR Profiler – Object Allocation Report for a Web Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Object Allocation” report shows the structure of the Managed heap, when the application was executing.

To view the “Object Allocation” report, use the following steps.

CLR Profiler – Object Aging report for an Asp.Net Web Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Histogram by Age” report shows the object allocating aging report which shows the object allocation across time intervals.

To view the “Histogram by Age” report, use the following steps.

CLR Profiler – Analyzing Object Memory Allocation for a Web Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Histogram Allocated Types” report shows the various types of objects which were created and allocated during the execution of the application. This report shows you on the share of object allocation to the Small Object Head and the Large Object Heap.

To view the “Histogram Allocated Types” report, use the following steps.

Using CLR profiler to Profile an Asp.Net Web Application

The CLR Profiler can be used to profiler your windows / web application. The CLR Profiler provides useful inputs in how the application is executed in the underlying runtime environment.

Before you profile your application using the CLR Profiler make sure that you are using the correct version of the CLR Profiler which matches with the version of the framework which was used to develop the application. Also make sure to select the format of the CLP Profiler 32/64 bit based on how you developed your application.

Once you selected the correct CLR Profiler, use the following steps to profile your web application.

CLR Profiler – Call Tree Report for a Windows Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Call Tree” report shows the object allocations done to the Heap over a specific time period.

To view the “Call Tree” report, use the following steps.

CLR Profiler – Timeline Graph Report for a Windows Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Timeline Graph” report shows the object allocations done to the Heap over a specific time period.

To view the “Timeline Graph” report, use the following steps.

CLR Profiler – Managed Heap Report for a Windows Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Object by Address” report shows the structure of the Managed heap, when the application was executing.

To view the “Object by Address” report, use the following steps.

CLR Profiler – Object Aging report for a Windows Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Histogram by Age” report shows the object allocating aging report which shows the object allocation across time intervals.

To view the “Histogram by Age” report, use the following steps.

CLR Profiler – Analyzing Object Memory Allocation for a Windows Application

The CLR Profiler provides various types of reports which help in determining the performance of the application and tuning it. The “Histogram Allocated Types” report shows the various types of objects which were created and allocated during the execution of the application. This report shows you on the share of object allocation to the Small Object Head and the Large Object Heap.

To view the “Histogram Allocated Types” report, use the following steps.

CLR Profiler error - Waiting for application to start common language runtime

Error:
When you try to analyze your application using the CLR Profiler, you might get the following error at times.

Waiting for application to start common language runtime

Cause:
The reason for this error could be one of the following.
1. The CLR Profiler is not compatible with the version of .Net Framework used by your application.
2. The CPR Profiler you choose 32/64 bit is not compatible with your Application

Resolution:

Using CLR profiler to Profile a Windows Application

The CLR Profiler can be used to profiler your windows / web application. The CLR Profiler provides useful inputs in how the application is executed in the underlying runtime environment.

Before you profile your application using the CLR Profiler make sure that you are using the correct version of the CLR Profiler which matches with the version of the framework which was used to develop the application. Also make sure to select the format of the CLP Profiler 32/64 bit based on how you developed your application.

Once you selected the correct CLR Profiler, use the following steps to profile your windows application.

Advantages of CLR Profiler

The CLR Profiler is a very handy tool especially when you are analyzing your application for performance issues. The CLR Profiler shows a clear picture of what is happening behind the scene when your application is running, it shows the state of the Managed Heap, the cycles run by Garbage Collection. This information will be very useful in identifying performance bottlenecks and memory related issues in your application.

The CLR Profiler is a free tool and is developed and distributed by the Microsoft Performance team, hence it integrates seamless with .Net Applications

The following are some of the advantages of using the CLR Profiler.

CLR Profiler for .Net 4.0

We have seen about the memory allocation in Stacks, Heaps, Garbage collections etc. in order to examine these things and find out memory leakages and other memory related issues, we need some kind of tools to see the status of Stacks, Heaps etc.

There are a number of free and paid tools available in the market which can analyze the state of the application, state of Stacks, Heaps, Garbage Collection etc. Microsoft provides a free tool “
CLR Profiler”, which allows developers to see the allocations made their managed application.

The
CLR provides the following information which will be very useful in analyzing the state of your applications, and investigation the causes behind issues like Memory Leakages etc.

Sunday, June 9, 2013

Dispose Vs Finalize

Both Dispose and Finalize are used to release un-managed resources, however there are many differences between the way Dispose and Finalize operates.

The Dispose() method should be explicitly defined in the class, and the program using the instance of the class should explicitly call the Dispose method.

Finalize is not explicitly defined, Finalize code is written in the destructor of the class, and is called automatically when Garbage Collection runs.

Finalize in C#

The Finalize block in C# .Net is used to clear un-managed resources before an object is destroyed. Classes / Objects which use un-managed resources should implement the Finalize method and clear all the un-managed resources they use in the Finalize block.

Unlike the Dispose() method, Finalize does not have an explicit Finalize() method in C#, instead the destructor of the class acts as the Finalize() block for the class.

The following example shows on how to declare the Destructor/Finalize block for a class.

Advantages of using Statement in C#

We know that classes using un-managed resources should implement the IDisposable interface, override the Dispose() method and clear all the un-managed resources in the Dispose() method. Even if all these are done properly, what if the code using the object does not call the Dispose() method, the un-managed resources will remain in memory till Garbage Collection runs and clears them.

Whenever we use a class which implements the IDisposable interface, we should make sure that we call the Dispose() method of the class after using the object of the class. But we might at time forget to call the Dispose() method and this will hold the um-managed resources in memory till Garbage Collection runs. The using statement helps us avoid these situations by calling the Dispose method automatically.

The following example explains on how to use the using statement.

Dispose & IDisposable in C#

The Dispose method in .Net is used to clear out un-managed resources like file stream, database connection etc once an objects goes out of scope.

In .Net resources are not clear immediately, when they go out of scope, instead they are maintained in the Managed Heap and wait for Garbage Collection to run and clear the resources. However network, resources like file stream and database connections wait till Garbage Collection runs and releases them, these resources are shared and should be freed as soon as possible for other objects to use them, hence .Net introduces a special method called the Dispose() method which can be used to clear all such un-managed resources.

Garbage Collection Improvements in .Net 4.5

The .Net framework 4.5 introduces a set of feature improvements to Garbage Collection, which helps it to perform more effectively. We know that the earlier versions of Garbage Collection had some limitations like performance issues when a full Garbage Collection happens, fragmentation issues with the large object heap etc. The Garbage Collection which comes with .Net 4.5 addresses some of these issues.

The following are some of the key improvements to Garbage Collection which ships with .Net 4.5

Saturday, June 8, 2013

Limitations of Garbage Collection

The .Net Garbage Collection offers a lot of advantages like frees the developers from having to allocate and dispose memory for the objects they create in their programs, using the most efficient way to allocate and dispose memory, etc.

Though there are many advantages of Garbage Collection, there are a few limitations in the way Garbage Collection operates; the following are some of the Limitations of Garbage Collection.

Garbage Collection Generations

Garbage Collection involves monitoring the Managed Heap, clearing off objects which are not used and reclaiming the memory used by those objects to make it available for the objects which gets created during the program execution.

Garbage Collection doesn't remove unused objects from the heap randomly, doing so might cause an overhead of re-creating frequently used objects again and again, to overcome this Garbage Collection employs a logic called Generations.

The Managed Heap is organized into a set of Generations, allocation of objects into each of this generation depends on the type of the object and the life time of the object.

The Heap is organized into 3 Generations

GC.Collect

We know that Garbage Collection is automatic and is managed by the runtime, but there might be situation when you want to explicitly force Garbage Collection to happen from your applications. The GC.Collect() method does exactly this, it forcefully initiates a Garbage Collection run.

In general it is not advisable to use GC.Collect() from your code, since the runtime by itself will determine the most optimal time and way to run Garbage Collection. However you can still use GC.Collect() if you are sure that there are no critical operations planned to happen for the next few seconds.

The following are some of the situations when you might want to call GC.Collect()

When does Garbage Collection Run?

Garbage Collection is completely controlled by the .Net runtime, generally we need not force the Garbage Collector to run, as this will lead to degradation in performance, but still you can force the Garbage Collector to run by calling the GC.Collect method.

The .Net runtime decides on the best time to run the Garbage Collection by evaluating various parameters on the available memory and other factors, the following are some of the situations when the .Net runtime triggers Garbage Collection.

Advantages of Garbage Collector

The Garbage Collector does automatic memory management for application running in the .Net. The Garbage Collector makes sure that it reclaims unused memory and provides it the new objects which get created as the program runs.

We know that all the reference type objects are stored in the Heap and it does not get cleared by itself, the garbage collector monitors the state of the heap and removes unused objects to reclaim the memory used by those objects.

The following are the advantages of Garbage Collector.

Friday, June 7, 2013

What is a Garbage Collector?

The Garbage Collector is a mechanism employed by the .Net runtime to manage the memory of objects added to the managed heap. Variables and references stored in a Stack Frame are cleared (popped) out once the method execution gets completed, but this is not the case for Heaps, there is no mechanism to clear the objects loaded into the Heap, this is where the Garbage collector comes into play.

Memory Management of Static variables in .Net

We have seen that the .Net run-time manages the variables and objects in Stacks and Heaps based on their type. Value types are stored in the Stack and reference types are stored in the Heap. This is fine for normal variables, but what happens to static variables.

Static variables cannot be treated like other variables, because static variables and methods in a static class can be accessed directly without creating instances of the class. In this post we shall see on how the .net run-time does memory management for static variables.

Memory Management of Threads in .Net

We have seen that the .Net run-time manages the variables and objects in Stacks and Heaps based on their type. Value types are stored in the Stack and reference types are stored in the Heap. This is fine for a single threaded application, what happens when your application uses multiple threads?
We shall see on how memory is allocated and de-allocated for multi-threaded applications in this post.

Thursday, June 6, 2013

UnBoxing

As the name suggests UnBoxing is the reverse of Boxing. In Boxing we saw that a value type gets converted into a reference type, UnBoxing is conversion of the reference type back to a value type.

We will continue with our example which we used for Boxing and implement UnBoxing by adding one more line of code to explain UnBoxing.


Boxing

Conversion of a value type to a reference type is termed as Boxing.

For example int is a value type, when we try to assign an int to an object, it gets converted to a reference type this is called boxing. When a value type is converted into a reference type it will be moved to the Heap. Stack is more efficient than Heap, hence we should avoid Boxing as much as possible.

The following example causes Boxing to happen.

Heap Memory management in .Net

Heaps are used to store reference type objects, the .Net runtime uses types of heaps to store objects.

Small object Heap: Used to store objects with size < 85K Bites
Large object Heap: Used to store objects with size > 85K Bites.

Heaps are used to store reference types like classes, objects, delegates etc. based on the size of the object the runtime decides where to place the object, either in the small object heap or large object heap.

Stack Memory management in .Net

A Stack is a Last-In-First-Out data structure called shortly as LIFO. In .Net a Stack is used to store the details of variables and parameters which are used for executing a program. Stacks are used to store value types which include the built in types and structs.

In a Stack values keep get added one on top of the other, i.e the first object added to the stack goes to the bottom of the stack and the subsequent objects get added on top of the first object. Removing objects happens from the top of the stack, i.e the value which gets added at last to the stack will get removed first. Hence this is called a Last-In-First-Out (LIFO) data structure.

.Net runtime used the Stack data structure to store all primitive variables like int, string, bool etc and to store the programming execution sequence i.e the sequence in which methods get called.

Let us consider the following example.

Memory Management in .Net

Memory Management is the concept by which memory is allocated and de-allocated to the variables and objects which we use in our normal day to day programming. .Net helps us to ease memory management by automatically allocating and de-allocating memory to the variables and objects.

The runtime takes care of allocating Memory, when we declare a variable or create an instance of an object the runtime automatically allocates memory to the variable or object, similarly when the object or variable goes out of scope the runtime takes care of clearing the memory used using a mechanism called Garbage Collection.

Memory for the variables and objects are allocated in Stack and Heap, we shall see on how this is done in detail in the following posts.

Wednesday, June 5, 2013

Runtime Polymorphism

In C# Dynamic Polymorphism or Runtime Polymorphism is achieved using the concept of inheritance; the methods defined in the base class can be overridden in the derived class and can be called dynamically at runtime.

The following example explains Dynamic or Runtime Polymorphism.

Dynamic Polymorphism

In C# Dynamic Polymorphism or Runtime Polymorphism is achieved using the concept of inheritance; the methods defined in the base class can be overridden in the derived class and can be called dynamically at runtime.

The following example explains Dynamic or Runtime Polymorphism.

Compile time Polymorphism

In C# Static Polymorphism or Compile time Polymorphism is achieved through function/method overloading.

Function overloading refers to having many functions with the same name but with different signatures i.e the names of the functions will be same but will vary in any one of the following.

1. Number of parameters
2. Type of parameters
3. Return Type.

The following example explains Static or compile time Polymorphism.

Static Polymorphism

In C# Static Polymorphism or Compile time polymorphism is achieved through function/method overloading.

Function overloading refers to having many functions with the same name but with different signatures i.e the names of the functions will be same but will vary in any one of the following.

1. Number of parameters
2. Type of parameters
3. Return Type.

The following example explains Static or compile time Polymorphism.

Polymorphism

Polymorphism is one of the key concepts of object oriented programming; polymorphism enables us to have different methods with the same name. The appropriate method to be called will be decided at compile/run time.

There are 2 types of Polymorphism.

Static / Compile time Polymorphism
Dynamic / Runtime Polymorphism.

Tuesday, June 4, 2013

Inheritance

Inheritance is one of the key concepts of object oriented programming, Inheritance helps us to reuse/extend the methods and properties of another class. The class which extends these members is called derived class and the original class is called the base class. Apart from reuse/extend inheritance helps in standardizing the basic features of the classes.

For example let us consider we want to create objects for Car, Bus, Jeep etc. Here all these are vehicles and have some property in common, hence we can create a base class say Vehicle and add the basic properties like Make, Model, Color etc to the base class, this way we make sure that any class which inherits the base class will have these properties.
In C# inheritance is defined using the colon (:) symbol, with the following syntax.

class : Derived Class Name : Base Class Name

Abstraction

Abstraction in OOPs means, hiding or abstracting something. Abstraction helps in hiding requirements which are not required for the actual implementation; this might sound similar to encapsulation. Yes Encapsulation and Abstraction concepts complement each other.

Abstraction tends to hide the full complexity of the system form the external world and show only the details which are required to use the features exposed by the object. The actual functionality might depend on many other parameters which are not required to be exposed to the outside world; abstraction hides these and shows only those details which are required to use the system.

The following class explains the concepts of Abstraction.

Encapsulation

Encapsulation is a combination of 2 concepts.

The first one is encapsulating a set of related methods properties into a single unit so that it can be exposed as a single instance to the external world. In C# this is implemented using the concept of classes. A class allows us to group a set of related variables and methods into a single unit and they can be accessed by creating a single instance of the class.

The second one is data hiding, i.e showing only the required details to the external world and hiding the other details which are not required to be exposed. Again this is implemented using classes and a set of access modifiers.

C# OOPs Concepts

Object oriented programming focuses on developing structured reusable programming modules, most of the modern programming languages support the OOPs concepts. Software design patterns are based on the object oriented concepts.

The following are some of the key object oriented concepts.

Monday, June 3, 2013

IEnumerable Vs IQueryable

IQueryable

The
IQueryable interface allows the objects to be queried based on the LINQ-to-SQL. Objects which implement the IQuerieable interface can be further queried using LINQ queries and these additional queries will be executed on the underlying data source.

The below line first queries the list of employees from the datasource, the resultant object empList is further queried based on the department name of the employee, both the filters are done in the underlying datasource and only the final list of employees belonging to the sales department are returned and stored in the memory, using LINQ-to-Sql. Hence more efficient based on
IEnumerable based objects.

IQueriable Interface

The IQueriable interface is used to execute queries against a data source, where the type of ata returned from the source is not known at design time.

IQueriable interface inherits from the IEnemurable interface, and allows the objects to be queried based on the underlying data source, hence they are more efficient when the types are to be queried/filtered further.

Namespace:  System.Linq 

IEnumerable T Interface

The IEnumerable interface exposes the enumerator, which supports a simple iteration over a collection of a specified type.

Namespace:  
System.Collections.Generic.

While using IEnumerable we provide the type along with the data, represents the type of data which will be stored in the collection.

Sunday, June 2, 2013

IEnumerable Interface

The IEnumerable interface exposes the enumerator, which supports a simple iteration over a non-generic collection.

Namespace:  System.Collections

.Net Framework pre-defined Interfaces

The .Net framework itself is built with a number of interfaces, each of these interfaces are pre-defined and have a specific purpose. The classes which implement these interfaces should override the methods in these interfaces, this way .Net makes sure that all the classes which implement the interfaces are consistent. The classes can add their own methods but they should definitely implement the methods defined in the interface.

The following are some of the commonly used interfaces which are per-defined in the .Net framework.

Accessing Methods of Explicit Interfaces

We have seen on how to implement more than one interface which have methods/properties with the same name and signature using explicit interfaces. Now how do we create instance of the class and call these methods individually.

The following example contains 2 interfaces IEmployee and IDepartment, both the interfaces contain a method GetName() with the same name and signature. The class OfficeClass implements both the interfaces and implements the GetName method from both the interfaces using Explicit Interface Implementation.

Explicit Interface Implementation

We know that a class can implement more than one interface, now what if a class implements 2 interfaces and if both the interfaces contain a method with the same name and signature, how do we implement these methods in the class body. This is where explicit Interface comes into play. In such cases the method name should be prefixed with the interface name and a (.) symbol.

The following example contains 2 interfaces IEmployee and IDepartment, both the interfaces contain a method GetName() with the same name and signature. The class OfficeClass implements both the interfaces and implements the GetName method from both the interfaces using Explicit Interface Implementation.

Interface Inheritance

Similar to class inheritance, interfaces also support inheritance, an interface can inherit from another interface. Similar to class inheritance, interface inheritance also makes use of the (:) operator to define inheritance.

The following example defines a parent interface IVehicle, and a child interface IBus, the IBus interface inherits from the IVehicle interface.

What are Interfaces?

An Interface defines a set of methods and properties which should be implemented in the class which implements the interface. Interfaces help us in implementing the concept of multiple inheritances in C#. In C# a class cannot derive from more than one parent class, but can implement more than one interface, hence they help us in implementing multiple inheritance.

In the following example the Interface IEmployee defines 2 methods and the class EmployeeClass implements this interface and adds the method definition to both these methods declared in the interface.

Virtual class Modifier

The Virtual modifier is used to specify that a method or property can be overridden in the derived child class. Unlike the other class modifiers which are used at the class level , the virtual modifier cannot be used at the class level, instead it is used to modify the behavior of the functions and properties of the class.

The following example defines a class with a virtual function which is overridden in the derived class.

Static class Modifiers.

When a class is defined as a static class its members can be accessed without creating an instance of the class. Static classes are useful when we want to define members which do not vary from one instance to another.

The following example creates a static class with a static variable and a function.

Partial class Modifier

Partial class modifiers are used to define a single class across multiple files, this modifier is useful when we want to write large and complex classes. Splitting the class across multiple files improves the readability of the class and improves maintainability.

In the following example we shall define a single class in 2 files by adding the modifier partial to the class, create an instance of the partial class and invoke the methods which are defined in both the files.

Sealed class Modifier

A sealed class modifiers prevents the class from getting inherited, cases marked with sealed cannot be derived by other classes, trying to do so will result in a complier error.

In the following example we try to define a sealed class and try to inherit the same from a derived class.

Abstract Class Modifier

The Abstract Class modifier is used to define base classes which can be derived by other classes. An Abstract class cannot be instantiated i.e we cannot create objects from an Abstract class, trying to do so will result in a compiler error.

Abstract class generally declare only the signature of the methods, the actual method body is coded in the derived class, however it doesn’t not stop us from adding a method body in the abstract class, we can still go ahead and do some code to the method body in the base abstract class.

The following example creates a simple abstract class, and a derived class which inherits from the Abstract class.

New Class Modifier

The new class modifier is used in derived classes when the derived class declared a member with the same name / signature which already exists in the base class.

When a member is declared in the derived class using the same name / signature of a member which already exists in the base class the following warning is thrown.

What are Class Modifiers

Class Modifiers are keywords which are used to add special meaning / purpose to a class. We have seen about access modifiers in the “Access Modifiers” section, access modifiers are general and can be applied to classes and class members, similarly class modifiers are special keywords which can be added to the class definition to alter the behavior of the class.

The following are the class modifiers available in C# .Net

Saturday, June 1, 2013

Access Levels

Access Levels are defined using access modifiers and combinations of access modifiers, access levels define different levels of accessibility to classes and its members by specifying an individual access modifier or combining access modifiers.

The following are the available Access Levels in C#