Archive

Archive for the ‘.Net’ Category

Extending DataTables Range Filter

November 15th, 2011

DataTables plug-in provides a very efficient and easier way to integrate grid style view on the client-side using basic HTML and JavaScript. Using this plug-in, you can produce filtering and sorting with many options. I have extended one of the column types. I have made a contribution on codeproject available on this link:
Link to CodeProject Article

.Net , , , , , , ,

Identifying Deadlocks using Windows Debugging Tools (WinDbg)

November 24th, 2010

If you had ever worked with multi-threaded applications, you will surely have faced situations where you have to troubleshoot deadlocks and it could be a nightmare to do so. You might have also worked with WinDbg. I came across a similar scenario and used WinDbg to identify deadlocks. So I thought its worth sharing. So here we go:

When we install Windows Debugging Tools and start using it, we came across number of issues which held us from following along. I was able to proceed by following following these steps:

Read more…

.Net , , , , , , , ,

Cross-site Scripting & Sql Injection

May 24th, 2009

 

There are many ways to inject into asp.net code. Some of the commonly used techniques are:

  • Sql Injection
  • Cross site scripting

 Lets discuss these techniques that how we may prevent from these attacks.

 Sql Injection

 Lets see an example for sql injection. Let’s say you input User’s NTN number to validate him/her in a text box. Let’s say  user inputs the following text in the text box:

 ’ ; DROP DATABASE orders –

 Now the code might have sql string like below:

 SELECT lname, fname, address FROM TaxedUsers WHERE NTN = ‘XXXXXXXX’

 With the input of above type, user will execute following sql:

 SELECT lname, fname, address FROM TaxedUsers WHERE NTN = ”; DROP DATABASE orders –’

 The above statement will be parsed in two steps, first will be terminated on semicolon and the next malicious code will get  executed. This separater depends on the DBMS you are using. — tells the DBMS to ignore rest of the stuff in this case  single quote.

Having said all the above, some steps need to be followed so that this might not occur with your code. First of all  constraint user input. User server side validation using regular expression. For instance for above example, we may contrain  the input to only alpha-numeric values. If input is coming from another source, use RegEx class to contrain your input  programatically.

Secondly, use parameter collection with stored procedures. Only using stored procedures without parameter servers no purpose. It helps enforcing type checking and length  validations as well. Parameter collection does not make your literal sql string an executable code rather it just serves as  a literal. Another benefit is that parameter collection may be used in sql queries and stored procedures both. Now something about using parameters. If you use your parameter like this:

 exec sp_yourstoredproc @var

 Everything passed in is executed, then passing something like ‘drop database orders’ will drop this table as soon as this command is executed. Hence, use your parameters intelligently. Moreover, use escape sequence to validate input and use least priviliged account so that even with sql injection, database/table(s) cannot be dropped. Error information should be shown like no technical information is disclosed to the user that might be used by hacker.

Cross Site Scripting

Cross-site scripting attacks exploit vulnerabilities in web page validation by injecting client-side script code. One of the commonly used type is of a cross-site scripting attack when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a web address known to the attacker. This enables the attacker to spoof the legitimate user’s identity and gain illicit access to the web site.

Two possible solutions are contraining input and encoding output. RegularExpressions are used to contrain input as discussed earlier as well. For encoding output HttpUtility.HtmlEncode can be used. It replaces characters having special meaning in HTML. Like &lt; is replaced with ‘<’. When html is encoded, it cannot be executed rather it becomes harmless. Note the following in your application:

Verify <pages buffer=”true” validateRequest=”true” /> tag is there in machine.config, it enables validation in your aspx page.

Wherver html output is shown, make sure response is encoded so that it does not make your html vulnerable.

Some tags are malicious like <applet>, <body>, <embed>, <frame>, <script>, <frameset>, <html>, <iframe>, <img>, <style>, <layer>, <link>, <ilayer>, <meta> and <object>. For instance, <img> tag could be used like to execute vulnerable code like:

 <img src=”javascript:alert(‘hello’);”> 

.Net , , , , , , , , ,

How to Avoid Duplicate Rows In DataTable

April 10th, 2009

Problem

One of the common problems faced in the data retrieval is to avoid duplicate rows from dataset or datatable. If you google for it, you will come across many solutions asking to loop through the complete in order to get rid of the duplicates. There is a very simple solution available in .Net that does not need looping but it comes with one problem that it can apply duplicate on a single column only. 

