Archive

Archive for the ‘Dot Net’ Category

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’);”> 

admin Dot 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 :)

admin Dot 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

admin Dot 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.

admin Dot 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:

admin Dot 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”.

admin Dot 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.

 
 

admin Dot Net , , , ,

Common Coding Mistakes

November 8th, 2008

While doing code reviews, you must have found common issues in the code. I am gonna list down some common problems in the developer’s code written in .Net. I have experienced these issues quite recently, so thought to jolt upon these. These could also help building up code review guidelines as well. This post has grown quite long, my apologies for that :) but certainly this subject can be extended to as much as possible and its quite little as far as this subject is concerned.

Unused Code

As we progress in our development, we face more un-used code. That un-used code not only produces huge size as well as make the code less readable. It produces burden on the compiler as well. .Net assemblies are dynamic, there is no way that compiler could get rid of the code automatically. We will need to use some third party tools for that. Either you may use http://www.preemptive.com/dotfuscator.html OR www.xenocode.com.

Throwing Exceptions

Exceptions are either not caught properly or used but improperly.

  • First let me tell you what do I mean by saying that exceptions are not caught properly. You will experience no try/catch OR empty catch block OR Exception class being caught OR the exception not logged at any place. If we do not log exception at any place, we will never be able to trace what went wrong in the production environment. Secondly, make it sure that you should have alternate mechanism for logging exception. For instance, you were logging in event viewer and it becomes full. Now when you will log another, you will experience an exception in your Logger class which is logging so you should have try/catch block even in your logger. At many times, developers argue a lot how come Logger class may also get crashed. The answer is yes, logger class can also get crashed so look for alternate mechanisms as well. Otherwise, be ready to play a blind game with production issues :)
  • When I say exceptions used improperly, I mean to use “throw” instead of “throw ex” (where ex is the object containing exception). You should ask what is the difference between them ? So here we go. The difference is that “throw” preserves the original stack trace whereas “throw ex” truncates the stack trace below the method in which the “throw ex” call is located. It means if exception has occurred in a method being called, using “throw ex” we will never know where actually exception has been generated.

Multi-dimensional vs Jagged Arrays

A jagged array is a type of array whose elements are arrays as well. Benefit is that, each array within jagged array can be of different sizes, leading to less wasted space for some sets of data. Example is as follows:

Private jaggedArray As Integer()() =      {New Integer() {1, 2, 3, 4}, _
                                           New Integer() {5, 6, 7}, _
                                           New Integer() {8}, _
                                           New Integer() {9}}

Private multiDimentionalArray As Integer(,) =  {{1, 2, 3, 4}, _
                                               {5, 6, 7, 0}, _
                                               {8, 0, 0, 0}, _
                                               {9, 0, 0, 0}}l

So as you see in case of multi-dimensional array, we need to initialize the same set of values. So preferable use jagged arrays.

Commented Code

Test code is commented out during development and never removed. Make sure to remove such code to improve readability and formatting of your code. Otherwise, it will cause problems during maintenance.

Overridden Methods Instead Of Default Parameter Values

Microsoft says that methods that use default parameters are allowed under the Common Language Specification (CLS); however, the CLS allows compilers to ignore the values assigned to these parameters. Code written for compilers that ignore default parameter values must explicitly provide arguments for each default parameter. To maintain the behavior that you want across programming languages, methods that use default parameters should be replaced with method overloads that provide the default parameters. The compiler ignores the values of default parameters for C#. (Ref: http://msdn.microsoft.com/en-us/ms182135.aspx)

Use Static Methods Wherever Applicable

All the methods which do not access any instance variables should be marked as static or shared. It will improve performance.

Objects Instantiation

Objects are instantiated in loops which runs several times, thus creating more and more memory. Avoid creating new object on each loop iterations OR nullify the previous one so that on next iteration same instance is being used. Be careful in case of string += operation which will always create two string instances in memory. Instead use StringBuilder.

Int16 OR Int32

At many times, developers will prefer using Int16 over Int32 if they are executing a loop that involves counter less than 32,000 or something similar. But on the contrary, MS says something else. Runtime optimizes performance of Int32 and recommends it for counters and other frequently accessed operations. (Ref MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0—Application Development Foundation). Int16 is good if you want your data structure to be as lean as possible. Otherwise, prefer using Integer. Similarly for floating points, Double is the most efficient data type to be used.

Returning Method

Make sure function returns from each code path. All code paths should return something or the other. Otherwise, you may face problems during different scenarios. It will be possible if each method is simple, as we move towards more complex methods it will be difficult to monitor each code path returns something.

Comments Phobia

