Welcome to my blog.

Post on this blog are my experience which I like to share. This blog is completely about sharing my experience and solving others query. So my humble request would be share you queries to me, who knows... maybe I can come up with a solution...
It is good know :-)

Use my contact details below to get directly in touch with me.
Gmail: nadarmuthukumar1987@gmail.com
Yahoo: nadarmuthukumar@yahoo.co.in

Apart from above people can share their queries on programming related stuff also. As me myself a programmer ;-)

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive.

This basically happens when your website is targeting ASP.NET 4.0 and the application pool is set to run ASP.NET 2.0.

Solution
To do this follow the steps below:
Log-in into your hosting control panel.
Select “Websites” from Hosting Space Menu on the left side.



Click on your website to see website properties.
Select “Extensions” tab. Here you will set ASP.NET version to your desired one. I selected ASP.NET 4.0 in my case and everything is going fine now.


If the above solution fails, simply remove “targetFramework” and everything will go fine after your set website’s properties from Extension tab.

This is cheating :(

Chennai to Bangalore = 350 km
.
.
.
.
.
.
Bangalore to Chennai = 350 km


Ground Floor to 15thFloor = 15 floors
.
.
.
.
.
.
15th Floor to Ground Floor = 15 floors


Monday to Friday = 5 days
.
.
.
.
.
.
.
Friday to Monday = 2 days

This is cheating!!!

Dangerous Shampoo Brands

Dangerous Shampoo!!!
Banned By Dubai Government!!









Sodium Laureth Sulfate (SLS)

CLEAR, FRUCTIS, Vo5, Palmolive, Paul Mitchell, L'Oreal, Body Shop

All these Shampoos use a chemical called SLS which is actually a floor cleaner. They are used so as to produce more foam

Imagine what a floor cleaner can do to you hair and scalp. It will damage the very roots of your scalp.

Check out for SLS in toothpaste too!!!

Use the ones which are free from this extremely harmful chemical.

Type in 'SLS Free Shampoo' or 'SLS Free Toothpaste' in Google.Com  to get a list of companies selling safe products

"Attention please.....Please forward to all.. This may be helpful for someone.........


Reference : (nadarmuthukumar.blogspot.com)

telnet is not recognized as an internal or external command operable program or batch file

Solution
Go to "Control Panel > Programs and Features" and then you will find something like "Turn Windows features" or "Advanced" ....You should find the option "telnet client" and select the option and click OK.

String was not recognized as a valid DateTime

I got this error when I was trying to convert date string with format dd/MM/yyyy.
Solution:
First Import below Namespace
using System.Globalization;
Replace STRDATE with your date. And use any of the below code for conversion.
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
OR
DateTime date = DateTime.ParseExact(STRDATE, "dd/MM/yyyy", CultureInfo.InvariantCulture);
OR
DateTime date = DateTime.ParseExact(STRDATE, "dd/MM/yyyy", null);

Get Last Executed Query on SQL Server 2005

SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in) , SQL SERVER – 2005 – Last Ran Query – Recently Ran Query

Cannot start Microsoft Office Outlook. Cannot open the Outlook window.

When you start Outlook 2007, you receive the following error:
Cannot start Microsoft Office Outlook. Cannot open the Outlook window.

This problem can occur when file that maintains the Navigation Pane settings becomes corrupted. This file is called profilename.xml, where profilename is the name of your Outlook profile. This file is stored in the following folder:

Windows XP

C:\Documents and Settings\username\Application Data\Microsoft\Outlook
Windows Vista, Windows 7

C:\Users\username\AppData\Roaming\Microsoft\Outlook

A good indication this file is corrupted is when the file size is 0 KB.

To resolve this problem, use the following steps.

On the Start menu click Run.
In the Run dialog box, type the following command:

Outlook.exe /resetnavpane

Note: There is a space between "Outlook.exe" and "/resetnavpane"
Click OK.

Note If you are using Windows Vista or Windows 7, you may not see Run on the Start menu. In this situation, use the following steps to locate the Run option.

On the Start menu click All Programs.
Click Accessories.
Click Run.

Split Function

