Tuesday, December 30, 2008

C# Questions

Here is the basic question which may get confused at some times

++a it increments the value and then it will assign where as a++ it will assign the value and then it increments

int a = 2;
int b = ++a;

b : 3
a : 3

int a=2 ;
int b =a++;

b : 2
a : 3

?? is the operator chks for the null if both c&f are null it results as -1 or else it results first non null value
int? c = 20;
int? f = null ;
int d = c ?? f ?? -1;

d : 20

int? c = null;
int? f = null;
int d = c ?? f ?? -1;

d : -1;

Convert to binary and left shift bit by 4 digits and then conver to numeric number.Shortcut method is 1*4*4.
int i = 1;
int j = i <<4

j : 16

Convert to binary and right shift by 2 digits and convert to numeric number .Shortcut Method is i =8 then 8/2 = 4/2 = 2
int i = 8;
int j = i >> 2;

j : 2

Monday, December 29, 2008

WebCustom Control VS WebUser Control

Here is the steps to create the custom control.To implement this create two projects

To create Custom Control
1. On the File menu, point to New, and then click Project.The New Project dialog box appears.
2. In the ProjectTypes pane, choose either Visual Basic Projects or Visual C# Projects. Select Web Control Library in the Templates pane.
3. Change the Name to CustomLabel and click OK. The new project is created, and WebCustomControl1 opens in the Code Editor. Code for a custom Label control is included in the Web Control Library template by default.
4. On the Build menu, click Build CustomLabel to compile the control.The control is compiled as CustomLabel.dll. By default, it is created in the Bin folder inside the CustomLabel project folder.
5. Save the file.Now the Default Label is created

To create WebForm
1)On the File menu, point to Add Project, and then click New Project.The Add New Project dialog box appears.
2) In the Project Types pane, choose either Visual Basic Projects or Visual C# Projects. Select ASP.NET Web Application in the Templates pan
3)Click OK.
The new project is created

Adding Control to the Toolbox:
1)Right click on the ToolBox,Select Choose Item
2)You will find the .netFrameWorkComponent tab, select Browse and map the webusercontrol dll
3)Click Ok
4)Now You can find the WebuserControl in the tool box .
5)Double Click on the control or register the control with the following Tag
<%@ Register Assembly="CustomLabel " Namespace="CustomLabel " TagPrefix="cc1" %>
6)Now Run Your Project

Web User Controls vs. Web Custom Controls
Web User Control:
1)Easier to Create.
2)Limited support for consumers who use a visual design tool.
3)A separate copy of the control is required in each application.
4)Cannot be added to the Toolbox in Visual Studio.
5)Good for static layout.

Web Custom Controls
1)Harder to create.
2)Full visual design tool support for consumers.
3)Only a single copy of the control is required, in the global assembly cache.
4)Can be added to the Toolbox in Visual Studio.
5)Good for dynamic layout.

Sunday, December 28, 2008

How to get the value between from date and to date in sql?

How to get the value between from date and to date in sql?

Consider the Table Employee has the following fields such as EId,Name,FromDate,ToDate
Suppose If u want to calculate the employee working days the follwing query results

Select * from Emp Where FromDate Between '2008-04-15 16:40:00' and '2008-04-15 18:47:0' and TODate Between '2008-04-15 00:00:00 and '2008-04-15 00:00:00'

Sunday, December 21, 2008

How to know how many tables contains same column in a database

How to know how many tables contains same column in a database?
Select Count (*) as counter from Syscolumn Where(name ='ColumnName')

Thursday, December 18, 2008

Difference between ISNULL and COALESCE in SqlServer2005

COALESCE() and ISNULL() is more or less but the difference is

1)Coalesce() accepts more than 2 parameter and Isnull() accepts only two parameter

ex: Select ISNULL('test',null, 'test1')
Select COALESCE('test',null,'test1')

