Tuesday, September 4, 2012

Case Sensitive SQL Query Search

Have you ever noticed when you do a string comparison in SQL using '=' notation, case of the string is neglected ???
For example, If TestTable has a TestColumn and it consist of  values ‘CaseSearch, casesearch, CASESEARCH, CaSeSeArCh’, following statement will return you all the four records.

SELECT Column1
FROM Table1
WHERE Column1 = 'casesearch'

If you dont want to ignore case and return only the exact row with the specified value, the query should be modified as follows,

SELECT Column1
FROM Table1
WHERE Column1 COLLATE Latin1_General_CS_AS = 'casesearch'

The above change should be done since the default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS is not case sensitive.

Monday, August 6, 2012

Background Worker - Complete Explanation

As requested by a commenter/follower of the blog, I created an example which explains all most all the processes related to the Background worker in .Net. The processes from A - Z is explained as follows,
  • Add a Background worker to the project
To add a background worker to the form you need, drag & drop the component from the Toolbox under the Components section.
  • Allow to Report Current progress or Cancel the background operation
Set the WorkerReportsProgress and WorkerSupportsCancellation properties to "True" in-order to allow the Background worker to allow Report current progress or Cancel the current operation.


Friday, July 27, 2012

Use of Background Worker, Error Provider

Have you ever experienced "Not Responding" message in your software applications, when you start some process ??? What do you think the reason for it ??? It's simply because the .NET Framework, all interaction with the user interface (UI) must be performed on a single thread, often referred to as the UI thread. The UI thread is the only thread that can update the UI or respond to events that the UI raises. So when a busy process is running the UI keeps freezing until the current process completes. The best solution to avoid this situation is to use a Background Worker.

The BackgroundWorker class enables you to run code on another thread. The BackgroundWorker class includes events that indicate the progress of the thread. A UI can subscribe to these events and update the screen by using the UI thread. This enables you to build a UI that remains responsive and up to date.
Download the sample from the  following link and you'll be able to get some knowledge on,
  • Simple usage of Background Worker
  • Usage of Error Provider in .Net framework
  • Simple Linq to Sql
  • Some coding standards 
Development Environment : MS Visual studio 2010, Sql Server 2005 or above

NOTE :  Before running the sample application modify the "app.config" file in the "StudentManagementSystem.Service" project with the connection string of your database.


Monday, July 23, 2012

Abstract - Key things about Abstract Classes/Methods

Abstract Classes
  • An Abstract class cannot be instantiated.
abstract class SampleAbs
{
...
}
SampleAbs instance = new SampleAbs(); // Compile Error
  • It cannot be modified with the 'sealed' modifier. In other words, an Abstract Class should be inherited.
  • An Abstract class may contain abstract as well as non abstract members.

Abstract Methods
  • An Abstract method cannot contain a method body.
abstract class AbsClass
{
abstract void AbsMethod(); // Legal

abstract void AbsMethod()
{
... // Illegal
}
}
  • An abstract method is implicitly a virtual method.
  • An Abstract method can only be added in an Abstract Class.

Thursday, July 12, 2012

Static - Key things about using 'static'

In this post I'll pin point you the important facts that you should be aware of when using static methods, variable & classes etc.
  • If a there is a static field declared in a non static context (class) it can be accessed without creating an object (object of the class).
    class Sales
    {
       public static double salesTaxPercentage = 20;
    }
    Sales.salesTaxPercentage  = 35; // can access like this

Monday, July 9, 2012

' ref ' keyword - Passing value types by reference

The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method.  In other words if you do a certain changed to the parameter in the method it'l affect the originally passed arguement as well. To use a ref parameter, the argument must explicitly be passed to the method as a ref argument. 
The following example will explain the above mentioned facts.

 private static void TestMethod(ref int a)
{
    // at this point the original value will be modified 
    a = a * a;
}
static void Main(string[] args)
{
    int a = 10; // First 'a ' is initialized to 10
    TestMethod (ref a); // Invoking and passing ref arguement
    Console.WriteLine(a);
    Console.ReadLine();
    // Output a = 100;
    // If it was not passed by reference the output would be 10      
}

Thursday, July 5, 2012

Data Validation in WPF