Sql Server does not have in-build Split function.
To achive the same I have created below function.
/****** Object:  UserDefinedFunction [dbo].[fn_Split] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[fn_Split]
(
     @InputStr VARCHAR(MAX) -- List of delimited items
    ,@SplitChar CHAR -- delimiter that separates items 
)
RETURNS @Splittings TABLE
(
     Position INT
    ,Val VARCHAR(20)
)
AS
BEGIN

    DECLARE @Index INT, @LastIndex INT, @SNo INT
    
    SET @LastIndex = 0
    SET @Index = CHARINDEX(@SplitChar, @InputStr)
    SET @SNo = 0
    
    WHILE @Index > 0
    BEGIN  
  SET @SNo = @SNo + 1
        INSERT INTO @Splittings(Position, Val)
        VALUES(@SNo, LTRIM(RTRIM(SUBSTRING(@InputStr, @LastIndex, @Index - @LastIndex)))) 
 
        SET @LastIndex = @Index +1
        SET @Index = CHARINDEX(@SplitChar, @InputStr, @LastIndex)
    END
    SET @SNo = @SNo + 1
    INSERT INTO @Splittings(Position, Val)
    VALUES(@SNo, LTRIM(RTRIM(SUBSTRING(@InputStr, @LastIndex, LEN(@InputStr) - @LastIndex + 1))))
    
    RETURN
END
To Call the Function you can use below query
SELECT * FROM dbo.fn_Split('Chennai,Bangalore,Mumbai',',')  

Difference Between Stored Procedure and Function

Fundamental difference between Stored procedure vs User Functions:
  1. Procedure may return none or more values.Function must always return one value, either a scalar value or a table.
  2. Procedure have input,output parameters.Functions have only input parameters.
  3. procedures are called independently whereas Functions are called from within SQL statement.
  4. Functions can be called from procedure.Procedures cannot be called from function.
  5. Exception can be handled in Procedure by try-catch block but try-catch block cannot be used in a function.(error-handling)
  6. Transaction management possible in procedure but not in function.
  7. Procedure are compiled for first time and compiled format is saved and executes compiled code when ever it is called. But function is compiled and executed every time it is called.
  8. Procedures can affect the state of the database by using insert,delete,update and create operations.Functions cannot affect the state of the database which means we cannot perform insert,delete,update and create operations on the database.
  9. Procedures can change server environment whereas Function can not change server environment.
  10. Cannot JOIN a Procedure in a SELECT statement.Can JOIN a Table values UDF in a SELECT statement.

Statement of boys with no girlfriends in college

Statement of boys, when they remain unsuccessful in making girlfriends in College... 
1st sem: Meri to pehle se hai... 
2nd sem: Chalo try karenge 
3rd sem: Apne batch me koi dhang ki nahi hai 
4th sem: Juniors bhi dhang ki nahi hai 
5th sem: Bhai kisise intro. to kara... 
6th sem: Koi bhi chalegi... 
7th sem: Mere paas time nahi tha varna... 
And Finally With Full Attitude  
8th sem: Dekha puri degree ho gayi paraaj tak kisiko bhaav nahi diya...

Google is a girl or a boy?

Teacher: Google is a girl or a boy...?
Student: Google is a Girl..... because it won't let you complete the whole sentence and start guessing, suggesting... and you ask only one question... but get hundreds of irrelevant answers in seconds...

First Fight of Young Couple

A Young Couple Were Having Their First Fight And this Was A Big One After A While, 
The Husband Said: "When We Got Married, You Promised To Love, Honor and Obey" 
His Bride Replied: "I Know But I Didn't Want To Start An Argument In Front Of All Those People at the Wedding"

Enum With Custom Values In C#

Designer

Code Behind
using System.ComponentModel;
using System.Reflection;

public enum Test
{
    [DescriptionAttribute("Alphabet")]
     ABCD
};

public static string stringValueOf(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());
    DescriptionAttribute[] attributes = (DescriptionAttribute[])     
    fi.GetCustomAttributes(typeof(DescriptionAttribute), false); 
    if (attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return value.ToString();
    }
}

protected void btnShow_Click(object sender, EventArgs e)
{
    Response.Write(stringValueOf(Test.ABCD));
}

Ref1, Ref2

Validate RadioButton in GridView, DataGrid, DataList

JavaScript inside Script Tag on your page.
    function ValidateSelection()
    {
        var grid = document.getElementById("");
        var Selected = 0;
        for (i = 1; i < grid.rows.length; i++)
        {
            if(grid.rows[i].getElementsByTagName("input")[0] != null
                && grid.rows[i].getElementsByTagName("input")[0].type == "radio" 
                && grid.rows[i].getElementsByTagName("input")[0].checked)
                {
                    Selected = 1;
                    break;
                }
        }
        if(Selected==0)
        { alert('Please select any row to proceed.'); return false; }
        else
        { return true; }
    }
Designer

Single Selection RadioButton on GridView

Designer

      
           
                 
                      
                 
           
           
                 
                       
                 
           
      



Code Behind
protected void btnApply_Click(object sender, EventArgs e)
    {
        int RowIndex = Convert.ToInt32(Request.Form["rdoRowIndex"]);
        if (RowIndex > -1)
        {
            GridViewRow _gvRow = gvDetails.Rows[RowIndex];
            Label _objSchemeName = (Label)_gvRow.FindControl("lblSchemeName");
            Response.Write(_objSchemeName.Text);
        }
    }
To Validate RadioButton is checked or not, click here

Convert Table Column to Property

Instead of creating each and every property, below query will help you created property on single fire.
Just replace "TABLENAME" with you table name.
DECLARE @COLUMN_NAME varchar(250)
DECLARE @DATA_TYPE varchar(250)
DECLARE c1 CURSOR FOR

SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.columns
where table_name = 'TABLENAME'
OPEN c1
FETCH NEXT FROM c1 INTO @COLUMN_NAME, @DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN

IF @DATA_TYPE = 'nvarchar' OR @DATA_TYPE = 'ntext' OR @DATA_TYPE = 'varchar'
BEGIN
    SET @DATA_TYPE = 'string'
END

IF @DATA_TYPE = 'datetime'
BEGIN
    SET @DATA_TYPE = 'DateTime'
END

DECLARE @pvar  VARCHAR(100)
SET @pvar = ' _' + @COLUMN_NAME
PRINT 'private ' + @DATA_TYPE + @pvar + ' ;'
PRINT 'public ' + @DATA_TYPE + ' ' + @COLUMN_NAME + ' {get{return '+ @pvar +';} set{'+ @pvar+'=value;} }'

FETCH NEXT FROM c1 INTO @COLUMN_NAME, @DATA_TYPE

END
CLOSE c1
DEALLOCATE c1
GO
In the query above I have only added few data type. People can add more data type as per their need.

Angry Wife To Husband...

An Angry Wife To Her Husband 0n Phone: "Where the Hell Are You ... ?" 
Husband: Darling You Remember That Jewelery Shop Where You Saw The Diamond Necklace and Totally Fell In Love With It and I Didn't Have Money That Time n I said "Baby It'll Be Yours 1 Day ..." 
O:) Wife, With A Smile & Blushing: Yeah I Remember That My Love ! 
Husband: I m In The Pub Just Next To That Shop :D

System.OutOfMemoryException

When I was trying to fetch about 145000 records, I was getting error as below

Exception of type 'System.OutOfMemoryException' was thrown.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

Solution
1. Use Paging to your gridview.

Request.QueryString Replace + with Empty Char

If I pass a string that contains + in a query string and try to read it, i will get the same string by replacing + with empty char.

For example if i pass query string like
Page.aspx?data=abc+1002
while reading Request.QueryString["data"] it gives me below value data ="abc 1002".

Reason behind this is + is the url encoded representation of space " "

In order to overcome this problem you will need to encode your url as below
Page.aspx?data=" + HttpUtility.UrlEncode("abc+1002")

which will produce:
Page.aspx?data=abc%2b1002
To get your original data back you need to decode the same as below
HttpUtility.UrlDecode("abc%2b1002")
which will give you abc+1002.
 

Get System IP Address

string sIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(sIPAddress))
    sIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return sIPAddress;

Girl getting caught by brother

UNKNOWN CALL
HE-------Do you have Bf?
SHE-----Yes ! Who are you?
HE ----- Main bol raha hoon tera BHAI..ruk ghar aata hoon fir bata hoon tujhe (angry)

ANOTHER UNKNOWN CALL
HE ------Do you have Bf ?
SHE --------oh no no! Who are you?
HE ------ I am your BF (angry) Cheat u broke my heart...
SHE -------Oh Sorry Darling !!! I thought you are my brother...
HE---- Main tera BHAI hi bol raha hoon kamini Ruk aaj tu...

Different types of Girlfriends

Different types of Girlfriend fighting with their boyfriend... 
Pilot's Girlfriend: Zyada ud Matt Samjha 
Teacher's Girlfriend: Mujhe mat Sikhao Samjhe 
Dentist's Girlfriend: Daant tod ke hath me de dungi 
C.A.'s Girlfriend: Hisaab se reh samjha... 
Engineer's Girlfriend: "Abey pehle Pass toh ho ja fir baat karna" :D :-P

Guy wanting to hold girls hand

Boy: Can I Hold Your Hand? 
Girl: No. 
Boy: Why? 
Girl: Because It Hurts When You Leave It !!! 
Boy (in his mind): Baap re.. I am acting but she is overacting !!

Bad Luck

Girl: hi baby! :) 
Boy: hi my lovely.. (sending failed
Girl: are you there?? 
Boy: yes ! yes i am here! (sending failed
Girl: are you ignoring me or what ??? 
Boy: honey i am not.... i am here.. (sending failed
Girl: ok! it's over; don't you ever talk to me again! 
Boy: DAMN! go to hell ! . . (message sent) :P

Distinct not working in Sql Server

Once I was trying to get distinct record from database, i found that my query was not working as of my expectation.
My table was like below
ProductId   ProductName   CreatedDate
----------   --------------   --------------
A001        Sample Data      2012-03-25 23:31:26.580
A001        Sample Data      2012-04-01 14:11:09.483
A002        Sample Data      2012-04-14 15:51:30.640

And the query which I wrote to fetch distinct record was as below
SELECT DISTINCT ProductId, ProductName, CreatedDate FROM tbl_Product
Reason behind the improper output was "DISTINCT removes redundant duplicate rows", to know more about DISTINCT click here
If you see my table you can find difference on CreatedDate of A001 record. Which means that row is not the duplicate.
In order to achieve proper output in such a case, use any of the below queries
SELECT P.ProductId, P.ProductName, MAX(P.CreatedDate) AS CreatedDate
FROM tbl_Product P
GROUP BY P.ProductId
OR
SELECT P1.ProductId, P1.ProductName, P1.CreatedDate
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY P.ProductId ORDER BY P.ProductId) AS RowNo,
P.ProductId, P.ProductName, P.CreatedDate
    FROM tbl_Product P
) P1
WHERE P1.RowNo = 1 

Difference between class and structure

  1. The structures are value types and the classes are reference types.
    Example:
    namespace DifferenceBetweenClassesAndStructures
    {
    
        struct StrucutreExample
        {
            public int x;        
        }
    
        class ClassExample
        {
            public int x;        
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                StrucutreExample st1 = new StrucutreExample(); // Not necessary, could have done StructureExample1 st1;
                StrucutreExample st2;
    
                ClassExample cl1 = new ClassExample();
                ClassExample cl2;                        
    
                cl1.x = 100;
                st1.x = 100;
    
                cl2 = cl1;
                st2 = st1;
    
                cl2.x = 50;
                st2.x = 50;
    
                Console.WriteLine("st1 - {0}, st2 - {1}", st1.x, st2.x);            
                Console.WriteLine("cl1 - {0}, cl2 - {1}", cl1.x, cl2.x);            
                Console.ReadLine();
            }
        }
    }
    
    Out put will be as below:
    st1 - 100, st2 - 50 cl1 - 50, cl2 - 50
  2. Object of structure store in stack exactly like any other value type like an Integer, a double but object of class store in heap.
  3. Your can assigned null to class variable but you can't assigned null value to structure variable
  4. Class support Inheritance but struct does not support so access modifier of a member of a struct cannot be protected or protected internal
  5. You can use Destructor in a class but You can use it in a structure
  6. When passing a class to a method, it is passed by reference. When passing a struct to a method, it's passed by value instead of as a reference.
  7. structures can not be garbage collector so no memory management.
    classes can be garbage collector because garbage collector works on heap memory.

Bulk Insert

connString is your database connection string
dt is the bulk data which has to be uploaded
table is the table name of you database
public void BulkInsert(string connString, DataTable dt, string Table)
        {
            if (connString == null || connString.Length == 0) throw new ArgumentNullException("connectionString");

            using (SqlConnection connection =
                    new SqlConnection(connString))
            {
                SqlBulkCopy bulkCopy =
                    new SqlBulkCopy
                    (
                    connection,
                    SqlBulkCopyOptions.TableLock |
                    SqlBulkCopyOptions.FireTriggers |
                    SqlBulkCopyOptions.UseInternalTransaction,
                    null
                    );

                // set the destination table name
                bulkCopy.DestinationTableName = Table;
                connection.Open();

                // write the data in the "dataTable"
                bulkCopy.WriteToServer(dt);
                connection.Close();
            }
        }

Encryption Decryption

Below are the algorithm which I find as simple and best.

First
///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
// 
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// Copyright (C) 2002 Obviex(TM). All rights reserved.
// 
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

/// 
/// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and 
/// decrypt data. As long as encryption and decryption routines use the same
/// parameters to generate the keys, the keys are guaranteed to be the same.
/// The class uses static functions with duplicate code to make it easier to
/// demonstrate encryption and decryption logic. In a real-life application, 
/// this may not be the most efficient way of handling encryption, so - as
/// soon as you feel comfortable with it - you may want to redesign this class.
/// 
public class RijndaelSimple
{
    /// 
    /// Encrypts specified plaintext using Rijndael symmetric key algorithm
    /// and returns a base64-encoded result.
    /// 
    /// 

    /// Plaintext value to be encrypted.
    /// 
/// 

    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.
    /// 
/// 

    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    /// 
/// 

    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    /// 
/// 

    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    /// 
/// 

    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be 
    /// exactly 16 ASCII characters long.
    /// 
/// 

    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
    /// Longer keys are more secure than shorter keys.
    /// 
/// 
    /// Encrypted value formatted as a base64-encoded string.
    /// 
    public static string Encrypt(string   plainText,
                                 string   passPhrase,
                                 string   saltValue,
                                 string   hashAlgorithm,
                                 int      passwordIterations,
                                 string   initVector,
                                 int      keySize)
    {
        // Convert strings into byte arrays.
        // Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);
        
        // Convert our plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes  = Encoding.UTF8.GetBytes(plainText);
        
        // First, we must create a password, from which the key will be derived.
        // This password will be generated from the specified passphrase and 
        // salt value. The password will be created using the specified hash 
        // algorithm. Password creation can be done in several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase, 
                                                        saltValueBytes, 
                                                        hashAlgorithm, 
                                                        passwordIterations);
        
        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);
        
        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();
        
        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;        
        
        // Generate encryptor from the existing key bytes and initialization 
        // vector. Key size will be defined based on the number of the key 
        // bytes.
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                         keyBytes, 
                                                         initVectorBytes);
        
        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream();        
                
        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream, 
                                                     encryptor,
                                                     CryptoStreamMode.Write);
        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                
        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();
                
        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();
        
        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);
        
        // Return encrypted string.
        return cipherText;
    }
    
    /// 
    /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
    /// 
    /// 

    /// Base64-formatted ciphertext value.
    /// 
/// 

    /// Passphrase from which a pseudo-random password will be derived. The
    /// derived password will be used to generate the encryption key.
    /// Passphrase can be any string. In this example we assume that this
    /// passphrase is an ASCII string.
    /// 
/// 

    /// Salt value used along with passphrase to generate password. Salt can
    /// be any string. In this example we assume that salt is an ASCII string.
    /// 
/// 

    /// Hash algorithm used to generate password. Allowed values are: "MD5" and
    /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
    /// 
/// 

    /// Number of iterations used to generate password. One or two iterations
    /// should be enough.
    /// 
/// 

    /// Initialization vector (or IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be
    /// exactly 16 ASCII characters long.
    /// 
/// 

    /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
    /// Longer keys are more secure than shorter keys.
    /// 
/// 
    /// Decrypted string value.
    /// 
    /// 
    /// Most of the logic in this function is similar to the Encrypt
    /// logic. In order for decryption to work, all parameters of this function
    /// - except cipherText value - must match the corresponding parameters of
    /// the Encrypt function which was called to generate the
    /// ciphertext.
    /// 
    public static string Decrypt(string   cipherText,
                                 string   passPhrase,
                                 string   saltValue,
                                 string   hashAlgorithm,
                                 int      passwordIterations,
                                 string   initVector,
                                 int      keySize)
    {
        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);
        
        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        
        // First, we must create a password, from which the key will be 
        // derived. This password will be generated from the specified 
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase, 
                                                        saltValueBytes, 
                                                        hashAlgorithm, 
                                                        passwordIterations);
        
        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);
        
        // Create uninitialized Rijndael encryption object.
        RijndaelManaged    symmetricKey = new RijndaelManaged();
        
        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;
        
        // Generate decryptor from the existing key bytes and initialization 
        // vector. Key size will be defined based on the number of the key 
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                         keyBytes, 
                                                         initVectorBytes);
        
        // Define memory stream which will be used to hold encrypted data.
        MemoryStream  memoryStream = new MemoryStream(cipherTextBytes);
                
        // Define cryptographic stream (always use Read mode for encryption).
        CryptoStream  cryptoStream = new CryptoStream(memoryStream, 
                                                      decryptor,
                                                      CryptoStreamMode.Read);

        // Since at this point we don't know what the size of decrypted data
        // will be, allocate the buffer long enough to hold ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        
        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 
                                                   0, 
                                                   plainTextBytes.Length);
                
        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();
        
        // Convert decrypted data into a string. 
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 
                                                   0, 
                                                   decryptedByteCount);
        
        // Return decrypted string.   
        return plainText;
    }
}

/// 
/// Illustrates the use of RijndaelSimple class to encrypt and decrypt data.
/// 
public class RijndaelSimpleTest
{
    /// 
    /// The main entry point for the application.
    /// 
    [STAThread]
    static void Main(string[] args)
    {
        string   plainText          = "Hello, World!";    // original plaintext
        
        string   passPhrase         = "Pas5pr@se";        // can be any string
        string   saltValue          = "s@1tValue";        // can be any string
        string   hashAlgorithm      = "SHA1";             // can be "MD5"
        int      passwordIterations = 2;                  // can be any number
        string   initVector         = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int      keySize            = 256;                // can be 192 or 128
        
        Console.WriteLine(String.Format("Plaintext : {0}", plainText));

        string  cipherText = RijndaelSimple.Encrypt(plainText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Encrypted : {0}", cipherText));
        
        plainText          = RijndaelSimple.Decrypt(cipherText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Decrypted : {0}", plainText));
    }
}
//
// END OF FILE
///////////////////////////////////////////////////////////////////////////////
Second
Note: Keys defined in "rgbIV" and "key" should be 16 and 32 characters respectively.
public string EncryptString(string ClearText)
        {

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

            System.Security.Cryptography.SymmetricAlgorithm rijn =  SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream();
            byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); 
            byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo"); 
            CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), 
    CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);

            cs.Close();

            return Convert.ToBase64String(ms.ToArray());
        }

private string DecryptString(string EncryptedText)
        {
            byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


            byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); 
            byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo"); 

            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), 
            CryptoStreamMode.Write);

            cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

            cs.Close();

            return Encoding.UTF8.GetString(ms.ToArray());

        }

Align DrawString

When you perform custom drawing, you may often want to center drawn text on a form or control. You can easily align text drawn with the DrawString or DrawText methods by creating the correct formatting object and setting the appropriate format flags.

Use a StringFormat with the appropriate DrawString method to specify centered text.
string text1 = "Use StringFormat and Rectangle objects to" 
    + " center text in a rectangle.";
using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
    Rectangle rect1 = new Rectangle(10, 10, 130, 140);

    // Create a StringFormat object with the each line of text, and the block
    // of text centered on the page.
    StringFormat stringFormat = new StringFormat();
    stringFormat.Alignment = StringAlignment.Center;
    stringFormat.LineAlignment = StringAlignment.Center;

    // Draw the text and the surrounding rectangle.
    e.Graphics.DrawString(text1, font1, Brushes.Blue, rect1, stringFormat);
    e.Graphics.DrawRectangle(Pens.Black, rect1);
}

From and To Date Filtering

I have been recently creating few reports that required dates as parameters. It is quite common to have a report that must be provided with from and to date range.

When I see two dates that must be provided to a report I believe that when I provide the same date in from and to parameters it will show all data for the particular day. 

But in my case it failed. After going through different queries, I came up with a solution which is below
SELECT *
FROM tbl_Employee 
WHERE DOJ >= DATEADD(dd, 0, DATEDIFF(dd, 0, @InFromDate))
    AND DOJ < DATEADD(dd, 1, DATEDIFF(dd, 0, @InToDate))

Twitter Delicious Facebook Digg Stumbleupon Favorites More