IsNull() returns error as The isnull function requires 2 argument(s).
COALESCE() returns test

2)COALESCE() Comapres with any type of datatype Where ISNUL() expression should be of same DataType

ex: Declare @test nvarchar(5)
Declare @test1 int
Set @test= null
Set @test1 =1234567890
Select Isnull(@test,@test1)as nullcolumn
Select COALESCE(@test,@test1,'testingvalue')as coalescecolumn

ISNULL() returns error as Arithmetic overflow error converting expression to data type nvarchar.
COALESCE() returns result as 1234567890

3)Eventhough if the ISNULL() is of same datatype it takes the first datatype.Let Me explain Clearly

ex: Declare @test nvarchar(5)
Declare @test1 nvarchar(10)
set @test = null
set @test1 = '0123456789'
Select Isnull(@test,@test1)as nullcolumn
Select COALESCE(@test,@test1,'testingvalue')as coalescecolumn

ISNULL() return as 01234
COALESCE() return as 0123456789

4)A relatively scarce difference is the ability to apply constraints to computed columns that use COALESCE() or ISNULL(). SQL Server views a column created by COALESCE() as nullable, whereas one using ISNULL() is not.

col1 INT,
col2 AS COALESCE(col1, 0)

Cannot define PRIMARY KEY constraint on nullable column in table 'Try'. Could not create constraint. See previous errors.

Wednesday, December 17, 2008

Install Assembly in GAC

Here is the steps to install Your assembly in GAC

1)Open Visual studio command tool and map the path of the dll that you want to install in GAC

2)Then Create the stongName Key by using sn -k key.snk .It generates the key for the assembly
For ex:
D:/MyProject/bin/debug sn-k Key.snk. key will be generated in the specified path.

3) Now Open Your Project of the corresponding dll , Right Click on the
project -> properties->Application->Assembly Information-> check the option of Make Assembly COM Visible.

4)Next Step
Project->Properties->Signing->select sign the assembly and browse the key from the project. Save the option.

5)Rebulid Your Project.

6)Now Register your assembly add
regasm dllname, to install the assembly in global assembly
Assembly will be registered

7)To install assembly in the
gacutil -i dllname.Now Your dll will be installed in Gac . Check in windows/assembly

Difference Between Aspx and ashx files

Here is the details about ashx file When some one new to this topic

Ashx File is nothing but just like an aspx page.They're equivalent to custom handlers written in C Sharp or Visual Basic.NET in that they contain classes that fully implement IHttpHandler. They're convenient in the same way ASPX files are convenient. You simply surf to them and they're compiled automatically.

When WebForms(aspx)to be used
Simple Html Pages
Asp.net Custom Controls
Simple Dyanamic Pages

When Handlers(ashx) to be used
Binary files
Dynamic Image Views
Performance critical web pages
xml files
Minimal Web Pages

Add the New item Generic handler in the Asp.Net Website

Here is the Example to use HttpHandler

It defines two parts of the IHttpHandler interface. The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested or pointed to.

1.Map the Handler:
you will probably want the new handler to take over an old URL in your site. To do this, use urlMappings.

2.Add Image In to ur Project
Juz add the image in to the project , to use the image in the handler

3. Modify your Handler.ashx
Here You must modify the process request.Juz modify the code as below
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");

context.Response.ContentType = "image/png";

