Author Archives: admin

Interfaces in C# Explained


Interface in C# contains definitions for a group of related features that a struct or a class can decide to implement.

By implementing an interface, you are able to incorporate behaviours from different sources into your class. This feature is very useful particularly considering that C# does not support Inheritance from multiple classes. Also as structs do not support inheritance, you can use interface to simulate inheritance from structs.

An interface has the following properties:

• An interface is like an abstract base class. Any class or struct that implements the interface must implement all its members.
• An interface can’t be instantiated directly. Its members are implemented by any class or struct that implements the interface.
• Interfaces can contain events, indexers, methods, and properties.
• Interfaces contain no implementation of methods.
• A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

You can define an Interface in C# using the interface keyword as shown below:

interface IEquatable<T>
    bool Equals(T obj);


Interfaces can contain the following:

• methods
• properties
• events
• indexers
• any combination of the above four member types.

An interface can’t contain the following:

• constants
• fields
• operators
• instance constructors
• destructors
• types

Interface members are automatically public, and they can’t include any access modifiers. Members also can’t be static

To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
When a class or struct decides to implement an interface, it must provide an implementation for all of the members that the interface defines.
The interface itself does not provide any implementation that a class or struct can inherit. However, if a base class implements an interface, any class that’s derived from the base class inherits that implementation.

The following example shows an implementation of the IEquatable interface. The implementing class, Car, must provide an implementation of the Equals method.

interface IEquatable<T>
    bool Equals(T obj);

public class Car : IEquatable<Car>
    public string Make {get; set;}
    public string Model { get; set; }
    public string Year { get; set; }

    // Implementation of IEquatable<T> interface
    public bool Equals(Car car)
        if (this.Make == car.Make &&
            this.Model == car.Model &&
            this.Year == car.Year)
            return true;
            return false;

Interfaces (C# Programming Guide)

Batching Techniques for SQL Database Applications in Azure

Batching operations can be very helpful in improving your performance and scalability for your in house application as well as cloud applications.

Here are some of the batching techniques available for you to consider:


Client side code based transactions can be simple and useful. Here is an example:

<pre>using (SqlConnection connection = new SqlConnection(CloudConfigurationManager.GetSetting("My.ConnectionString")))



SqlTransaction transaction = conn.BeginTransaction();


foreach (string commandString in dbOperations)


SqlCommand cmd = new SqlCommand(commandString, conn, transaction);







Table-Valued Parameters

In code, you create a DataTable with the exact same names and types of the table type. Pass this DataTable in a parameter in a text query or stored procedure call. The following example shows this technique:

using (SqlConnection connection = new SqlConnection(CloudConfigurationManager.GetSetting("Sql.ConnectionString")))




DataTable table = new DataTable();

// Add columns and rows. The following is a simple example.

table.Columns.Add("mytext", typeof(string));

table.Columns.Add("num", typeof(int));

for (var i = 0; i &lt; 10; i++)


table.Rows.Add(DateTime.Now.ToString(), DateTime.Now.Millisecond);



SqlCommand cmd = new SqlCommand(

"INSERT INTO MyTable(mytext, num) SELECT mytext, num FROM @TestTvp",



new SqlParameter()


ParameterName = "@TestTvp",

SqlDbType = SqlDbType.Structured,

TypeName = "MyTableType",

Value = table,






SQL Bulk Copy

SQL bulk copy is another way to insert large amounts of data into a target database. .NET applications can use the SqlBulkCopy class to perform bulk insert operations. SqlBulkCopy is similar in function to the command-line tool, Bcp.exe, or the Transact-SQL statement, BULK INSERT. The following code example shows how to bulk copy the rows in the source DataTable, table, to the destination table in SQL Server, MyTable.

Here is an example:

using (SqlConnection connection = new SqlConnection(CloudConfigurationManager.GetSetting("Sql.ConnectionString")))
{    connection.Open();    
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))   
bulkCopy.DestinationTableName = "MyTable";       
bulkCopy.ColumnMappings.Add("mytext", "mytext");       
bulkCopy.ColumnMappings.Add("num", "num");       
bulkCopy.WriteToServer(table);    }}


Multiple-row Parameterized INSERT statements

One alternative for small batches is to construct a large parameterized INSERT statement that inserts multiple rows. The following code example demonstrates this technique.