Solution

For a dataset the following line will return distinct records for the column:

ds.Tables["MyTable"].DefaultView.ToTable(true,”column_name”);

For a datatable the following line of code will return distince records for the column:

dt.DefaultView.ToTable( true, “column_name”);

The first parameter of ToTable is a boolean for distinct or non-distinct. The second one is the name of the column. It is as simple as it looks :)

.Net , , , , , , ,

Dot Net: Error Creating Control

March 2nd, 2009

Sometimes during dot net development, you face this error while trying to open a web application project

Error Creating Control – control_Name

‘/LM/W3SVC/1/Root/Project_Name’ is not a valid IIS application. This error normally occurs if you have defined a sub folder as a virtual directory that is already within a virtual directory.

Solution

You can resolve this error by following the below steps , the root cause of this error is the incorrect mapping between web application project and the virtual directory in your IIS.

Follow these steps to resolve this issue:

1-Right click – you web application project and select Properties -> Web

2- In the server section choose Use IIS Web Server -> then click Create Virtual. If the URL is already provided but not correct one, modify it accordingly.

3- Clean your project and compile again.

You are done

.Net , , , , , , , , , ,

All About Threads in .Net

February 26th, 2009

Thread management has always been tricky especially from synchronization, locking and resource sharing perspective. At the same time avoiding dead locks is cumbersome. There are quite much features introduced in .Net that are available built-in to reduce effort required writing code from scratch. Not finding the material consolidated at one place, I decided to blog on them. I will be discussing those features one by one here:

Dot Net Thread Pool

Dot Net has provided a thread pool that can be used to execute our requests in multiple thread. It is quite a handy thread pool but it just provides basic functionality. What do I mean by that? I mean it just provides a queuing mechanism to queue up threads and executes these in a queue fashion. No other facility is provided like pause a thread, terminate a thread and most importantly prioritize a thread. Here is how you may use a Thread Pool:

thread pool

In the above code, you are telling the threadpool to execute DisplayMessage method in a new thread. You should use ThreadPool.SetMaxThreads() and ThreadPool.SetMinThreads() to set the minimum and maximum limits for the threads.

If you would like to use smart thread pool, look at Smart ThreadPool available at:

http://www.codeproject.com/KB/threads/smartthreadpool.aspx

Latest Smart Thread Pool can be downloaded from: (thanks Simon)

http://www.codeplex.com/smartthreadpool

Asynchronous Method Calling

Often, it is required to call a method asynchronously. In order to achieve that we need to define delegates. Find below a snippet:

Asynch Call

Monitors

Have you ever heard about monitors. No ? No problem. In multi-threaded applications, the biggest challenge is to avoid execution of multiple threads on the same resource. One thing that could be used for that purpose is Monitor. Look at the following code snippet:

Monitor

It’s been a nice synchronization technique available in .Net. Technically each object has a Monitor associated with it. We can also use Monitor without getting a lock on the shared resource.

NOTE: Just one suggestion, Monitor should be used almost always to make sure resource locking before performing operations on it.

Something About Mutex

We need to coordinate the activities of multiple threads (possibly across process boundaries) to
ensure the efficient use of shared resources or to ensure several threads are not updating the same
shared resource at the same time. Lets take a look at the following snippet using Mutex:

Mutex

Semaphores

There are some business scenarios in which we need to limit the number of threads that can share concurrently some resource. We can do so by using Semaphore class provided by Dot Net. Look at the following code snippet, how we may achieve this:

Semaphore

Confused About Monitor, Mutex and Semaphore:

Monitor should be used in most of the circumstances to make sure resource is locked. Mutex is used for Inter-Process communication. Semaphores are used if a resource lock can be shared by limited number of threads.

.Net , , , , , , ,

Messaging Queues

February 17th, 2009

Message queuing is used in scenarios where we need a failsafe mechanism while two processes communicate with each other. Microsoft has provided MSMQ for implementing message queues. MSMQ is essentially a messaging protocol that allows applications running on disparate servers to communicate in a failsafe manner. A queue is a temporary storage where one process can store messages and the other process can retrieve those. In this way, implementing a producer/consumer mechanism. This ensures that messages are not lost even if the systems are not connected for some time period.

There are different type of queues as mentioned in the table below:

Queue Type Description
Public queue Registered in directory services, can be located by any Message Queuing applications
Private queue Registered on local machine, typically cannot be located by other applications
System Queue These are system level queues.

