Thursday, December 29, 2011

How to add Lead Control References

1. Goto Tools->Options

2.Select Project and Solutions-> VC++ Directories


3. Select Executable Directories from the Combo box and add the redist path as selected in snapshot.


4. Select Include files from the Combo box and add the classlib path as selected in snapshot.



5. Select Include files from the Combo box and add the vcl path as selected in snapshot.



6. Select Library files from the Combo box and add the vcl path as selected in snapshot.



You can download the document and application from here: Click Here

Wednesday, December 21, 2011

Error 6 fatal error C1083: Cannot open type library file: 'msxml.dll': No such file or directory

Replace this line

#import <msxml.dll> named_guids

with this one

#import <msxml.tlb> named_guids

And build the application.

Friday, December 9, 2011

Pdf To Post Script

Write this function in a Java Script file and save this file into JavaScript Folder inside Adobe(C:\Program Files\Adobe\Acrobat 9.0\Acrobat\Javascripts) with js extension.

function pdftops()
{
var pp = this.getPrintParams();

var path = this.path;
path = path.replace("/\//gi", "");
path = path.replace("/%20/gi", " ");
path = path.replace("/\\/gi", "\/");

var PdfName = path;
var iDotIndex = PdfName.indexOf(".");
PdfName = PdfName.substring(0,iDotIndex);

var OutputFilePath = this.documentFileName;

pp.fileName = PdfName + ".ps";
pp.printerName = "";
this.print(pp);
}

Or you can download java script file from this path

PdfToPs

Now call this function from VB .Net in this way

Private Sub ConverToPostScript(ByVal InputFilePath As String)
Dim gApp As Acrobat.CAcroApp
Dim gPDDoc As Acrobat.CAcroPDDoc
Dim jso As Object
Dim PsFilePath As String


gApp = CreateObject("AcroExch.App")
gPDDoc = CreateObject("AcroExch.PDDoc")
If gPDDoc.Open(InputFilePath) Then

jso = gPDDoc.GetJSObject

PsFilePath = System.IO.Path.ChangeExtension(InputFilePath, "ps")

If (System.IO.File.Exists(PsFilePath)) Then
System.IO.File.Delete(PsFilePath)
End If

jso.pdftops()
}

Before start coding in .Net you need to add Arobat dll reference from com component(Adobe Acrobat 9.0 Type Library)

Complete Setup Here Distiller

Friday, October 28, 2011

Difference Between Throw and Throw ex

1. Throw is used to throw current exception while throw ex used to create wrapper of exception.
2. Throw ex reset the stack trace so error will appear from the line where throw ex is written while Throw does not reset the stack trace.
3. In MSIL code, when use throw ex it will generate code as throw while throw will create code for rethrow..
4. Throw ex is used to customize the exception.



Friday, September 16, 2011

Difference between Int32.Parse and Convert.ToInt32

Both function use for string format to integer value.

There are some cases

1) If string is null Parse throws ArugmentNullException
2) If String it not compatible to int it throws Format Exception
3) If value is less than Minimum value or greater than Maximum value it will throws Overflow Exception

While in case of Contvert.ToInt32. This function is a wrapper of Int32.Parse. It throws the same exception except in case of null string it returns zero(0).

Example
string s1 = "20";
string s2 = "25.50";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


result = Convert.ToInt32(s1); //-- 25
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException

Int32.TryParse doesn't throws any exception instead it returns zero if value is not compatible. and return false.

success = Int32.TryParse(s1, out result); //-- success => true; result => 25
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0

Friday, September 9, 2011

Locking in SQL Server

In multi user environment SQL Server use lock to prevent conflict modification. This is purely logical no hardware is needed for that.

There are different types of lock available in SQL Server.

1) Shared Lock :- In shared lock other process can not modify the data they can read only. Shared lock used for operations that do not change or modify the data. Select statement is an example of shared lock. Shared lock are held on data under the pessimistic concurrency level.Two shared lock are compatible with each other.

2)Update Lock :- SQL Server use the Update Lock when SQL Server intends to modify the data. It later promote Update Lock to Exclusive lock when actually making the changes.Update lock are compatible with shared lock.Basically to avoid deadlock update lock has used.

3) Exclusive (X) :- Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.

4) Intent :- Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).

5) Schema :- Used when an operation dependent on the schema of a table is executing. The types of schema locks are schema modification (Sch-M) and schema stability (Sch-S).

6) Bulk Update (BU) :- Used when bulk-copying data into a table and the TABLOCK hint is specified.


Friday, September 2, 2011

Static Class

Static class used to define the information that is object independent like company info. Static class contain only static methods and properties. Instance constructor can not be created inside static class. Although a static constructor can be defined there.

Properties of static class

1) Static class are sealed they can not be inherited since there is no constructor. Like a class which contain a private constructor.
Static class can not inherit another class nor simple nor static.
2) They can not be instantiated.
3)They are loaded when program or namespace containing the static class load.
4) They can not have non static methods or variables.
5) They can have only static constructor if needed.
6) Benefit of using static class, compiler guarantee this thing that class does not have any instance.
7) Static class make implementation simple and faster since there is no object needed to call the methods. A good example of static class is Math class that contain all math functions like sin,cosine.

Friday, August 26, 2011

What is JSON?

JSON stand for Java Script Object Notation, is a text base format, that contains the value in key value pair.

JSON can be used as

var objJSON = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.

Members can be retrieved using dot or subscript operators.

objJSON.bindings[0].method // "newURI"

Friday, August 19, 2011

Force User to Check in the code

My machine has been corrupted. Thank God mostly projects were checked in. I have lost some project code which was not checked in. Than I really feel the importance of VSS. Than I have found a option in Visual Studio which force you to check in your code before closing your project. I would like share it with you people.

Go to Tools- Option


A dialog box will open for you select Source Control -- Environment


After selecting Environment check the option (Enclosed in Red Color Box) “Check Everything When Closing Solution or Project”.

Friday, August 12, 2011

Active Directory

What is Active Directory?
An Active Directory is a service that stores information about items on Network so the information can be easily made available through a logon a process or Network Administrator. You can view entire network object from a single point using Active Directory.

Active Directory performs a variety of task which includes providing information on objects such as Hardware and Printer and services for the end users on the Network.

What is the use of Active Directory?
In network environment it is crucial to control access to each network device easily. A method is needed to control who has access to which device and when.This includes printers, files and another local network resource or item on distributed network.

AD is simply hierarchical database that represents al of your network resources.

In .Net there is System.DirectoryServices namespace through which you can manage Active Directory in .Net.

Friday, August 5, 2011

Find Element name on MouseDown IE-8

Yesterday I was working on click even of WebBrowser Control(HtmlDocument). I need to find element name on mouse down event. I have used simple method of WebBrowser

HtmlElement objHtmElem = objWebBrwser.Document.GetElementFromPoint(e.MousePosition);

It was working fine in IE-5. But when I have installed IE-8. All the functionality has been disturbed. On mouse down it was giving Document Element name no matter matter where you have down your mouse.