using (SqlConnection connection = new SqlConnection(CloudConfigurationManager.GetSetting("Sql.ConnectionString")))
string insertCommand = "INSERT INTO [MyTable] ( mytext, num ) " +       
"VALUES (@p1, @p2), (@p3, @p4), (@p5, @p6), (@p7, @p8), (@p9, @p10)";    
SqlCommand cmd = new SqlCommand(insertCommand, connection);    
for (int i = 1; i &lt;= 10; i += 2)   
              cmd.Parameters.Add(new SqlParameter("@p" + i.ToString(), "test"));       
              cmd.Parameters.Add(new SqlParameter("@p" + (i+1).ToString(), i));    }    

Data Adapter

The DataAdapter class allows you to modify a DataSet object and then submit the changes as INSERT, UPDATE, and DELETE operations. If you are using the DataAdapter in this manner, it is important to note that separate calls are made for each distinct operation. To improve performance, use the UpdateBatchSize property to the number of operations that should be batched at a time.



The use of XML has no advantages over other methods and several disadvantages. The approach is similar to table-valued parameters, but an XML file or string is passed to a stored procedure instead of a user-defined table. The stored procedure parses the commands in the stored procedure.

There are several disadvantages to this approach:

  1. Working with XML can be cumbersome and error prone.
  2. Parsing the XML on the database can be CPU-intensive.
  3. In most cases, this method is slower than table-valued parameters.




Batching Techniques for SQL Database Applications in Azure

OOPS Concepts Tips: Inheritance in C#

Inheritance is one of the key features in OOPS and C# does support the OOPs principles. Because of the principle of Inheritance you can create a new class that can extend, reuse or modify the behavior and operations of another class.
The class whose members are inherited by another class is called the base class and the class which inherits are called the derived class.
In C# all the classes are implicitly inherited from the Object Class, which is the base class and provides support to all the .Net classes and gives basic services to all classes.

Here is an example to inherit from a base class in C#:

class MyDerivedClass:MyBaseClass{}

By default in C# all classes can be inherited, but you can explicitly specify if you do not want a class to be inherited by other classes. Here is how you do it in C# using the sealed keyword.

public sealed class MyClass { } 

Also if you want a class to be used only as a base class and should not be instantiated, you can do so with the abstract key word. Here is an example:

public abstract class MyClass { }

Design Patterns: Articles from MSDN

If you are an experienced developer and always on a look out for ways of smarter development, sure you are not to miss on Design Patterns. Patterns are everywhere, in our day to day life. Its there in the problems we face and the solutions we come up with.. if you can just insightfully recognize those patterns, life would be much easier.. Here is a good collection of Articles on Design Patterns from MSDN…

Explore it..

Design Patterns: Exploring the Singleton Pattern

Singleton Pattern The intent of the Singleton pattern as defined in Design Patterns is to “ensure a class has only one instance, and provide a global point of access to it”. What problem does this solve, or put another way, what is our motivation to use it? In nearly every application, there is a need to have an area from which to globally access and maintain some type of data. There are also cases in object-oriented (OO) systems where there should be only one class, or a predefined number of instances of a class, running at any given time. For example, when a class is being used to maintain an incremental counter, the simple counter class needs to keep track of an integer value that is being used in multiple areas of an application. The class needs to be able to increment this counter as well as return the current value. For this situation, the desired class behavior would be to have exactly one instance of a class that maintains the integer and nothing more. At first glance, one might be tempted to create an instance of a counter class as a just a static global variable. This is a common technique but really only solves part of the problem; it solves the problem of global accessibility, but does nothing to ensure that there is only one instance of the class running at any given time. The responsibility of having only one instance of the class should fall on the class itself and not on the user of the class. The users of the class should always be free from having to monitor and control the number of running instances of the class. What is needed is a way to control how class instances are created and then ensure that only one gets created at any given time. This would give us exactly the behavior we require and free a client from having to know any class details.
Read On….

Design Patterns: Exploring the Observer Pattern