public bool IsReusable {
get {
return false;

4.Now compile and run the default.aspx
Above Specified is simple application
Here is the other sample to handle the handler with the query string
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {

HttpResponse r = context.Response;
r.ContentType = "image/png";
// Write the requested image
string file = context.Request.QueryString["file"];
if (file == "logo")

public bool IsReusable {
get {
return false;
It juz checks the querystring and display the result as specified

Handlers vs. web pages. ASP.NET web forms inherit from the Page class. This provides them with many events and a very detailed initialization and event model. You don't need that for dynamic images, XML, or binary files.

Why is it faster? It is faster because it does a lot less. As you can imagine firing 10+ events each time a request is handled is a fair amount more expensive than only firing one event.

Monday, December 1, 2008

Find Top second salary in sql

Here is the query to find the 1,2,3,4.. nth highest salary

Select Top 1 salary from (select Distinct top 3 salary from Employee Order By Salary desc) as a order by salary asc

Thursday, November 20, 2008

How CLR Manages execution of code

How CLR Manages execution of code?

When the application runs OS(windows) Checks whether the application contains .net headers . When Os finds .net header it starts CLR and load executable assemblies. find the entry point and it starts executing the code.Before it start executes it converts the code in to machinecode by JIT Complier.CLR stores these compiled code as workset and run the compiled code.

Monday, November 17, 2008

Difference Between VSS and TFS

Here is the link which explains the difference between VSS and TFS more specific

Here is the Crisp information about the difference between VSS and TFS

The choice between VSS and TFS depends on Project Complexity

1)When you want to control only your Solution Explorer then it is better to choose VSS whereas TFS supports control over documenting,auditing and SolutionExplorer

2)To Use VSS no extra tools are needed whereas for TFS need IIS,SqlServer

3)Multiple Checkin are allowed for the same file in TFS whereas it is not possible in VSS

4)Scalability is the main difference for VSS . Vss can support a team about 20 peoples whereas TFS supports around 2000 People

5)Visual SourceSafe does not store the merge history between two branches of files or folders. However, Team Foundation source control does have support for merge history

Thursday, November 13, 2008

Insert Select function:Insert Data From One Database to Another Database in sql

Here is the Query to insert the value from a table form one database in to a table in other database if the table is created manually

Insert into database1.dbo.TableName(FieldName1,FieldName2)Select FieldName1,FieldName2 from database2.dbo.TableName

For Ex :
Consider the DataBase Employee and Employee1
Now the Query will be

Insert into Employee.dbo.User(FirstName,LastName)Select FirstName,LastName from Employee1.dbo.User

It Fetches the Record from Employee1 and copy in to Employee

Here is the Query to create the table as same type and insert the values too

Select * into DatabaseName.dbo.NewTableName from DatabaseName.dbo.OldTableName(i.e the value from the table to be copied)

Select * into
Employee1.dbo.User from Employee.dbo.User

Monday, November 10, 2008

Difference between .net3.0 and .net 2.0

with .NET 2.0, the CLR works on a relatively simple concept: A common runtime model executes code for any system running the .NET Framework.
Version 3.0 of the .NET Framework is the first release that doesn’t improve on the Common Language Runtime.The .NET 3.0 Framework isn’t improving upon existing technologies but rather introducing four new foundation technologies:
* Windows Presentation Foundation (WPF)
* Windows Communication Foundation (WCF)
* Windows Workflow Foundation (WWF)
* Windows CardSpace (WCS)

Windows Presentation Foundation (WPF)

Windows Presentation Foundation (WPF) is arguably the most well-known of the four new foundation class sets. This is largely because of two things:

* You can actually see a WPF solution.
* WPF has been compared frequently to Adobe’s Flash
WPF is a consistent programming model for building solutions, and enables the use of richer controls, design, and development in Windows programs. A WPF program can be developed and released to desktops, the Web, and devices.Once interesting aspect of WPF is the XML standard programming language called XAML (pronounced "Zammel") that controls the layout of objects

Windows Communication Foundation

The core purpose of the Windows Communication Foundation (WCF) is to allow programs to talk to other programs on the same computer or network, or across the Internet. The WCF programming model unifies web services, .NET Remoting, distributed transactions, and message queues into a single service-oriented programming model for distributed computing.WCF is designed in accordance with service-oriented architecture principles to support distributed computing, in which services are used by consumers, clients can consume multiple services, and services can be consumed by multiple clients. Services typically have a WSDL interface that any WCF client can use to consume the service, irrespective of the platform on which the service is hosted.