After lot of googling I have solved the problem. Actually where we have used e.MousePosition we must use e.ClientMousePostion like..

HtmlElement objHtmElem = objWebBrwser.Document.GetElementFromPoint(e.ClientMousePosition);

This works fine for both browser(IE-5 and IE-8).

Friday, July 29, 2011

Call Server Side Method using ajax JQuery in ASP .Net

When I have started work on ajax. I used to passed parameters in the url while calling server side method through ajax call. But problem was that when we send value with Hash(#). It was not sending whole value to server side.It was sending only value before hash(#). Than I have found another way to send parameter to sever side.We can directly call server side method and pass parameter through ajax call.


Write this function on client side.

function SendServer()
{

// var sVal = $("#txtName").val();

var sVal = "Red";

$.ajax(
{
type: "POST",
url: "Customer.aspx/GetValue",
data: "{param1: " + "'" + sVal + "'" + " }",
//data: "{'param1': 1}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout:5000,
success: function (msg)
{

alert(msg);
// $('#Rslt').text(msg);
},
error:function(msg1)
{
alert(msg1);
// $('#Rslt').text("Some error has been occurred.");
}
});
}

And on server side define a static method with WebMethod attribute. Add a name space System.Web.Services

[WebMethod]
public static string GetValue(string param1)
{
return "Call Server Side method through ajax call and pass parameter :" + param1;
}


One thing that you have to remember parameter name should be same on both side.Just like the above example I have used param1 both side.


You can download the sample code from here.

http://www.box.net/shared/ivv6jhk1gm

Friday, July 22, 2011

Search is not working in Windows XP

Today I have encountered search problem in Windows XP. I was trying to find a string in a folder which contains files with extension .xhtml. But could not while file was exist inside folder with searched text.

Actually windows has some specified extension for which it do the search. If you want to add some more extension follow these step.

1) Go to Run.
2) Type REGEDDIT
2) Go to HKEY_CLASSES_ROOT
3) Expand the key and search your desired extension here.
If it is not here create one the name it like .xhtml,.xml,.bak whatever required
4) Create a subkey and name it PersistentHandler.
5) Double click on Default item in the right side pane.
6) A pop up window will, Copy paste below string in the value filed and close it

{5e941d80-bf96-11cd-b579-08002b30bfeb}

7) Reboot the system.

For an Example I have done it for .xhtml file and my registry key is

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.xhtml\PersistentHandler]
@="{5e941d80-bf96-11cd-b579-08002b30bfeb}"

Or


[HKEY_CLASSES_ROOT\.[EXTENSION]\PersistentHandler]
@="{5e941d80-bf96-11cd-b579-08002b30bfeb}"

Or

You download this file and change your extension in the file it is for .xhtml currently. You can replace .xhtml with your required one. Now just double click on the file and follow the instruction.

http://www.box.net/shared/xjehmjqxic

Friday, July 15, 2011

Put the dlls in separate directory

In dot net you can put the dlls in separate directory from the exe. You need to add following code in your config file.

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" >
<probing privatePath="bin;bin2"/>
</assemblyBinding>
</runtime>
</configuration>


privatePath : contains the directory name where put your dll files. It may contain multiple directory name separated by semi colon.

Friday, July 8, 2011

How to create Bookmark in pdf file

How to create bookmark in pdf file using Java Script. In java script we can create a plug-in to create the bookmark in Adobe Acorbat Reader.


To create a book mark in pdf file just download the file

bookmark_pagejs-10


And copy this file at

* Mac: ~/Library/Application Support/Adobe/Acrobat/9.0_x86/JavaScripts (or similar)
* Linux: /home/[User Name]/.adobe/Acrobat/9.0/JavaScripts/
* Windows XP: C:\Documents and Settings\[User Name]\Application Data\Adobe\Acrobat\9.0\JavaScripts (or similar)
* Windows 7 & Vista: C:\Users\[User Name]\AppData\Roaming\Adobe\Acrobat\9.0\JavaScripts


With the help of this file you can create multiple bookmark. Restart the Acrobat Reader and go to View->Bookmark this page.

But if you want to create a single bookmark just like a book. For that download the file.

pdf_bookmark.zip

And copy it on same location.

Restart the Acrobat Reader and go to Tools->Bookmark -> Bookmark this page.

Friday, July 1, 2011

UpdateMode in Update Panel

UpdateMode property in Update Panel.

Why update panel is slow?
Due to Update Mode property of the UpdatePanel. If it is set to Always it will make the whole page slow. Since on each post back each Update Panel content update.

This property plays an important role in performance of ASP .Net page. By default it is Always.

When UpdateMode set to Always?

1) The update panel content is always updated on each post back of page whether it is synchronous call or asynchronous. No matter the control that triggered the post back is inside the update panel or not. Or inside other update panel.
2) If the update panel is inside other update panel. Than when parent will update child always update. No matter child update panel update mode is Always or Conditional.

When UpdateMode set to Conditional?

1) Update Panel content will update only in case of any control that is inside Trigger cause post back.

2) Or if ChildrenASTrigger set to true. Than Update Panel contents update in case of its child cause post back.

3)Or you have called Update method of Update Panel explicitly.

ChildrenAsTrigger property in UpdatePanel
Set it to true to update the content of update panel on post back cause by children control of the update panel. If panel is nested with another update panel. Than parent update panel contents will not update on post back cause by children control of the inner update panel.

By default value of ChildrenASTrigger is true.

You can not set it false with UpdateMode="Always". In that case InvalidOperation Exception thrown during PreRender event.

RenderMode property in UpdatePanel.

There are two possible values for RenderMode one is inline and other one is block. if it is set inline Update Panel convert into span tag. In case of block Update Panel convert into div tag. By default value of RenderMode is div.

Friday, June 24, 2011

Security in Web Service

If you want that only authenticated user can call a Web Service method than you have to use SoapHeader for that. Suppose you have a webservice defined as below. You can decorate any method with SoapHeader attribute which you want to secure. In SoaHeader you have to give object name of Validator class.

What is Validator class? When you use SoapHedaer authentication you have to define a User defined class inherited with SoapHeader class. You can define your own variables and properties inside that class to authenticate. This all information related to that Validator class goes in Header section.

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Configuration;

public class Service:System.Web.Services.WebService
{
public CValidate objCValidate;

public Service()
{
}

public class CValidate:SoapHeader
{
private string sUser;

public string User
{
get { return sUser; }
set { sUser = value; }
}
private string sPassword;

public string Password
{
get { return sPassword; }
set { sPassword = value; }
}
}

[WebMethod,SoapHeader("objCValidate")]
public string HelloWorld()
{
if (objCValidate.User =="Khaleek" &&
objCValidate.Password =="Ahmad")
{
return "User Name : " +objCValidate.User + " and " +
"Password : " +objCValidate.Password;
}
else
{
return "Invalid credential";
}
}
}

How to call this method

private void CallWebSrvMethod()
{

localhost.Service objWebService = newlocalhost.Service();
localhost.CValidate objCValidate =
newlocalhost.CValidate();

objCValidate .strUserName = “Khaleek”;
objCValidate .strPassword = “Ahmad”;

objWebService.objCValidate =objCValidate;
string str = objWebService.HelloWorld();
}


