Posts tagged: C#

Searching for Multiple Strings

By Ashish Khandelwal, July 5, 2011

Suppose you have an application that needs to search for all occurrences of multiple strings in a text stream. For example, you might want to search a large text file for all occurrences of “cycling”, “bicycling”, “bicycle”, “cycle”, “bike”, and other bicycling-related terms. This can be a more difficult task than it first appears.

The simple case

If the file is small, the task isn’t terribly difficult. You can read the entire file as a string into memory and then use standard string searching methods to find each string, as shown here.

private static void FindAllSimple(string textToSearch, string[] searchStrings)
{
    // brute force method
    foreach (var s in searchStrings)
    {
        int iPos = 0;
        int foundPos;
        while (iPos < textToSearch.Length && (foundPos = textToSearch.IndexOf(s, iPos)) != -1)
        {
            Console.WriteLine(“{0},{1}”, foundPos, s);
            iPos = foundPos + 1;
        }
    }

  Read more »

All about Multithreading (Concept, Issues and Synchronization)

By Ashish Khandelwal, June 30, 2011

Multithreading ensures that the program never “goes to sleep” by keeping UI more responsive to the user. In my blog I cover numbers of articles on multithreading programming, issues with multithreaded programming and the synchronization technique to handle these issues. I found it is worth to consolidate these all information at one place. Hopefully this will help visitor to quickly refer the topic.

What is Multithreading?

Article: Multithreading Read more »

LINQ to SQL Vs Entity Framework

By Ashish Khandelwal, June 8, 2011

LINQ to SQL and Entity Framework both are designed for ORM (Object Relational Model) support. They are developed to avoid the difficulties involved in writing Object Oriented code to perform RDMS operations. The OOP and RDMS are conceptually very different. The question arises when to use LINQ2SQL and when to use Entity Framework. What is the different between LINQ to SQL and Entity Framework.

LINQ to SQL and the Entity Framework have a lot in common, but each has features targeting different scenarios. While speaking about similarities or differences, I understand that ADO.NET Entity Framework’s LINQ to Entities can be considered as superset of LINQ to SQL and that, ADO.NET Entity Framework is much more than LINQ to Entities. Read more »

Hyperlink in ListBox

By Ashish Khandelwal, June 3, 2011

Today, one of my friends was asking me a question about how to add hyperlink text into the ListBox. I replied by adding respective control directly to the ListBox. Here in reply to my friend question, I am describing the steps:

Every Control in C#.net has a property called “Contorls” to add any control within it. I used the same to add LinkLable (Hyperlink text) to add into ListBox.

I have created one simple Windows Form application called “HyperLinkInListBox”. Added one windows form called “frmHyperLinkInListBox” and the following controls within the form:

  1. One ListBox control named “lstName” : this will display all the Names and will have hyperlink associated with it.
  2. One Label control “lblURL” : This will the URL associated with Name. So that when user will click on any Name in the ListBox, the respective URL will display here. Read more »

Interface vs Abstract class

By Ashish Khandelwal, April 20, 2011

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let’s explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined
Is-a vs able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

Understanding Destructors in C#

By Ashish Khandelwal, April 14, 2011

Introduction

This article is about understanding the working concept of destructor in C#. I know you all may be thinking why a dedicated article on simple destructor phenomenon. As you read this article you will understand how different is C# destructor are when compared to C++ destructors.

In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. The destructors enable the runtime system, to recover the heap space, to terminate file I/O that is associated with the removed class instance, or to perform both operations. For better understanding purpose I will compare C++ destructors with C# destructors. Read more »

C#: lock vs Monitor

By Ashish Khandelwal, April 12, 2011

They both are same but each one has some draw back and advantages.

lock is more concise over monitor; it releases the lock from the blocked code even if there is exception generated within blocked code. There could be deadlock with lock if we do not use it correctly, also when we use lock the thread will wait for infinite time to get the lock on object. Read more »

Events Programming in C# and .NET

By Ashish Khandelwal, March 13, 2011

In the early days of computing, a program would begin execution and then proceed through its steps until it completed. If the user was involved, the interaction was strictly controlled and limited to filling in fields.

Today’s Graphical User Interface (GUI) programming model requires a different approach, known as event-driven programming. A modern program presents the user interface and waits for the user to take an action. The user might take many different actions, such as choosing among menu selections, pushing buttons, updating text fields, clicking icons, and so forth. Each action causes an event to be raised. Other events can be raised without direct user action, such as events that correspond to timer ticks of the internal clock, email being received, file-copy operations completing, etc. In programming, you are often faced with situations where you need to execute a particular action, but you don’t know in advance which method, or even which object, you’ll want to call upon to execute it. For example, a button might know that it must notify some object when it is pushed, but it might not know which object or objects need to be notified.

C# adds on value to the often mentioned world of event driven programming by adding support through events and delegates. Read more »

Introduction to Objects and Classes in C#

By Ashish Khandelwal, March 1, 2011

In this article we will understand some of the concepts of object-oriented programming in C# like objects and classes. To read this article you must have C# programming basics.

Read more »

State Management in ASP.NET

By Ashish Khandelwal, January 25, 2011

Web form pages are HTTP-Based, they are stateless, which means they don’t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost, therefore state management is really an issue in developing web applications

We could easily solve these problems in ASP with cookie, query string, application, session and so on. Now in ASP.NET, we still can use these functions, but they are richer and more powerful, so let’s dive into it.

Mainly there are two different ways to manage web page’s state: Client-side and Server-side. Read more »

Shared Assembly

By Ashish Khandelwal, January 25, 2011

Introduction:

When you install the Visual Studio .NET, the common language runtime has the Global Assembly Cache (GAC). The GAC stores assemblies that are shared by the several applications on the computer called as Shared Assembly or Global assembly. This shared assembly is globally available to all the applications on the computer.

Changing private assembly into a shared assembly:

A private assembly is normally used by a single application and is stored in a application directory or sub-directory beneath. This assembly cannot be shared by other applications. To make it globally available this assembly we need to install assembly in the global assembly cache (GAC). But to be installed in a GAC, it must have a Strong Name. Read more »

Replacing File.Copy

By Ashish Khandelwal, January 12, 2011

The easiest way to copy a file in a .NET program is to call the File.Copy method, supplying it the source and destination files. It could hardly be simpler than this:

File.Copy(srcFilename, destFilename);

That method will throw IOException if there is an existing file of the same name as destFilename. If you want to overwrite existing files, call the overload and specify true for the overwrite parameter:

File.Copy(srcFilename, destFilename, true);

File.Copy certainly is very easy to use, but as I mentioned in the previous section, it suffers from the large file copy problem. That is, using File.Copy to copy a very large file from one machine to another can cause the source machine to run out of memory. For example, I encountered that problem when executing a statement of this form:

File.Copy(@"\\server\data\file.dat", @"d:\data\file.dat", true);

If you want to copy a file and not encounter those problems, you have to write your own copy method. Read more »

Copying Large Files

By Ashish Khandelwal, January 10, 2011

Windows Server 2008 provides at least three different command line utilities for copying files. The familiar COPY and XCOPY commands have been around since the early DOS days. And ROBOCOPY, a more robust and feature-rich tool, began shipping with Windows Vista and Windows Server 2008. These tools work just fine in most cases. But all three suffer from a fatal flaw when you’re trying to copy a file that’s larger than available memory.

Manifestation of the Problem

Our main servers are quad-core machines with 32 gigabytes of RAM, running the 64 bit version of Windows Server 2008. Our custom format repository file is about 90 gigabytes in size. That’s after compression. In addition to daily backups, I periodically need to copy that file to another computer. And that’s where the problems start. Read more »

string.GetHashCode() and HashTable calls GetHashCode() Differ?

By Ashish Khandelwal, November 11, 2010
—–See below code,
string str = “blair”;
string strValue = “ABC”;
string str1 = “brainlessness”;
string strValue1 = “XYZ”;
int hash = str.GetHashCode() ; // Returns 175803953
int hash1 = str1.GetHashCode(); // Returns 175803953
Hashtable ht = new Hashtable();
ht.Add(hash ,strValue);
ht.Add(hash1,strValue1); // ****ERROR****
string strTmp = (string) ht[str];
string strTmp1 = (string) ht[hash1];

In Above code when i try to call GetHashCode() for both str and str1,
it returns me same Hash Code ’175803953′, and that’s why when i try to
add into hashtable, exception generates which is normal (i know we
cannot add same key twice). Now…. see below code Read more »

C#: Thread Synchronization

By Ashish Khandelwal, July 27, 2010

This article describe .Net classes that can be used to synchronize access to resources in multithreaded applications.

One of the benefits of using multiple threads in an application is that each thread executes asynchronously. For Windows applications, this allows time-consuming tasks to be performed in the background while the application window and controls remain responsive. For server applications, multithreading provides the ability to handle each incoming request with a different thread. Otherwise, each new request would not get serviced until the previous request had been fully satisfied. Read more »