Windows Workflow Foundation

Windows Workflow Foundation (WWF) is a Microsoft technology for defining, executing, and managing workflows. Workflows are composed of activities; developers can write their own domain-specific activities and then use them in workflows


Windows CardSpace, originally code-named "InfoCard," lets any Windows application, including Microsoft technologies such as the next release of Internet Explorer and those created by others, give its users a common way to work with digital identitiesThe goal is to let people on any machine, running any operating system, use digital identities as easily, as effectively, and as securely as they today use their identities in the physical world.

Find All Stored Procedure in SqlTable

Following code will help to find all the Stored Procedures (SP) which are related to one or more specific tables. sp_help and sp_depends does not always return accurate results.

   ----Option 1
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name ,o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

Thursday, September 18, 2008

Add Dynamic Column in SQL

Here is the Code to Add column dynamically in a table

Declare @ColumnName as Varchar(50)
declare @ssql nvarchar(200)
Set @ColumnName ='Column1'
set @ssql = 'Alter table TableName Add ' + @ColumnName + ' int'
exec sp_executesql @ssql

Here is the code to add dynamic column with data type

Declare @ColumnName as Varchar(50)
declare @ssql nvarchar(200)
declare @DataType

Set @ColumnName ='Column1'
Set @
DataType ='Bigint'
set @ssql = 'Alter table TableName Add ' + @ColumnName + ' ' +@DataType
exec sp_executesql @ssql

Tuesday, September 16, 2008

Remove ?xml version="1.0" encoding="utf-8"? in c#

Here is the code to remove xml header

public class XmlTextWriterFormattedNoDeclaration : System.Xml.XmlTextWriter
public XmlTextWriterFormattedNoDeclaration(System.IO.TextWriter w): base(w)
Formatting = System.Xml.Formatting.Indented;

public override void WriteStartDocument() { } // suppress
Then you can serialize like this

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(typeof(object));
StringWriter sw = new StringWriter();
XmlWriter writer = new XmlTextWriterFormattedNoDeclaration(sw);
serializer.Serialize(writer, this, ns);

Wednesday, September 10, 2008

Difference Between Rank and DenseRank in Sql

Here is the differnce between  Rank() and DenseRank() function
Consider Below  Table Employee Which is ordered by salary
Table Name: Employee
EmpId         Name         Salary
 1  John       100
 2               Jenny           170
 3               Mac             170
 4               Millon 350

Here is the query to rank employee by salary

Select *, Dense_RANK() over(order by Salary) As DenseRank,RANK() over(order by Salary) As Rank From Employee  

Now the tablewill be
EmpId           Name            Salary       Rank     DenseRank
 1                John             100          1             1
 2                 Jenny             170          2             2
 3                 Mac                170         2             2
 4                 Millon  350         4             3

Dense Rank last value will be the total unique value in table

Friday, September 5, 2008

Cropping and Resizing Image in c#

Here is the best link to crop and resize the image step by step process

Merge Image in c#

Here is the code to merge image in c#
// Create a new image
Image img = new Bitmap(300, 100);
// Create image object from existing image
Image img = Image.FromFile("Image.jpg");
Before make changes with img we need to convert it to Graphics object: 
Graphics g = Graphics.FromImage(img);
// Place a.gif
g.DrawImage(Image.FromFile("a.gif"), new Point(10, 10));
// Save changes as output.jpg
img.Save("output.jpg", ImageFormat.Jpeg);

Thursday, August 7, 2008

Read SWF File As Byte Array

By using the following function we can Read the SWF File as Byte Array

byte[] data= File.ReadAllBytes("Path of the file")
//Save SWF File in Specified Path
string path = "D:\\SWFFiles\\test.swf";
string dirPath = path.Remove(path.LastIndexOf("\\"), (path.Length - path.LastIndexOf("\\")));
if (!Directory.Exists(dirPath))
using (BinaryWriter binWriter = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate)))