The XML structure of an XML Web service response can defined as follows:




Khaleek
Ahmad





User Name : Khaleek and Password : Ahmad





Header tag is optional that contains additional information. Body tag contains the main message. CValidate is the name of class that represent SoapHeader class and inherit SoapHeader. Each element of the CValidate tag is called SoapHeader.

Friday, June 17, 2011

Deploy Web Services

How To deploy web service?

There is nothing special in deploying web service. We can do the same way as we deploy any website. Just copy the Web Service folder inside inetpub and make it virtual directory. Now you can access this web service from any where. If you don't want to give source code you can publish it as well as we do for Website.

We can call this web service using http://ip address/WebSite1/Service.asmx

How to Access web service?
Right click on solution explorer


Click on Add Web Reference a window will open as below



Paste the URL(sample : http://ip address/Website1/Service.asmx) in URL box.Afterwords click on Go button.


After this next window will open click on Add Reference button. And you have finished. Your web service success fully added in your project now you can use it.

like:
private void button1_Click(object sender, EventArgs e)
{
localhost.Service objWebSrv = new localhost.Service();
MessageBox.Show(objWebSrv.HelloWorld());
}

Friday, June 10, 2011

Count 45 minutes with the help of two candles

1) You have two candles , one candle take one hour to burn fully you cave to count 45 minutes. How will you do that?

Answer: Better is that think a bit and if still you didn't find any answer than see below.

..
..
..
..
..
..
..
..
..
..
..
..

Burn the one candle from both side and burn the second candle from only one side. This will take only half an hour to burn the one candle fully. Since One candle takes one hour to burn fully.

In this way you have counted half an hour.Now burn the remaining second half candle from both end this will take 15 minutes.

This way you have counted 45 Minutes.

Friday, June 3, 2011

Difference between Dataset and Datareader

1) Datareader is forward and read only record set while dataset is both(backward and forward) and editable.

2) Datareader process one row at a time and discard the row if it is already accessed so it is extremely fast in comparison of dataset. And required very less network in comparison of dataset.

3) Datareader is connected and dataset is disconnected architecture.

4) In Datareader you can not get the total number of records using one direct function.

5) In case of large database datareader is best choice in comparison of dataset. Means if you have 2 million row in a table than dataset will not work with it you should use datareader here.

6) If you need result in form of xml than in that case also you can use ExecuteXmlReader rather than using dataset which is extremely slow.

7) We can not fetch the data Randomly with datareader since it is read only and did not store data.

8) Dataset can contain more than one table while datareader can contain only one table.

9) Dataset is just like small database it maintain relationship inside. It is too heavy.It requires a lot of memory space.If data is huge dataset affect the performance of application drastically.

10) To improve the performance of dataset never use command builder to generate the sql statement.

11) Dataset is well suited to communicate remotely as it is disconnected and changes
can be updated whenever it is required.

12) Dataset supports integration with XML whereas Datareader doesn't support.

13) For dataset we use data Adopter for datareader we use Command object.

14) The DataReader has a property named HasRows that return true false based on whether any row exist there in datareader or not. This can be used before Read method.

15) For dataset you have to include System.Data and for datareader you have to include System.Data.SqlClient.

16) Dataset and datareader both can be use with ASP .Net GridView the only difference is datareader does not support paging, you have to write down the code for that. But still datareader is fast than dataset.

17) The DataSet can read and load itself from an XML document as well as export its row set to an XML document. Because the DataSet can be represented in XML, it can be easily transported across processes, over network, or even the Internet via HTTP.

18) Dataset can be serialized while datareader can not thus cannot be passed between physical-tier boundaries where only string (XML) data can go.

19) When you need to do the operation delete,update,insert dataset is best choice.Although Datareader can be use to update the row with the help of separate sql DataAdapter.But it is not as easy as in dataset.

20) When we need operation searching, sorting and filtering dataset is best choice as it can be traverse in any direction.

21) If we have to bound the single server control datareader is best choice if we have to bound more than one control (suppose three) with the same query than dataset is better in case of datareader same query will hit the database three times.

22) Datareader can not be created, filled or traversed with out connection while in other hand dataset can be created manually without a connection to data source.

Friday, May 27, 2011

Interview Questions H.. 12

1)Write a query to get the fifth higest salary froma table.
Ans. Select min(custkey) from (Select top 5 * from Customers order by custkey desc) as topfive

2) Difference between Class and object.
Ans. Class is a collection of functions and data(variables) while object is away to access those functions and variable.

3) What are the different properties of OOPS?
1) Encapsulation 2) Inheritance 3) Polymorphism 4) Abstraction

4) Trigger on Log on
Ans. Yes we can create Log On Trigger in SQL 2005. It will fire whenever any one will login. But there some problem I have notice it is doing multiple entries for one login, 3 for me.

5) Trigger on ddl.
Ans. Yes we can create Trigger on DDL in SQL 2005.

6) Which one is saved in memory object or class?
Ans. Please let me know if you find the answer.

7) What is serialization? And why we use it?
Ans. To save the state of object in a form that can be save in memory or transfer through wire.It is called serialization. We use this in games to save the intermediate state of game or any other place where is required.

8) What is Reflection?
Ans. Reflection is used to call an assembly or class functions dynamically. Or to access any other information from assembly.

9) What is Singleton Patter?
Ans. Single Pattern to strict the creation of object ( only one object). This can be achieved using private constructor. Singlton

10) What other design pattern you know?
Ans. 1) Iterator Pattern 2)Abstract Factory 3) Factory Pattern.4) Prototype Pattern
Patterns

11) C# is case sensitive ?
Ans. Yes

12) VB.Net is case sensitive ?
Ans. No

13) Join
Ans. Click here

14) Garbage Collection.
Ans. Click here for detailed explanation

15) Difference between hiding and overriding.
1) When you want a same name function in child class without overriding than you can hide the function. Hide function is completely new function for child there is no relation of this method to base class. Both methods signature can be different.
2)For Hiding we use new keyword while for overriding we use override keyword. Hiding is also applicable by default.
3)If you have assigned child class reference to base class variable it shows different behavior for hiding and overriding. In hiding it will call base class method while in case of overriding it will call child class method.

Friday, May 20, 2011

Interview Questions N- 11

1) Difference between Truncate and Delete.

2) Difference between obj1.equal(obj2) and obj1==obj2

3) Webservice is stateless or stateful?

4) How can we maintain state in webservice?

5) Difference between function and procedure

6) Difference between abstract and interface.

7) Can we declare public variables in interface?
Ans: No, access specifier not allowed in interface. Although only function are allowed in interface not variable.

8)What is virtual function?

9) Which type of VB.Net is equalent to Variant of VB?
Ans : Object

10) Which method is equalant to C# destructor in VB .Net?
Ans : Finalizers

11) Which type of exception a web service can throw?
Ans : Fault Exception

12) Range Validator Support which type?
Ans :
Currency
Date
Double
Integer
String