When it comes to Data Validation most of us use the old mechanism of inspecting the key press. What can can you do If you want the user to enter only values in a specified range for a text box ??? One of the old mechanisms are to check the entered value at a button click event to save the record. Thanks to WPF Validation rules, we can make the work more easier and create cleaner code. The steps of implementing Validation rules will be further explained using an example where you need to validate a Person's age as for the following conditions,

- Age > Min age
- Age < Max age
- Age should only be numeric.

Follow the below steps to implement.

1) Create a WPF project and Add a class (I've used 'AgeRangeValidation' as the name).
2) Bring System.Windows.Controls namespace into scope.
3) Inherit from the ValidationRule class and implement the abstract method Validate
4) Add Automatic properties to set the Min and Max ages.
5) Add code as follows to validate for non numeric characters and age against the specified range.

Monday, July 2, 2012

Image Processing - Template Matching

The following code segment can be used to perform a simple template matching which maps pixel by pixel between two images, gets a count of the errors/mismatching pixels and through the calculation of a error rate it determines weather the two images are same or not. Error rate is calculated by dividing the total errors by the total number of pixels inspected. In this example I've used 30 as the margin between matching and mismatching.



You can download a sample from the following link :
Template Matching Sample

Sunday, July 1, 2012

Enumerations - New Enum Types


Under this blog post we'll be discussing on " What are Enumerations ?" & creating and using new Enum types.
  •  What are Enumerations ???
An Enumeration type is a set of related named constants. An Enumeration type is a scalar type that has a user defined range of values. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. The following examples will further explain these to you.
  • Initializing & Using Enums
enum Days
{ Monday, Tuesday = 1, Wednesday, Thursday, Friday,
Saturday, Sunday /* In this case, the enumeration literals Wednesday,
Thursday,Friday,Saturday and Sunday will automatically 
have the values 2, 3,4,5 and 6. */ }; static void Main(string[] args) {
// loops through the days of the week for (Days dayOfWeek = Days.Monday; dayOfWeek <= Days.Sunday;
dayOfWeek++) { Console.WriteLine(dayOfWeek); } Console.ReadLine(); //Output is: //Monday //Tuesday //Wednesday … }

Thursday, June 28, 2012

Output Parameters

Is it possible to have multiple return statements within a function ??? Obviously the answer would be NO !!!. What if you need to get multiple values returned ??? Output Parameters would be the solution.
Using Output Parameters additional data can be returned from a method. The following example demonstrate the use of Output Parameters.


Note: When an Output Parameter is declared in a method, it should be assigned value before leaving the method scope.

Named Arguments

When invoking a method can you even think of messing up the order of the parameters  ??? YES, you can. ;) Thanks to Named Arguments in C#.
Using these you can specify parameters by a name and supply arguments in an order that differs from order of the parameters in the method signature. The following example helps you to understand this more.

// Method declaration
void NameArgs(int _first,int _second,int _thrid) 
{
...
}
// Method invocation
NameArgs(_third:10,_second:5,_first:3);

Optional Parameters

When invoking a function, can you not pass in values as mentioned in the method signature and pass in only the values you need ???
Sorry !!! you cannot do that. But what if you need to do so ??? Optional Parameters is the answer. Optional Parameters allows you to define a method and provide default values for parameters in the parameter list.
Note : All the declared optional parameters should be at the end of the parameter list. In other words it should be declared after the normal parameters.
// Method declaration
int OptionalTest (int a, int b, int c = 10)
{
...
}
// Method invocation
int _val = OptionalTest(10, 5); // ' c ' would be 10
int _val = OptionalTest(10, 5, 25); // ' c ' would be 25

Jagged Arrays

Jagged array is an array of arrays. When declaring and initializing a jagged array, the size of the first array should be specified. But must not specify the sizes of the other arrays that are contained in this array.
string [][] _str = new string [10][];
_str[0] = new string [5];
_str[1] = new string [4];

String Immutability - String Builder

First of all Immutable means - Once created cannot be changed and Mutable means liable to change. Strings are immutable. The best example to demonstrate this would be a string concatenation example. When concatenating a string, a new string object is created and the variable references to the newly created object and the previously created object will be sent for garbage collection. This scenario would be explained further using the following code snippets.


To avoid this situation of StringBuilder class can be used as follows,