Understanding StopWatch Class in c#

Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Startmethod, then eventually call the Stop method, and then you check elapsed time using the Elapsed property. (From MSDN)

Let say i want to find out Total Time a Process has been Running. 
1. How many Minutes or Second it took to insert 1000 record in Database?
2. How many time it took to update the Database ? etc ..

I provide a very Basic Example with a Console Application ..

The Stopwatch Class has two Primary Methods 1. Start() 2. Stop() and One Property that is Elapsed .

The Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace StopWatchExample
class Program
static void Main(string[] args)
Stopwatch sw = new Stopwatch();
Console.WriteLine("Stop Watch Start....n");
for (int i = 1; i <= 5; i++)
Console.WriteLine(i + "n");
Console.WriteLine("Stop Watch Stopped:");
Console.WriteLine("Total Time: {0}", sw.Elapsed);

As You can See I have started our Stopwatch Just Before My loop has started.
Now the Loop will Do its work ..
After That As Soon As we are out sw.Stop has been Called.

I have Just Recorded The Timing The Loop Took To Complete.

The Output Will Look SomeThing Like These:


Embeding Firefox Brower (Gecko Engine) in C# using GeckoFX

Ever Thought if it was possible to not WebBrower control and use the Firefox Browser in your c# window Application…??

Yes ,, It is possible using GeckoFx wrapper class for  C#.net and vb also.

You will need the Followings:

1. GeckoFx Wrapper [Download]
2. Xul Runner [Download] (Download the zip file from here)

How to:

1.   Now Extract Skybound.GeckoFX.bin.v1.9.1.0.zip (First download).
      You will find Skybound.Gecko.dll and that’s what we need.
2.   Now create a Project and name is GeckoFxcsharpBorwer or anything you like.
3.   Now  add the reference of the above dll and also add that to your toolbox.
4.   Now Exctract the Second downloaded file (xulrunner- and you will find xulrunner . This is the path to xulrunner runtime.
5.   Create a Form Layout Like The Figure Below:

Now The Coding Part:

Our Form’s Constructor:(Providing the Path to XulRunner Runtime)

public Form1()
Skybound.Gecko.Xpcom.Initialize("Path To the xulrunner directory [Extracted from the Second Downloaded File]"); // for example "c:\xulrunner\"

Form’s Load Event:

private void Form1_Load(object sender, EventArgs e)

Stop Button click Event:

private void btnStop_Click(object sender, EventArgs e)

Refresh Button Click Event:

private void btnRefresh_Click(object sender, EventArgs e)

Save Page Button Click Event:

private void btnSavePage_Click(object sender, EventArgs e)
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = " Html File | *.html";
if (sfd.ShowDialog() == DialogResult.OK)

And Now Finally the Output:

That’s All.

Complete Project : GeckoNet

ps: You can easily Add an Addressbar and other stuff


Parsing Comma Delemeted String in Sql

I will just go with the Example as its Self Exclamatory.

Sql Query:

declare @string varchar(500)

declare @pos INT
declare @piece varchar(500)

-- Need to tack a delimiter onto the end of the input string if one doesn’t exist
if right(rtrim(@string),1) <> ','
set @string = @string + ','

set @pos = patindex('%,%' , @string)
while @pos <> 0
set @piece = left(@string, @pos - 1)

-- You have a piece of data, so insert it, print it, do whatever you want to with it.
print cast(@piece as varchar(500))

set @string = stuff(@string, 1, @pos, '')
set @pos = patindex('%,%' , @string)



A stored Procedure to Count Numbers of Rows in Table

This a simple Stored procedure to count the total numbers of rows in each table of your Database.
I assume you have Northwind database installed.

The Stored Procedure

FROM sysobjects
WHERE id = OBJECT_ID(N'[dbo].[sp_GetRowsCountForAllTables]')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1 )
DROP PROCEDURE [dbo].[sp_GetRowsCountForAllTables]

CREATE PROCEDURE sp_GetRowsCountForAllTables
SET nocount ON

TableName VARCHAR(128)
, norows INT NULL
, id INT IDENTITY(1, 1)

, @maxID INT
, @TableName VARCHAR(128)
, @FKName VARCHAR(128)
, @cmd NVARCHAR(1000)
, @rc INT
, @spcmd VARCHAR(1000)

SET @cmd = 'exec ' + @DBName + '..sp_executesql N''insert #a (TableName)
select TABLE_NAME from information_schema.tables
where TABLE_TYPE = ''''BASE TABLE'''' ''
EXEC (@cmd)

SELECT @id = 0
, @maxID = MAX(id)

WHILE @id < @maxID
SELECT @id = MIN(id)
WHERE id > @id

SELECT @TableName = TableName
WHERE id = @id