13) What will be the effect of ApplydefaultSort=true in a dataset?
Ans : If true, the DataView sets a sort order to ascend based on the primary key column of the underlying DataTable. If set to false, this property has no effect. The ApplyDefaultSort property is ignored if the DataView.Sort property isn’t a null reference or an empty string. ApplyDefaultSort also has no effect if the underlying DataTable doesn’t have a primary key defined.

14) Which method used for determine dataset changes?
Ans : HasChanges()

15) Integer datatype represent which one
a) Int32 b) Int64 c) Int16
Ans : Int32

16) How will you use switches in webservice?

17) How will you trace a page in web application?

18) How will you implement roll based security in ASP .Net

19) What is boxing?
a) Encapsulate a value into object
b) Encapsulate a copy of value into object

Ans : Boxing is the process of converting a value type to the type object

20) What is difference between Byval and ByRef.

21) What is scope identity?
Ans : Give the last identity used in a function or procedure.

22) Write a query to get highest salary from employee table.

Ans : Select Top 1 Salary from Employee.

23) What is dll hell problem?
Most beautiful answer of this question was : Ma'am I have searched a lot on google but did not find any answer.

And that guy was selected.

24) How will you get any value from resource file?
Ans :
ResourceManager.GetString or ResourceManager.GetStream, depending on the type of the resource
Ex

string resourceFile = file;

string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();

ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
// retrieve the value of the specified key
resourceValue = resourceManager.GetString(key);

Another way is using namespace

Namespace.Properties.Resources.FileName

Ex.
i.e.: TestProject1.Properties.Resources.MyXmlFile -> direct access to the File in the resources

25) When you deploy an ASP .Net application which files copy on production server?
Ans : Deploying an ASP.NET web application entails copying the ASP.NET-related files from the development environment to the production environment. The ASP.NET-related files include ASP.NET web page markup and code and client- and server-side support files. Client-side support files are those files referenced by your web pages and sent directly to the browser - images, CSS files and JavaScript files, for example. Server-side support files include those that are used to process a request on the server-side. This includes configuration files, web services, class files, Typed DataSets, and LINQ to SQL files, among others.

In general, all client-side support files should be copied from the development environment to the production environment, but what server-side support files get copied depends on whether you are explicitly compiling the server-side code into an assembly (a .dll file) or if you are having these assemblies auto-generated.

26) What is the type of web config file?
a) Dll b) Xml c) Resource
Ans : Xml

27) What is the use of @ when you use it before string value?
Ans: Used as escape character for backslash

28) Why we use Monitor object?
Ans : Monitor object are used to ensure that a block of code runs without interruption of other thread. This is a way of synchronization, code from other thread can not run until code written in synch block has finished.

29) Can we update ,delete or insert in a function?
Ans : Can write but such a function can not called will throw error.

30)Can we perform Select in function?
Ans : Yes

31) How can we overload methods in web service?
Ans: Using Message Name attribute

32) What is the use of MessageName, Duration in web service?
Ans : used for overloading

33) How can we override methods in web service?

Friday, May 13, 2011

Interview Questions NGR- 10

1) What is ManualReset event?
Ans : They are used to signal and non signal the waiting thread.


2) What is the use of dispose method?

3) What is connection pooling?

4) What is dipatcher?

5) Join Difference between eque join and self join?

6) Can we write return statement inside finally?
Ans : No

7) What is the use of background worker component?

8) What is Garbage Collection?

9) What us gen0, gen1, gen2?

10) Can we have destructor in C#?
Ans : Yes
11) All questions from Threading and Garbage Collection

12) If we have same method in two interfaces and we implement the same with them than how will you define that method in the class and how you will call that method?

13)If we written return statement in catch block will control go in finally ?
 Ans : yes

14) Where we use bubbling give me real scenario?
Ans : Gmail

Friday, May 6, 2011

Interview Questions Inoday - 9

1) What is job scheduling?

2) Why we use view state?

3) What is the difference between two textboxes if one has multiline true and other has false. And max length for both is 10?

4) Can we move view state tag from above to below of the page on Render event to help in SEO?

5) What is the difference between Arraylist and Arrays?

6) What is assembly?

7) What is dll?

Friday, April 29, 2011

Interview Questions IG - 8

1) What is Json?

2) Why we use Json?

3) Joins - Left Outer, Right Outer, Full Outer, Inner Join?

4) Why we use static method?

5) Give me real example where you use static method.

6) If we have a table in which thousands of record inserting,deleting and updating daily. Which tyhpe of index you will use there.

7)Any critical job/work that you have done so far?

8) Difference between clustered and non clustered index.

9) What is identity?

10) What is scope identity?

11) Is it make sense that we define clustered index on primary key column.
Ans : No, not required already clustered index created on primary key

12) Can we define clustered index on composite column?
Ans : yes

Friday, April 22, 2011

Interview Questions MMT -7

1) Difference between WebFarm and WebGarden.

2) Session is best in WebGarden Scenario?

2) Three differences between PrimaryKey and UniqueKey.

Answer. 1. Primary key is only one in table while unique key can be multiple
2. unique key can be null
3. cluster index create on primary key while non cluster index can be created on non cluster index.

3)What is Currency Control?

4) Where we use Currency Control?
a) Forms b) Control c) Both d) None

5)What is the use of Server.Execute?

6) Default in web.config file.
Answer : Anonymous access

7)Do we need to stop IIS before installing new version of an assembly?

8)Which file is used to define Resource Info ?
a) Web.config b) Global.asax c) Both d) None

9)If you want to get Forms Collection what will you use?
a) Response.Redirec b) Server.Transfer c) Server.Execute d) None e) All

10)Thread is a
a) Event b) Object c) Instance Method d) Static Method

11)Which can not be new?
a) DataReader b)DataTable c) DataRow d) DataColumn

12)How will you bind a text box with dataview?
a) Text1.Databinding(dv,"EmpNo")
b) Text1.Databinding(dv)
c) Text1.Databinding("EmpNo")
d) None

13)Which is wrong?
a) You can find data in dataview if dataview is sort only.
b) Dataview is a subset of rows and columns.
c) None
d) Both

14) ConnectionPool access in case of
a) Connection Close b) Connection Dispose c) Connection Life time expired d) All

15) Pessimistic lock used when
a) High Contention
b) Lock cost is low than Rollback
c) Lock cost is high than Rollback
d) All
e) None

16)Session objects are accessible in?

a) web forms b) 2. web Garden c) both d) none

Answer. web forms – check once

17) Application objects are accessible in?

a) web forms b) Web Garden c) both d) none

Answer. a. web forms

18)Which control have the paging?

a) dataset b) datareader c) None d) All
Answer. dataset

19)Which file contains the configuration settings for URI to access in web services?
Answer. .disco (check it once)

20) I have a datagrid/Gridview can i have a dropdown inside a column and binding to different dataset?
Answer : Yes, using template field

21) How will you fill a dropdown from another dataset and grid from another dataset.
Answer: Fill the grid first than on RowDatabound event find the combo control and bind it with another dataset.

22) How will you add increasing number (index numbers of rows) in datagrid without bringing it from database.