Usually developers are faced with a phobia not to write down comments. With Visual Studio 2005 and onwards it has become very easy to write down comments before namespace, class, method etc. Use shortcut of ”’ and block of comments will be available. You may just fill in the spaces to complete your comments block which will be very beneficial for others. Moreover, it could be sued to generate documentation later on.

Dispose or Not to Dispose

There had been a lot of debates lately between me and a lot of developers. That gives me inspiration to further look down at this issue. I have came across certain findings as well in that regard as well.  Certainly GC collects all managed objects. First lets look at the difference between Dispose and Finalize:

Dispose is the normal method by which unmanaged resources are freed up. It is called in the normal way from user code, often via a Close method.

Finalize is a safeguard to clean up resources in the event that the Dispose method is not called ( a programming error ).

GC calls finalize method but do not call Dispose() method. Dispose method is available with only objects that EITHER has some unmanaged resources associated with it OR for objects that encourages its child classes to implement it.

Having said that, it is apparent that if an object has a Dispose() method, it means it is recommended to call it. If you are too much curious why you should do it, use Reflector to look at the code of the assembly that what its Dispose is doing. I would always recommend using Dipose().

In the following are some links that you may visit to read more about discussion about it:

http://forums.asp.net/p/466400/593963.aspx
http://bytes.com/forum/thread279478.html

admin Dot Net , , , ,

Test Driven Development (TDD)

October 18th, 2008
Having heard a lot about TDD and all the benefits we could achieve using it, I got the chance to compare different methodologies and their pros/cons. Let’s start by looking at some of our practices:

  • We start our implementation by writing some code.
  • Code is being saved in some repository like CVS, VSS etc.
  • Checking code at regular intervals.
  • Doing unit testing using some methodology
  • Build preparation on daily/weekly depending upon our criteria
  • Acceptance testing

The above process keeps on moving until we have our final release or the project we are working on is finished. Broadly speaking there is two types of tests:

  • Tests focused on technical aspects
  • Tests focused on business

Using TDD, we will be only testing technical aspects. For business functionality QA personnel should take care of all the scenarios. In the following diagram, you can find a little about what the whole process all about:

TDD image

In principle TDD says “write test before you program” but it has a little more insight like:
•    It pressurizes the developer to think about the module he is to program even before he writes it.
•    Indirectly, it introduces a level of design before we even write something, which is of course very good.
•    Using automated testing, we are awared at all the times where does our code stand at any the times.

Red / Green Refactor

  • Red factor says, write a test that fails.
  • Green says write code to make the test pass.
  • Refactor says improve the design so that code works as well as test passes.

Frameworks available for unit tests automation are Junit, Nunit, Microsoft Test Environment. For .Net environment NUnit and Microsoft Test System both could be used. We need to look at the pros and cons of both which will be presented in the sections below.

Tips for writing unit test

  • Tests we write should just test the functionality, we should not start programming in our tests making them more complex and useless as well.
  • All tests should be independent in themselves.
  • Prepare and destroy test data on start and end of the test

Comparison of NUnit and Microsoft Team System
In the following a comparison has been presented between NUnit and MS Team System.

NUnit

Team System Unit Test

Its the de-facto standard for unit tests in .NET but not available out of the box

Out-of-the-box integration with Team Foundation Server.

Already exists for several years now and it’s very stable

Less users

New releases and new features on a regular basis

Its not free and only available for the Team System editions of Visual Studio. There’s also no stand-alone test runner available. When our project lead or our functional analysts like to run some integration tests, they have to install one of the Team System editions of Visual Studio in order to do so.

It has a rich set of  assertions and extending assertions is possible.

It’s evolving its set of assertions and has associated issues as well.

Very good integration with all editions of Visual Studio

Test runs are very slow. One of the most important characteristics of a good unit test is that it’s fast.

It’s open-source

Less features than other unit test frameworks like NUnit. Less assertions, no inheritance of test fixtures to name a few.

It’s available for both .NET 1.1, .NET 2.0 or higher

Only available for .NET 2.0 or higher.

admin Dot Net , , , , ,

Edit Configuration Disabled

September 30th, 2008

Problem

You might face a problem that “Edit Configuration” button is shown disabled in IIS. It is being shown in the figure below:

IIS Edit Configuration

Due to this, you will not be able to edit any of the configurations related to your website.

Solution

The actual reason for this is that dot net is not being configured with IIS. One reason might be that you have installed dot net first and then IIS. That’s why IIS could not be configured properly.

You will need to go to Start -> Microsoft Visual Studio 2005 -> Visual Studio Tools -> Visual Studio 2005 Command Prompt. On the prompt write down this command:


aspnet_regiis -r

The above command will register dot net with IIS and now the button will also be enabled.

admin Dot Net , , , , ,


Copyright © 2008-2009 W@rfi