Observer Pattern One of the overriding principles of object-oriented development is the proper assignment of responsibility in the given application. Each object in the system should focus on a discrete abstraction within the problem domain and nothing more. In short, an object should do one thing and do it well. This approach ensures that a crisp boundary exists between objects, enabling greater reuse and system maintainability. One area where the proper separation of responsibility is of special importance is the interaction between the user interface and the underlying business logic. During the development of an application, it is quite common for user interface requirements to change rapidly without an associated impact on the rest of the application. In addition, it is also likely that the business requirements will change without regard to the user interface. In many cases, both sets of requirements will change, as anyone with substantial development experience well knows. Without the benefit of separation between the UI and remainder of the application, modification of either portion may adversely impact the whole. The need to provide a distinct boundary between the user interface and business logic is a common problem that spans applications. As a result, a number of object-oriented frameworks developed since the inception of the GUI have supported the wholesale separation of the user interface from the remainder of the application. Not surprisingly (well maybe a little), most of these adopted a similar design pattern to provide this functionality. This pattern, commonly known as Observer, is advantageous in creating a clear distinction between various objects in the system. In addition, it is not uncommon to find this solution utilized within non-UI related segments of a framework or application as well. As with most other patterns, the usefulness of the Observer pattern extends far beyond its original intent.
Read On…


How to Enable Development Errors in CRM?

CRM by default tends to throw a General error for any error that occurs. If you need to have a more specific error, enable DevErrors in Web.config.

To do it do the following:

Step 1: Goto the CRM Web Server to the Web Installation path.

Step 2: Open the Web.config file

Step 3: Change the value of DevErrors Key to ‘On’

Step 4: Save the Web.config file.

Now CRM should show up more specific errors.

Explain Factory Design Pattern

An important facet of system design is the manner in which objects are created. Although far more time is often spent considering the object model and instance interaction, if this simple design aspect is ignored it will adversely impact the entire system. Thus, it is not only important what an object does or what it models, but also in what manner it was created. Since most object-oriented languages and runtimes provide object instantiation (e.g. new, newobj, etc.) and initialization (e.g. constructors) mechanisms, there may be a tendency to simply use these facilities directly without forethought to future consequences. The overuse of this functionality often introduces a great deal of the inflexibility in the system, as the direct use of a language/run-time object instantiation function creates an explicit association between the creator and created classes. While associations are a necessary type of relationship in an object-oriented system, the coupling introduced between classes is extremely difficult to overcome should requirements change (as they always do). Since the need to reduce the inherent coupling associated with instance creation spans systems, it was not uncommon to see the same types of solutions being used in a variety of different applications and frameworks. Formalized within Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Publishing Company, 1995), these solutions are known as creational patterns. Creational patterns describe object-creation mechanisms that enable greater levels of reuse in evolving systems. One of the most widely used creational patterns is the Factory.

Read On…

Some Essential Elements on Design Patterns

Here are some Essential Elements of Design Patterns. It basically has four key elements.

1. The Name of the Pattern, that we use to describe and identify a design problem.

2. Secondly the Problem which describes when to apply the pattern.

3. The solution that describes the elements or artifacts that make up the design,and

4. Finally, the consequences that come up as a result of applying the pattern.

Those were just the Tip of the Iceberg, explore them

Threading Design Tips

Threading is a valuable programming technique to make applications more scalable and responsive. Weather you are aware of it or not, it is likely that the programs you are writing are using some aspect of threading – this is particularly true of web applications where web page requests are handled by a thread pool in the web server. Programming in a threaded environment requires experience and care to avoid issues such as deadlocking and race conditions. The threading knowledge pack is designed to help you create thread-safe code easily so your software is more responsive and scalable.

Protect Static Data with Thread Synchronization: Static data should be effectively protected from possible threading issues by using appropriate synchronization methods. Avoid calling static methods that call static methods on the same class: Performance issues can result when a static method in class calls another static method in the same class. Avoid providing static methods that alter static state: Avoid providing static methods that alter static state. Static state is shared across threads which means multiple threads can execute that code at the same time opening up the possibility for threading bugs. Use thread pooling classes to optimize multi-threaded applications: Avoid using System.Threading.Thread class to create threads unless you have special needs. Instead usage of system thread pool (ThreadPool class) can improve your performance and scalability.

Do not terminate other threads using Thread.Abort: Avoid calling Thread.Abort method, instead use Thread.Join to wait until desired thread finishes. Excessive use of thread synchronization: Excessive locking or thread synchronization can cause significant scalability and performance issues and should be minimized Ensure lock release by using try/finally block: When using Monitor to synchronize your static data, you should ensure adequate release of the lock under any circumstance by using try/finally blocks.

Lock Must not be Obtained on a Value Type: Montor.Enter() and Exit() calls must lock on a reference type (in other words an object). They should never lock on a value type such as “int”.