Answer : using rowdatabound

23) Suppose there is two button in a datagrid column. how will you identify which button is clicked?
Answer : using command name and command argument

24) How many nulls unique key can have?
Answer : Only one

25) Can we define unique key on combination of keys?
Answer : yes

Friday, April 15, 2011

eval in javascript

1) eval is used to evaluate the expression.
Example:

var iValue =10;
document.write(eval(iValue+10));
eval("iFirst=10;iSecond=20;document.write(iFirst*iSecond)");

Output:
20
200

2) eval used to reduce the number of lines.

Suppose you are doing some validation part.
Without eval

if (document.myForm.Name.value.length==0)
{
alert("Name requires a value");
}

if (document.myForm.Salary.value.length==0)
{
alert("Salary requires a value");
}

Using eval

var fieldList = new Array('Name','Salary');
var tempObj;

for (count=0;count<fieldList.length;count++)
{
tempObj=EVAL("document.myForm." + fieldList[i]);
if (tempObj.value.length==0)
{
alert(fieldList[i] + " requires a value");
}
}

3) eval can be used to generate dynamic variable.

eval("iValue" + iIndex);
Same way we can use window["iValue"+ iIndex]

Friday, April 8, 2011

Interview Questions -- RG-6

1) What about security in web services?
Never Implemented

2) How will you overload methods in web services?

3) What is the use of eval function?

4) What is XMLHTTP Object?

5) If you have two xml with same structure and we have to create single with distinct daata. How will you do that?

6) If there are duplicate rows in data table how will you get distinct row in ADO .Net and SQL server.

7) Have you used SQL Profiler?

8) Static vairables in C#?

9) Difference between Dispose and Finalizer/

10)What is clustered index?

11) What will you do improve the perfonace ofa page?

12) What is difference between dataset and DataReader.

13) If you have two millions rows in database than whihc one you will use dataset or datareader?

14) What is the use of yield keword?

15) What is dispathcer?

16) Which interface do you use in Remoting?

17) How will you use SOAP Header in Web Services?

Wednesday, April 6, 2011

Ranking Functions in SQL Server

In Oracle we had rownum function which was used to assign a number for each row. Same way, SQL Server 2005 introduce four Ranking functions to assign a number to each row. Each function has unique features. Let’s discus in detail.

Ranking functions allow you sequentially number your result set. There are four Ranking function.

1) Row_Number() :- Returns the Sequential number for each row in increasing order start from 1.

Syntax : Row_Number() over(partition_clause|order_by_clause)

Suppose you have table named Employee
Table 1
Name                Age              Sex
Asim                20                M
Amir                20                M
Anas                24                M
Shabnam             17                F
Shradha             19                F
Rachna              21                F

Use RowNumber() with order by clause.

Select ROW_NUMBER() over(order by Age) as RowNumber,Name,Age,Sex from Employee

Table 2
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
2                 Shradha        19            F
3                 Asim           20            M
4                 Amir           20            M
5                 Rachna         21            F
6                 Anas           24            M


If you don’t want to sort the table but want the data with RowNumber you can use Select 1 statement as Row_Number required order by clause

Select ROW_NUMBER() over(order by (Select 1)),Name,Age,Sex from Employee

Table 3
RowNumber          Name          Age         Sex
1                  Asim          20           M
2                  Amir          20           M
3                  Anas          24           M
4                  Shabnam       17           F
5                  Shradha       19           F
6                  Rachna        21           F


-- Use Row Number with partition by clause
Select ROW_NUMBER() over(partition by Sex order by age),Name,Age,Sex from Employee

Table 4
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
2                 Shradha        19            F
3                 Rachna         21            F
1                 Asim           20            M
2                 Amir           20            M
3                 Anas           24            M

--You can not use Row_Number without order by clause
Select ROW_NUMBER() over(),Name,Age,Sex from Employee

Msg 4112, Level 15, State 1, Line 1
The ranking function "ROW_NUMBER" must have an ORDER BY clause.

May be you have noticed one thing in above tables Amir and Asim have same age but have different row number. If you want the same sequence number for rows that have same value than you have to use rank function for this. But it leave a gap between sequence number.
For an example we have same value for Amir and Asim 20,20. Sequence number for Asim and Amir is 3 but sequence number for Rachna is 5. (4 is missing here you can say draw back or advantage of rank function according to your requirement).

-- Use rank() with order by caluse
Select rank() over(order by Age) as RowNumber,Name,Age,Sex from Employee

Table 5
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
2                 Shradha        19            F
3                 Asim           20            M
3                 Amir           20            M
5                 Rachna         21            F
6                 Anas           24            M


There is no use of Select 1 statement with rank function as it will give you 1 for all row in the table.

Select rank() over(order by (Select 1)),Name,Age,Sex from Employee

Table 6
RowNumber          Name          Age         Sex
1                  Asim          20           M
1                  Amir          20           M
1                  Anas          24           M
1                  Shabnam       17           F
1                  Shradha       19           F
1                  Rachna        21           F

partition clause also can use with rank function also output will be same as for RowNumber except one thing. All rows having same value will assign same number.

-- Use rank() with partition by clause
Select rank() over(partition by Sex order by age),Name,Age,Sex from Employee

Table 7
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
2                 Shradha        19            F
3                 Rachna         21            F
1                 Asim           20            M
1                 Amir           20            M
3                 Anas           24            M

order by clause is must for rank function also.

If you will see the above tables(for rank), you will notice a gap between numbers. In table 5 Rachna has sequence number 5 which should be 4. for this you can use dense_rank(). It same as rank but it did not leave the gap.

-- Use dense_rank() with order by clause
Select dense_rank() over(order by Age) as RowNumber,Name,Age,Sex from Employee.

Table 8
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
2                 Shradha        19            F
3                 Asim           20            M
3                 Amir           20            M
4                 Rachna         21            F
5                 Anas           24            M

all others would change as well.

Have you missed one thing so far, yes grouping with sequence number. SQL server provide a function name NTILE(TOTAL_GROUP_NUMBER). NTILE function divide the table in groups as many you have given in braces(TOTAL_GROUP_NUMBER). And than assign the same number for each member of the same group.

Let’s see the example for detail. Suppose you want to divide the given table in 3 groups than the query will be.

-- Use NTILE(3) with order by caluse
Select NTILE(3) over(order by Age) as RowNumber,Name,Age,Sex from Employee

Table 9
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
1                 Shradha        19            F
2                 Asim           20            M
2                 Amir           20            M
3                 Rachna         21            F
4                 Anas           24            M



NTILE first divide the Total Rows by Total Group Number. And calculate how many rows should be come in one group.

Here group number is 3 and Total Rows are 6 So there will be 6/3 =2 rows in each group.

NTILE start making group from start and assign the same number for each row of the group. In above example Shabnam and Shardha are in the same group it has assign the same number that is 1 (starting number), Asim and an Amir are in the second group and have the same sequence number that 2. , Rachna and Anas are in the third group number that is 3.

It makes the group on the basis of FCS.