Let’s look how you may create a queue.

  1. Open the computer management snap-in.
  2. Navigate to the [Message Queuing] node under the Services and Applications node.
  3. Right click on the [Private Queues] and in the context menu select New -> Private Queue.
  4. Name the queue msmq_web as shown in the figure below:

Once you have created this queue, it will be shown in the snap-in. Now we can write and read messages from this queue. Download the code at the end of this article, it consists of a web application. The web application contains two buttons. One is “Send Message”, as soon as you click on it a message is recorded in the msmq_web queue. You can configure your message in the web.config. When you click the second button “Consume Message”, one message is consumed from msmq_web queue and recorded in the database. You can find the code to record and retrieve messages from a queue. The application is shown in the figure below:

Download code here:

.Net , , , , , ,

Windows Service Installer

January 28th, 2009

I happen to create a windows service and its installer in VS 2005 using .Net. The service is pretty simple to implement and the installer as well. The thing that matters is that if we just add the service to the installer and installs it, the service will be installed on the machine but it would not be registered with SCM. In order to auto-register it with SCM what we need is to include two custom actions for Install and UnInstall.

The above is depicted in the following figures:

Installation custom action

Go to custom action, add a custom action for Install and select service primary output with the argument “/install” as shown in the figure below:

UnInstallation custom action

Go to custom action, add a custom action for UnInstall and select service primary output with the argument “/uninstall” as shown in the figure below:

Now when you will un-install, the service will be un-registered as well. A word of caution is that “before un-installing, stop your service. Otherwise it remains in your service manager and vanished once you restart or log-off from your machine”.

.Net , , , ,

Bulk Inert In Sql Server 2005 Using Dot Net 2

January 21st, 2009

Data bulk insertion is a requirement often faced by developers. Using dot net 2 and sql server 2005, Microsoft has provided a nice feature for bulk insertion using SqlBulkCopy class. It is really fast and indeed no comparison of performing instead in transaction or row by row. Coupling SqlBulkCopy with Transaction is very nice. Here how it works:

using (SqlConnection lConnection = new SqlConnection(“connection_string goes here”))
         {
            connection.Open();
            SqlTransaction lTransaction
=lConnection.BeginTransaction();           

 try
            {
              
// BulkUpload actually starts here
               using (SqlBulkCopy lCopy = new SqlBulkCopy(lConnection,
                  SqlBulkCopyOptions.Default, lTransaction))
               {
                  lCopy.DestinationTableName = targetTable; // the table to which data is to be written
                 lCopy.ColumnMappings.Add(New SqlBulkCopyColumnMapping(SourceColumnName, DestinationColumnName));
                 lCopy.BatchSize= BATCH_SIZE; // records to be written in one batch
                 lCopy.NotifyAfter = 200; // in number of records
                 lCopy.WriteToServer(SourceTable);
                 lTransaction.commit();
catch
            {
               lTransaction.Rollback();
              
throw;
            }

 

The above code writes a source data table to destination database table on the basis of connection string and table name. We can set the batch sieze, we may also write an event so that after each batch we are notified of the success. Its easy and certainly very fast.

 
 

.Net , , , ,

Visual Studio 2010

January 15th, 2009

Microsoft’s new version of Visual Studio i.e., 2010 is coming up with new wave of enhancements and  features. Its major focus will be to ease developers, designers and architects by including advanced  modeling features built in Studio 2010. Along with the studio, enhanced Visual Studio Team System will also be accompanied.

Having said that let’s look at what these feature are:

Modeling Facilities

Microsoft has decided to go extra miles by providing the facility of modeling to developers as well as  business users. UML is also supported. These graphical facilities will ease users and developers to use right tools at the right time.

VSTS improvements

In order to improve the productivity and efficiency, new VSTS include features to remove non-reproducible bugs, and quick deployment for highest degree of completenes. It will also provide progress trakcing and ensure all code paths are properly tested.

Life cycle management

Major focus is on managing life cycle effectively so that less time is being consumed on managing life cycle and the collaboration is easy to maintain. Teams can track work items easily and hierarchical work item relationships are supported as well. Using TFS one can track changes across branches.

Above features are just a glimpse of what will be included in VSTS 2010. There is no shipping date as such available but we can hope to get a stable version before the time as its name implies :)

Visual Studio , , , ,


Copyright © 2006-2011 W@rfi