Write Image in Browser C#

using System.IO;
using System.Text;
using System.Xml;

protected void Page_Load(object sender, EventArgs e)
Response.ContentType = "image/jpeg";
Response.BufferOutput = true;
//Read the Image in Byte Array
byte[] data= File.ReadAllBytes("Path of the Image");
//Write the Image in Browser
using (MemoryStream stream = new MemoryStream(data))

Wednesday, July 9, 2008

WCF in .net

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. Although in theory you could build services without WCF, in practice building services is significantly easier with WCF. WCF is Microsoft’s implementation of a set of industry standards defining service interactions, type conversion, marshaling, and various protocols’ management. Because of that, WCF provides interoperability between services. WCF provides developers with the essential off-the-shelf plumbing required by almost any application, and as such, it greatly increases productivity. The first release of WCF provides many useful facilities for developing services, such as hosting, service instance management, asynchronous calls, reliability, transaction management, disconnected queued calls, and security. WCF also has an elegant extensibility model that you can use to enrich the basic offering. In fact, WCF itself is written using this extensibility model. The rest of the chapters in this book are dedicated to those aspects and features. Most all of the WCF functionality is included in a single assembly called System.ServiceModel.dll in the System.ServiceModel namespace.

Friday, July 4, 2008

Self-Join in SQL

when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same.
If you have a table of members who can refer each other for services, then this might be a job for a SELF JOIN in sql where you INNER JOIN a table to itself
SELECT c.custname AS 'Customer', r.custname AS 'Referrer'
FROM customers AS c
INNER JOIN customers AS r ON c.referredby=r.custnum
WHERE c.referredby<>'99999'
ORDER BY c.custname;

Wednesday, July 2, 2008

Event Objects In Javascript