You will give Group number 6 than output will be different. In this case Total Rows in each groups is 6/6=1.

Table 10
RowNumber          Name          Age          Sex
1                 Shabnam        17            F
2                 Shradha        19            F
3                 Asim           20            M
4                 Amir           20            M
5                 Rachna         21            F
6                 Anas           24            M

Total group number may less ,equal or greater than total number of rows in table.


Other queries can be checked as well

-- If you don't want to sort the table but want the data with NTILE(3) you can use Select 1 statement as rank required order by clause
Select NTILE(3) over(order by (Select 1)),Name,Age,Sex from Employee

-- Use NTILE(3) with partition by clause
Select NTILE(2) over(partition by Sex order by age),Name,Age,Sex from Employee

You can download the complete script : Rankning Functions

Friday, April 1, 2011

Master Page Life Cycle

Page Life Cycle with Master Page

When we use Master Page in our application than it affects the Life Cycle of the page. There are two types of event one is for controls of the page and second one is for page itself. Controls event always fired before Page event except two exceptions cases Load and PreRender. These two events fired before controls corresponding event. Same is true for Content and Master, Master Page event fired before Content's event except these two cases.


1) Master Controls Init
2) Content Controls Init

3) Master Page Init
4) Content Page Init

5) Content Page Load
6) Master Page Load

7) Master Controls Load
8) Content Controls Load

9) Content Page PreRender
10) Master Page PreRender

11) Master Control PreRender
12) Content Control PreRender

13) Master Controls Unload
14) Content Controls Unload

15) Master Page Unload
16) Content Page Unload

Friday, March 25, 2011

Row State And Row Version

Row State
When we modify any row data that row status has been changed according to action. When we call AcceptChanges() method of dataset or Table, status of all rows changed to Unchanged.
And deleted rows has been removed from the dataset. But when we call RejectChanges all Added rows has been deleted and deleted rows recovered and status of all rows set to Unchanged.
When we use Fill method to fill the dataset than all row’s status will be Unchanged initially until unless any change has been done.

Row State Description
Unchanged It means there is no change in row’s data.
Added It means row has been added in dataset.
Modified Row has been updated.
Deleted Row has been deleted from table.
Detached It means row is not attached with dataset. Means you have just created the row but not added in dataset by calling Add method yet. If row has been removed from dataset or deleted it’s row status will be detached.

Row Version
A data row object contains multiple value based on the version of row. If we pass version value in data row we can get the data row value for that version.

DataRow objEmpDataRow = objDtEmp.Rows[0];
string objEmpDataRow = objEmpDataRow["EmpID", DataRowVersion.Original].ToString();


Version can be categorized following way.

Current With the help of this you can get the current value of the row.
If row state is Deleted you can not get value for this version.
Default Default row version depends upon Row Status, If Row Status is Added,Modified or Unchanged, the default version value will be equivalent to Current. For Deleted it is equivalent to Original. For Detached it is equivalent to Proposed.
Original This gives you original values of the row. This is not exist if Row State is Added.
Proposed This gives proposed value of the row. This exist Only if Row Status is detached.

Friday, March 18, 2011

Non Clustered Index

In non clustered index leaf node contains the row pointer instead of row itself. If a clustered index is defined on table than leaf node contains the clustered index value rather than row pointer. So physical order of table does not change.Non clustered index can be defined on a table or view with a clustered index or heap. A table can have maximum 249 non clustered index.

The row pointer is a combination of file identifier, page number and number of the rows in page, this row pointer is also called ROW ID.

When we have to use non clustered index?

1) Column which contains mostly the distinct values. If there are very few distinct values(less than 95%) suppose 1 or 0 than query will not use index since table scan will be more efficient.
2) Columns that are frequently used in search that return exact result.
3) Columns that are frequently used in join and grouping
4) Used for queries that return few rows.
5) Queries that return small range of data. Clustered index perform better for large range of data.
6) Queries that contain both clause where and order by.
7) Try to create index on integer column rather than character column, since it takes less space.

How non clustered index affect the table
1) Does not change the physical order of table.
2) Non clustered index is similar to the back index of the book.

Friday, March 11, 2011

Clustered Index

What it does basically create a copy of table and sort it according to the specified column and delete the original table. So it help in searching and sorting the data against that column.
A table can have only one clustered index. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index.

If there is a primary key in table without specification of non clustered index and no clustered index exist on table than a clustered index automatically created on table.If no clustered index defined a table is called heap.


On which column we have to use Clustered Index? When we have to use clustered index?
1) The column which is used in search too frequently specifically in range search like date.
2) No need to create on Primary key it is automatically created for Primary Key if there is no other index created on any other column.You can override the default behavior of primary key by creating index on any other column, if you think it will improve performance.
3) Never create a cluster index on column which frequently updated since in case of clustered index it have to update the row in index table.
4) Create clustered index on a column which is used frequently for sorting the table.
5) Clustered index can be created on multiple column[Composite].
5) It is a good practice to create clustered index on each table.
6) Create a clustered index on a column which has sorted data somewhat.
7) Create a clustered index on a column which has minimal duplicate values.
6) Create a clustered index On a foreign key column.
7) Avoid creating a clustered index based on incrementing(Identity) column. When inserting and updating many rows at once it can create problem. As we know SQL Server automatically create a clustered index on primary key so explicitly specify non clustered key word to indicate that a primary key will use non clustered index.

Clustered index affect the table following way :

1) Reorder the data each time when you fired a query(Update,Delete)
2) Reorder the table according to clustered column.
3) Insert will be slow since the row will be inserted into right place.
4) If there are too many indexs(non clustered) than it affect(slow) the performance.
5) Every time the clustered index key is updated, SQL Server must maintain not just the clustered index but also the non-clustered indexes since non-clustered indexes contain a pointer to the clustered index instead of row pointer. This is yet another reason why you shouldn't create the clustered index on multiple columns.
6) Create a clustered index for each table, a table without clustered index is heap and data will not be sorted in any order and all row will be added at the end of table that can create the problem so better is that create a clustered index for each table if there is no index(by default) means no primary key.
7) If you are creating a clustered index on composite column suppose Name and Age. Than order of the column is very important here only queries that have Name(left most)in where clause will use the index.

Restrictions:
1) When creating an index using create statement you need to specify clustered by default it creates non clustered index.
2) Only owner of the table can create index.
3) Create Clustered index first than non clustered. Since if you will create clustered index after non clustered index it will update the non clustered index to replace row identifier with clustered index value.

Friday, March 4, 2011

Interview Questions TFT -- 5

1) If you have two div and you want to display them left-right than what css style you will use?

Answer: There is a float property which has three possible values : none,left and right, you can use that property to flow the content according to your requirement.By default it is none means your content will flow as it is given.

<div style="background:green;border:1;width:10;height:10;float:left" >
Hello
</div>
<div style="background:yellow;border:1;width:10;height:10">
How are you?
</div>