SET @cmd = 'exec ' + @DBName
+ '..sp_executesql N''update #a set norows = (select rows from sysindexes where indid in (0,1) and id = object_id('''''
+ @TableName + '''''))'
SET @cmd = @cmd + ' where #a.id = ' + CONVERT(VARCHAR(10), @id)
+ ''''

EXEC (@cmd)
IF @rc <> 0
OR @@error <> 0
RAISERROR('failed %s',16,-1,@TableName)

FROM #a ORDER BY norows desc


The Output:

EXEC sp_GetRowsCountForAllTables


Finding Duplicates in a Table ‘s Column

I assume You have Northwind Database.

I will be using The Employee Table.

As Show in the figure there are 6 Selected cells which are the Duplicates( Just assume it)
I want to find this number ( i mean 6.)

The query for the above is:

, COUNT(Title) AS NumOccurrences
FROM dbo.Employees
HAVING ( COUNT(Title) > 1 )

FROM dbo.Employees


Finding Total Number of Rows, Columns in a Database and Tables Sizes

Here is the Script:

USE Northwind 
table_name SYSNAME
, row_count INT
, reserved_size VARCHAR(50)
, data_size VARCHAR(50)
, index_size VARCHAR(50)
, unused_size VARCHAR(50)


INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused ''?'''
SELECT a.table_name
, a.row_count
, COUNT(*) AS col_count
, a.data_size
FROM #temp a
INNER JOIN information_schema.columns b ON a.table_name COLLATE database_default = b.table_name COLLATE database_default
GROUP BY a.table_name
, a.row_count
, a.data_size




.Net Framework 3.0 Vs 3.5 Vs 4.0 (.Net FrameWork Comparisions)

NET Framework 3.0 consists of four major new components:

  • Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
  • Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
  • Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
  • Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person’s digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.

Changes in 3.5 since 3.0

  • New language features in C# 3.0 and VB.NET 9.0 compiler
  • Adds support for expression trees and lambda methods
  • Extension methods
  • Expression trees to represent high-level source code at runtime.
  • Anonymous types with static type inference
  • Language Integrated Query (LINQ) along with its various providers
  • LINQ to Objects
  • LINQ to XML
  • LINQ to SQL
  • Paging support for ADO.NET
  • ADO.NET synchronization API to synchronize local caches and server side datastores
  • Asynchronous network I/O API.
  • Peer-to-peer networking stack, including a managed PNRP resolver
  • Managed wrappers for Windows Management Instrumentation and Active Directory APIs
  • Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services. WCF services can be made stateful using the WF persistence model.
  • Support for HTTP pipelining and syndication feeds.
  • ASP.NET AJAX is included.

Key focuses for 4.0  release are:

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as statement lambdas, implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).

Source: wikipedia.org


Encryption and Decryption Functions In Vb.net


Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text


Public Function Encrypt(ByVal plainText As String) As String

Dim passPhrase As String = "yourPassPhrase"
Dim saltValue As String = "mySaltValue"
Dim hashAlgorithm As String = "SHA1"

Dim passwordIterations As Integer = 2
Dim initVector As String = "@1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256

Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)

Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)

Dim keyBytes As Byte() = password.GetBytes(keySize 8)
Dim symmetricKey As New RijndaelManaged()

symmetricKey.Mode = CipherMode.CBC

Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

Dim memoryStream As New MemoryStream()
Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)

cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
Dim cipherTextBytes As Byte() = memoryStream.ToArray()
Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
Return cipherText
End Function


Public Function Decrypt(ByVal cipherText As String) As String
Dim passPhrase As String = "yourPassPhrase"
Dim saltValue As String = "mySaltValue"
Dim hashAlgorithm As String = "SHA1"

Dim passwordIterations As Integer = 2
Dim initVector As String = "@1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
' 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.
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

' Convert our ciphertext into a byte array.
Dim cipherTextBytes As Byte() = 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.
Dim password As 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).
Dim keyBytes As Byte() = password.GetBytes(keySize 8)

' Create uninitialized Rijndael encryption object.
Dim symmetricKey As 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.
Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

' Define memory stream which will be used to hold encrypted data.
Dim memoryStream As New MemoryStream(cipherTextBytes)

' Define cryptographic stream (always use Read mode for encryption).
Dim cryptoStream As 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.
Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}

' Start decrypting.
Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)

' Close both streams.

' Convert decrypted data into a string.
' Let us assume that the original plaintext string was UTF8-encoded.
Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

' Return decrypted string.
Return plainText
End Function


Dim strEncryptedText  As String
strEncryptedText = Encrypt("yourEncryptionText")

Dim strDecrptedText As String
strDecrptedText = Decrypt(strEncryptedText)

You can easily set the passphrase, saltvalue and bits to your liking..

For More Info Go to:

Fill free to Comment ..


A Function to Concat String Array Values by Specified Delimiter

Let ‘s Say I have Following Array:

string[] st = new string[5];
st[0] = "Animation";
st[1] = "Action";
st[2] = "Romance";
st[3] = "Drame";
st[4] = "Comedy";

Now I want to Merge all of it with ‘,’ Delimiter Like Below:

Output :   Animation,Action,Romance,Drame,Comedy

Here is the Function For the Above

public string GetAllStringsFromArrary(string[] strArray,string strDelimeter)
string strFinal = string.Empty;

for (int i = 0; i < strArray.Length ; i++)
strFinal += strArray[i];

if (i != strArray.Length - 1)
strFinal += strDelimeter;
return strFinal;


We will Call it Like This:

string str = GetAllStringsFromArrary( st,",");