Src Element
In Explorer =
The element which fired the event.
In FireFox = target, but in Firefox the nodes of type text can also fire events,
so to keep things working you'll need to climb up the tree until you find a element's (tag's) node:
var node = e.target;
while(node.nodeType != node.ELEMENT_NODE)
node = node.parentNode;

To get the Position of the window browser
relative to the screen.
In Explorer =
In FireFox =
window.screenX - someValue,
window.screenY + someValue
These properties are not extactly the same as the Explorer.
In explorer they give the coordinates of the origin of
the IE control, while in Firefox they give the origin
of the Firefox window itself.

Function to element's event_name.
In Explorer = element.attachEvent( event_name, function)
In FireFox =
element.addEventListener(event_name, function, false)

Function to the node element
In Explorer =contains(node)
In FireFox =
DOM level 2 does not have an equivalent method,
but a very simple method like the shown below can be used
(it works in Firefox and Explorer):
function contains(a, b)
// we climb through b parents
// till we find a
while(b && (a!=b) && (b!=null))
b = b.parentNode;
return a == b;
The new DOM level 3 standard defines
node.compareDocumentPosition() and
Firefox already implements it, but Explorer doesn't.

To obtain the window in which the document is.

In Explorer =document.parentWindow
In FireFox = document.defaultView.
Note that the window object is available everywhere.

Access a form
In Explorer = myForm
In FireFox =document.myForm, it works everywhere.

Tuesday, July 1, 2008

Validate Multiple Email Addresses in javascript

function mailValidation()
var emailfield = document.getElementById('controlId').value;
var email = emailfield.split(';');
if(email.length > 0)
for(var i=0;i < email.length;i++)
var toSpan = document.getElementById('spanId').innerHTML;

if(toSpan != "")
return false;
function validateEmails(addr,man,db,SpanId,controlId)
if (addr == '' && man) {
if (db)
document.getElementById(SpanId).innerHTML="Enter To address ";
return false;
if (addr == '') return true;
var invalidChars = '\/\'\\ ",:?!()[]\{\}^|';
for (i=0; i if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
if (db)
document.getElementById(SpanId).innerHTML="To address contains invalid characters(Enter in the format:name@example.com;name@example.com)";
return false;
for (i=0; i if (addr.charCodeAt(i)>127) {
if (db)
document.getElementById(SpanId).innerHTML="To address contains non ascii characters";
return false;

var atPos = addr.indexOf('@',0);
if (atPos == -1) {
if (db)
document.getElementById(SpanId).innerHTML="Email address must contain an @";
return false;
if (atPos == 0) {
if (db)
document.getElementById(SpanId).innerHTML="Email address must not start with @";
return false;
if (addr.indexOf('@', atPos + 1) > - 1) {
if (db)
document.getElementById(SpanId).innerHTML="Email address must contain only one @";
return false;
if (addr.indexOf('.', atPos) == -1) {
if (db)
document.getElementById(SpanId).innerHTML="Email address must contain a period in the domain name";
return false;
if (addr.indexOf('@.',0) != -1) {
if (db)
document.getElementById(SpanId).innerHTML="period must not immediately follow @ in email address";
return false;
if (addr.indexOf('.@',0) != -1){
if (db)
document.getElementById(SpanId).innerHTML="period must not immediately precede @ in email address";
return false;
if (addr.indexOf('..',0) != -1) {
if (db)
document.getElementById(SpanId).innerHTML="Two periods must not be adjacent in email address";
return false;
var suffix = addr.substring(addr.lastIndexOf('.')+1);
if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
if (db)
document.getElementById(SpanId).innerHTML="Invalid primary domain in email address";
return false;


javascript validation for gridview

var theGridView = null;
theGridView = document.getElementById(gridViewCtlId);
for ( var rowCount = 1; rowCount < theGridView.rows.length; rowCount++ )
var theGridViewRemarks = theGridView.rows[rowCount].cells[0];
var textbox = theGridView.rows[rowCount].cells[0];
var value= textbox .firstChild.nextSibling;
var value= textbox .firstChild;

Monday, June 30, 2008

Like Query In SQL

Which of the query executes Perfectly
1) select * from emp where name like'[b-d]%'
2) select * from emp where name ='[b-d]%'

Option 1 Returns the records starting with b,c,d Where as option 2 will not return error, it return empty row

What Happens When a Request Reaches IIS

When a request arrives at an IIS Web server, IIS examines the requested file's extension to determine how handle the request. Requests can be handled natively by IIS—as are HTML pages, images, and other static content—or IIS can route the request to an ISAPI extension. (An ISAPI extension is an unmanaged, compiled class that handles an incoming Web request. Its task is to generate the content for the requested resource.)
For example, if a request comes in for a Web page named Info.asp, IIS will route the message to the asp.dll ISAPI extension. This ISAPI extension will then load the requested ASP page, execute it, and return its rendered HTML to IIS, which will then send it back to the requesting client. For ASP.NET pages, IIS routes the message to the aspnet_isapi.dll ISAPI extension. The aspnet_isapi.dll ISAPI extension then hands off processing to the managed ASP.NET worker process, which processes the request, returning the ASP.NET Web page's rendered HTML.

Note : ASP.NET-related extensions—.aspx, .ascx, .config, .asmx, .rem, .cs, .vb, and others—are all mapped to the aspnet_isapi.dll ISAPI extension.

If a user visits /Products/, IIS doesn't see any file extension, so it checks the directory to see if there exists a file with one of the default filenames. (Default.aspx, Default.htm, Default.asp, and so on. These default filenames are defined in the Documents tab of the Web Server Properties dialog box in the IIS Administration dialog box.) Of course, if the /Products/ directory doesn't exist, IIS will return an HTTP 404 error.

Perform some action when close button is clicked in javascript

Alert hi when window close button is clicked
function BrowserClosed()
var top=self.screenTop;
if (top>9000)