2) What is the use of dot(.) and Hash(#) in CSS?
We use dot(.) to specify the class and Hash(#) for id. If we define an item with dot(.) in CSS than that style will apply to all elements with the same class. Same for id.

3) If you have two elements with the same id, which one you will get while using getElementById().
Very First One( It will check the physical order of elements, float property will not affect this function).

4) What is the difference between getElementById() and getElemntsByName()
getElementById return single element while getElementsByName return array of elements.

5)What do you do make working like a group of radio buttons?
They should have same name to work like a group.

6) Where we use Having clause?
Having clause used with group by and aggregate functions.
Ex. Select Department from Inno Having avg(Salary)>100000 group by Department

7) Difference Between Clustered Index and Non Clustered Index? Can we have more than one clustered index on a table if not than why?
See Link :- http://interview-preparation-for-you.blogspot.com/2010/11/interview-questions.html

8) What is the difference between lib and binding?
Still Searching....

9) Give me some example of Dynamic polymorphism.
I know only one that is virtual function.

10) Give me some example of call back functions in JQuery.
success function and error function

11) Write a program to print 1-100. All the numbers that are divisible by 3 and 5 should print in word and all other numbers should print in integer.
I know you can write it easily :)

12) You have an array of string. You write a program to get the index of that item which has maximum length.
This is a simple program but you have to write very carefully there should not be any loop holes basically he is checking your coding standard not only logic.

13) Is there any other method to prevent page refresh instead of Update Panel?
Through JQuery you can do it.

14) If you are saving a value using ajax function of JQuery and connection has been break in the middle than how you will handle this situation?
You can attach error call back function to ajax, it will return time out in case of connection break or any other case in which server does not send response.

15) Give me an example of iterator pattern?
See Link :- Iterator Pattern

16) What is the difference between Hashtable and Dictionary?
Dictionary is generic Hashtable is not.When retrieving the values from hashtable you need to typecast them into appropriate type while in case of dictionary there is no need to type cast.

17) What is entity framework?
Don't know.

18)Have you worked in WCF?
NO

19)How will you host webservices?
We can do it just like a web site. by deploying at this path C:\Inetpub\wwwroot. And make it virtual directory from inetmgr.

20) Difference between capturing and bubbling.
See :http://interview-preparation-for-you.blogspot.com/2010/08/bubble-event.html

21) How will you attach error call back function in ajax call?
Don't know

Friday, February 25, 2011

Identity and scope Identity

Scope_Identity()
This function returns Last generated Id in the same scope. A scope may be store Procedure,Trigger,Function or Batch.

IDENT_CURRENT('table_name')
Returns the last identity value generated for a specified table or view. The last identity value generated can be for any scope.

@@IDENTITY
@@IDENTITY is a global variable. And returns the last identity value generated for any table across all scopes.

We have two tables Employee1 and Employee2

Employee1 Structure
Id int Not NULL IDENTITY(1,1),
Name varchar(100) NULL,
Salary int


Employee2 Structure
Id int Not NULL IDENTITY(1,1),
Name varchar(100) NULL

You can create the duplicate copy of Employee1 as

Select * into Employee2 from Employee1

And a procedure is used to insert values in first table.

Crate Procedure sp_InsertEmp(@Name varchar(50),@Salary int)
as
Begin
insert into Employee(Name,Salary) values(@Name,@Salary)
Select @@Identity
End

And a trigger is used to insert values in second table.

Create Trigger InsertInEmplyee2 On Employee1 For Insert
As
Begin
Declare @Name varchar(100),
Select @Name = [Name] from Inserted
Insert into Employee2(Name) values (@Name).
End

Here you can not use Identity it will give you last generated Id that will be the Id of Employee2. Bu here we want last generated Id of Employee1. So in this scenario we can use Scope_Identity() or Ident_Current(‘Employee1’). If you are using two tables in the same procedure and you want id generated by a specific table than better is use Ident_Current(‘Table_Name’) instead of Scope_Identity().

When you create an Identity column there are two parameters First is seed and second one is Increment.

Ex. Id int IDENTITY(1,2).. It will start from 1 and per row 2 will be increment number.

You can download the sample sp and trigger :- http://www.box.net/shared/ydez5c49jx

Friday, February 18, 2011

Start with Selector JQuery

Today I have stuck in a problem where I have to select an item start with a specific character in a select box. I found the quiet short and interesting solution for this problem. I want to share this experience with you people.

There is a start with selector in jquery in this you can find out the item start with a specific character or string.

Start with Selector :- We use ^[Power sign] for this in jquery

Suppose you want item start with character C.You can find the value of that item like :

var Char='C';
var sValue = $("#SelectBoxId option[text^='"+ Char + "']").val();


Now select that specific item

$("#SelectBoxId option[value='"+ sValue + "']").attr("selected","selected");

I have found some more selector that may be useful for you.

End with Selector :- Use $ for end with selector

Suppose you have to find out the item which end with a specific character

var ='C';
var sValue = $("#SelectBoxId option[text$='"+ Char + "']").val();

Contains with selector :- Use * for contains with selector

Suppose you have to find out the item which contains a specific string like "rose".

var sValue = $("#SelectBoxId option[text*='rose']").val();

Friday, February 11, 2011

Handlers

Whenever Client do the request to the Server it always goes through the Modules and HttpHandlers.After the Handler it again pass through the modules. A request can go through multiple Modules at a time but pass through only one handler at a time.

If you want to modify request in the middle than you can use HTTP Handlers for that.

To service incoming Http requests Asp.Net use Http Handlers. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.

Any class that implements the IHttpHandler interface can act as a target for the incoming HTTP requests. HTTP handlers are somewhat similar to ISAPI extensions. One similarity between HTTP handlers and ISAPI extensions is that HTTP handlers can be called directly by using their file name in the URL, similar to ISAPI extensions.

The following are the methods in IHttpHandler interface

ProcessRequest : Used to call Http Requests.
IsReusable : To check the re-usability of same instance handler with a new request of same type.

We can use <httpHandlers> tag for adding HTTP handlers to our Web applications like..

<httpHandlers>
<add verb="supported http verbs" path="path" type="namespace.classname, assemblyname" />
<httpHandlers>

Attributes

verb = The verb attribute defines allowed HTTP request methods for this handler.If the handler supports all of the HTTP verbs, simply use "*", otherwise list the supported verbs in a comma separated list. So if your handler supports only HTTP GET and POST, then verb attribute will be "GET,POST". Possible values are head, get, post etc*.

path = The path attribute specifies the path or wild card specification of the files for which this handler will be invoked. For example, if you want your handler to be called only when test.xyz file is requested, then the path attribute will contain "test.xyz"; similarly if you want your handler called for any file having .xyz extension, the path attribute will contain "*.xyz".

type =The type attribute specifies the actual type of the handler or handler factory in the form of a combination of namespace, class name and assembly name. ASP.NET runtime first searches the assembly DLL in the application's bin directory and then searches in the Global Assembly Cache (GAC). In type you can give your Handler name also if you have added it through ASP .Net new Items.

The <add> directives are processed in a top-down sequential order. If two or more <add> sub elements specify the same verb/path combination, the final <add> overrides all others.

When we use HttpHanlers?

If your ASP.NET or Sharepoint web application is storing binary data (images, PDF’s) in a database, And you want to pick those images and display to user as if it were normal files on the server (www.example.com/name1.jpg). A clever way to do that is using the IHttpHandler interface.

Even ASP.Net itself use Handlers for its internal processing. You can see in the Machine.config file
<httpHandlers>
<add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler"/>

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>

<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory"/>

<add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler"/>

<add verb="GET,HEAD" path="*" type="System.Web.StaticFileHandler"/>

. . . . . .
. . . . . .
</httpHandlers>

Friday, February 4, 2011

Move a Window

You can move a window at any place. All you have to do get the handle of that window which you want to move. There are two API functions that can be used to move a window.

To get the handle of the window.

[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName);

There are two parameter
lpClassName :- Name of the process.
lpWindowName :- Title of the Window

In case of a blank notepad window which has a title Untitle parameres

For example for a new unsaved notepad window

lpClassName :- Notepad
lpWindowName :- Untitle

To move the the window.

[DllImport("User32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool MoveWindow(IntPtr hWnd, int xPos, int yPos, int Width, int Height, bool repaint);

Parameters Detail.
hWnd :- Handle of the window
xPos :- xPosition where you have to move
yPos :- yPosition where you have to move
Width :- Width of the Window
Height :- Height of the window
repaint :- Do you want to repaint the window.

Friday, January 28, 2011

Difference Between Truncate and Delete

Truncate and Delete both are used for deletion of data.But there are so many difference in between both.

1)TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server. While DELETE is a DML command and can be rolled back. Memory not released to server. After delete memory used by table will be same as before. But in Sql Server 2005 you can roll back Truncate also by using Transaction and even Delete command can not be roll back without Transaction.

2)Where clause can not be used in truncate while in delete you can.

3)A DDL it actually sets the high water mark level of the table back to zero (depends on MINEXTENTS too) hence no one can read the table records.The commend get itself issues a commit as it is DDL command hence can not be rolled back

4) In case of TRUNCATE ,Trigger doesn't get fired.But in DML commands like DELETE .Trigger get fired. But in Sql Server 2005 you can write Trigger for DDL also.

5) Do not Check Constraints.While Delete check.

When there is foreign key constraint even though there
is no data in child table Truncate cannot be done. only
when the constraint is dropped truncate can be executed.

Whereas though we have foreign key constraints if the child
table is deleted, then parent table can be deleted.

6) TRUNCATE resets the Identity counter if there is any identity column present in the table where delete not resets the identity counter.

7) Delete and Truncate both are logged operation.But DELETE is a logged operation on a per row basis and TRUNCATE logs the deallocation of the data pages in which the data exists. That’s Truncate is faster than delete.

Drop is similar to truncate only one difference is in case of drop table structure deleted too.


Ex.Below Example is true only for Oracle in SQL Server delete reduces the number of rows also.

Delete
SQL> SELECT COUNT(*) FROM emp;

COUNT(*)
----------
14

SQL> DELETE FROM emp WHERE job = 'CLERK';

4 rows deleted.

SQL> COMMIT;

Commit complete.

SQL> SELECT COUNT(*) FROM emp;

COUNT(*)
----------
10

Truncate

SQL> TRUNCATE TABLE emp;

Table truncated.

SQL> SELECT COUNT(*) FROM emp;

COUNT(*)
----------
0

Drop
SQL> DROP TABLE emp;

Table dropped.

SQL> SELECT * FROM emp;
SELECT * FROM emp
*
ERROR at line 1:
ORA-00942: table or view does not exist

Friday, January 21, 2011

Difference Between Get and Post

get and post are HTTP methods that are used to send request to the server.Difference of them are listed below.

Get() transfer only 256 char. While there is no limit for post.

Get is not Secure information appear in browser, Post is secure.And information does not appear in the browser

As the data transfers through address bar (URL) there are some restrictions in using space, some characters like ampersand (&) etc in the GET method of posting data. We have to take special care for encoding data if such special characters are present. While in post there is no restriction.

If get method is used and if the page is refreshed it would not prompt before the request is submitted again. while in case of post it will prompt to user.

One can store the name value pairs as bookmark and directly be used while sharing with others - example search results.While in Post method bookmark can not be save.

It is a single call system While Post is a two call system.

Data transmission is faster in get while in post data transmission is slow.

In get data is always submitted in the form of text in get method. In Post data is submitted in the form as specified in encrypt attribute of form tag and thus files can be used in FileUpload input box.

If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.

In ASP .Net Response.Redirect use get method while using Server.Transfer use post method.

Friday, January 14, 2011

Http Methods

HTTP offers a number of methods that can be used to perform actions on the web server. These HTTP methods can be used for various purposes.
Http Methods are.

* HEAD
* GET
* POST
* PUT
* DELETE
* TRACE
* OPTIONS
* CONNECT

* GET :- The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

* HEAD :- The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

* POST :- The POST method is used to request that the origin server accepts the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

* DELETE :- This method allows a client to delete a file on the web server.

* PUT :- This method allows a client to upload new files on the web server.

* CONNECT :- This method could allow a client to use the web server as a proxy.

* TRACE :- This method simply echoes back to the client whatever string has been sent to the server, and is used mainly for debugging purposes. This method, originally assumed harmless, can be used to mount an attack known as Cross Site Tracing, which has been discovered by Jeremiah Grossman.

* OPTIONS :- The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

Some methods are really harmful for a web application, as they allow an attacker to modify the files stored on the web server and, in some scenarios, steal the credentials of legitimate users. More specifically, the methods that should be disabled are the following:

put,delete,connect


Friday, January 7, 2011

WebMethod Properties

WebMethod is an attribute that is used in Web Service to inform the CLR that particular method will expose as a part of Xml Webservice. WebMethod attribute has some properties which can be sued to control the behavior of the WebMethod.

BufferResponse :- By default it’s value is true. If it true, Response of webmethod serialized and stored in a buffer. When buffer is full or response completed than it sends the data to the client. Thus minimize communication between the worker process and IIS (Internet Information Services) process. If it is false, ASP.NET buffers the responses in chunks of 16 KB while communicating to the client.In case of large file make it false.
Ex:- Suppose we have requested 64 KB file from web service. If BufferResponse is true and Method generating 8 KB data in one go. Than Webserive will not send this 8 KB data to host but Buffer this 8 KB data until unless buffer is full or whole file is completed. And if BufferResponse is false than Webservice buffer this 8 KB data and wait for second call after the second call when data is 16 KB than it sends it to the host.

Cache Duration :- When we call a web method. Web Service cache the response of each unique set of parameter for a time span. This time span is set by Cache Duration property.By default value is zero which means no caching.

Description :- You specify what a web method will do. This will appear on the service help page.Default value is empty string.

Enable Session :- If you want to use Session in Web Service you have to set this property as true. By default value is false. You can use session in web service through HttpContext.Current.Session or with the WebService.Session property if it inherits from the WebService base class.

MessageName :- If you want to overload a WebMethod than you can use this property to uniquely identified a WebMethod. By default value is method name.

Followers

Link