Monday, November 22, 2010

Multiple Rows to column.

create table #Test (
ProdID varchar(5),
ProdDesc varchar(256)
)

insert into #Test (
ProdID,
ProdDesc
)
select 'Prod1', 'Description 1' union all
select 'Prod1', 'Description 2' union all
select 'Prod2', 'Description 1' union all
select 'Prod3', 'Description 1' union all
select 'Prod3', 'Description 2' union all
select 'Prod3', 'Description 3' union all
select 'Prod3', 'Description 4'


select distinct
a.ProdID,
stuff((select
',' + b.ProdDesc
from
#Test b
where
b.ProdID = a.ProdID
for xml path('')),1,1,'') as ProdDesc
from
#Test a

Thursday, October 28, 2010

Autocomplete feature of textbox

write the below code in aspx page inside the javascript tag:

$(document).ready(function(){ $("#<%=fname.ClientID%>").autocomplete("TestHandler.ashx"); });

where fname is your textbox name .



In TestHandler.ashx write the below code:
using System;
using System.Web;
using System.Data;

public class TestHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string Dealercode = context.Request.QueryString["q"];
DataSet objds = new DataSet();
//get the dataset from your class.Here dataprocessor is a class having
//runspreturndataset method which will return the dataset.
objds = DataProcessor.RunSpReturnDataset("get_dealer_details", Dealercode);
string[] items = new string[objds.Tables[0].Rows.Count];
foreach (DataRow dr in objds.Tables[0].Rows)
{
//items.SetValue(dr["dealercode"].ToString(), Convert.ToInt32(dr["tmsw_dealer_id"].ToString()));
context.Response.Write(dr["dealer_code"].ToString().TrimEnd() +"-"+ dr["dealership_name"].ToString().Trim() + Environment.NewLine);
}


}

public bool IsReusable
{
get
{
return false;
}
}

}

Sort dropdown in ascending order.

private void SortDDL(ref DropDownList myddl)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();


foreach (ListItem li in myddl.Items)
{
textList.Add(li.Text);
}

textList.Sort();
textList.Reverse();


foreach (object item in textList)
{
string value = myddl.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
myddl.Items.Clear();

for (int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
myddl.Items.Add(objItem);
}
}

Saturday, May 1, 2010

Disable back button on browser



Call this in body tag of html :

onload="disableBackButton()"

IIS Isolation Levels?

Internet Information Server: IIS5 supports three isolation levels, that you can set from the Home Directory tab of the site Properties dialog:
* Low (IIS Process): ASP pages run in INetInfo.Exe the main IIS process, therefore they are executed in-process. The problem is that if ASP crashes, IIS crashes as well and must be restarted (IIS5 has a reliable restart feature that automatically restarts a server when a fatal error occurs).
* Medium (Pooled): In this case ASP runs in a different process, which makes this setting more reliable and if ASP crashes IIS will not crash. All the ASP applications at the Medium isolation level share the same process, so you can have a web site running with just two processes (IIS and ASP process). IIS5 is the first Internet Information Server version that supports this setting, which is also the default setting when you create an IIS5 application.
* High (Isolated): Each ASP application runs out-process in its own process space, therefore if an ASP application crashes, neither IIS nor any other ASP application will be affected. The downside is that you consume more memory and resources if the server hosts many ASP applications.

When selecting an isolation level for your ASP application keep in mind that out-process settings - that is, Medium and High - are less efficient than in-process (Low). However out-process communication has been vastly improved under IIS5 In practice, you shouldn't set the Low isolation level for an IIS5 application unless you really need to serve hundreds pages per second.

How you will handle session when deploying application in more than a server? Describe session handling in a webfarm, how does it work and what are th

By default, ASP.NET will store the session state in the same process that processes the request. ASP.NET can store session data in an external process which can even reside on another machine. To enable this feature:
* Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424.
* Set the mode attribute of the section to "StateServer".
* Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state.

How does an AppDomain get created?

AppDomains are usually created by hosts like Windows Shell, ASP.NET and IE etc.
When you run a .NET application from the command-line the host is the Shell. The Shell creates a new AppDomain for every application.

AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain creates an instance of an object inside it, and then
executes one of the object's methods.

using System;
using System.Runtime.Remoting;

public class AppDomainInfo : MarshalByRefObject

{
public string GetAppDomainInfo()

{
return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;
}
}

public class App
{

public static int Main()
{
AppDomain ad = AppDomain.CreateDomain( "My new domain", null, null );
ObjectHandle objh = ad.CreateInstance( "appdomaintest", "GetAppDomainInfo");
GetAppDomainInfo myInfo = (GetAppDomainInfo)(objh.Unwrap());
string info = myInfo.GetAppDomainInfo();
Console.WriteLine( "AppDomain : " + info );
return 0;
}
}

Wednesday, April 28, 2010

Thursday, April 1, 2010

Difference between OLEDB Provider and SqlClient ?

SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better performance), and it was written with lots of help from the SQL Server team.

What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling?

Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class.
Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached.
Following are important differences between object pooling and connection pooling:

* Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long.
* Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.)

COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced.

What is portable executable (PE)?

The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.

Friday, March 12, 2010

What are relation objects in dataset and how & where to use them?

In a DataSet that contains multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table.

The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.
custDataSet.Relations.Add("CustOrders",
custDataSet.Tables["Customers"].Columns["CustID"],
custDataSet.Tables["Orders"].Columns["CustID"]);

OR
private void CreateRelation()
{
DataColumn parentCol;
DataColumn childCol;
parentCol = custDataSet.Tables["Customers"].Columns["CustID"];
childCol = custDataSet.Tables["Orders"].Columns["CustID"];
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);
custDataSet.Relations.Add(relCustOrder);
}

What is serialization in .NET? What are the ways to control serialization?

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
* Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.
* XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.

Delete confirmation message in datagrid

Private Sub myGrid_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles myGrid.ItemDataBound

Select Case e.Item.ItemType Case ListItemType.Item, ListItemType.AlternatingItem
Dim deleteButton As LinkButton = CType(e.Item.Cells(3).Controls(0), LinkButton) deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete?');")
End Select

End Sub

Private Sub myGrid_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles myGrid.DeleteCommand
If e.CommandName = "Delete"
// 'delete from database commands
BindData()
End If
End Sub

Disable back button on browser

Write a javascript function:

function disableBackButton()
{
window.history.forward();
}

Call it on load of body in html.
i.e. onload="disableBackButton()"

String Manipulations

// Concatenation of the strings.
string start = "This is a ";
string end = "concatenated string";
string result= start + end;

// Inserting Strings into Strings
string first= "Please check this code.";
string second= "understand";
Console.WriteLine(first.Insert(24, second));

// Search and Replace
string sample = "The good programming.";
string result = sample.Replace("good", "excellent"));

// Copying Strings
string myString= "The ultimate programming code.";
string result = string.Copy(myString);

// Extracting Text from a String
string sample = "The quick start tutorial is a must.";
string result = sample.Substring(4); //result will be "quick start tutorial is a must."

//Trim Function
string myString= " String Manipulation " ;
string Result= Name.Trim(); //it will remove the starting and ending space of the string.

// Remove specified number of characters from string
string myString= "The String Manipulation";
string Result= MainString.Remove(1,4);

Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use?

Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention.
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced.

What are Satellite Assemblies?

Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version.

What Is The Difference Between ViewState and SessionState

View state is a client side state management whereas Session is used to manage state at server side.
Session variable can be accessible from all pages in web application. It is scoped to current browser session only.
ViewState persist the values of controls of particular page in the client (browser) when post back operation done. When user requests another page previous page data no longer available.
SessionState persist the data of particular user in the server. This data available till user close the browser or session time completes.

Saturday, February 27, 2010

What is the use of web.config? Difference between machine.config and Web.config?

ASP.NET configuration files are XML-based text files , each named web.config that can appear in any directory on an ASP.NET Web application server. Each web.config file applies configuration settings to the directory it is located in and to all virtual child directories beneath it. Settings in child directories can optionally override or modify settings specified in parent directories.Machine.config provides default configuration settings for the entire machine. ASP.NET configures IIS to prevent direct browser access to web.config files to ensure that their values cannot become public .
At run time ASP.NET uses these web.config configuration files to hierarchically compute a unique collection of settings for each incoming URL target request (these settings are calculated only once and then cached across subsequent requests; ASP.NET automatically watches for file changes and will invalidate the cache if any of the configuration files change).

Application and Session Events

The ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:
Application events are raised for all requests to an application. For example, Application_BeginRequest is raised when any Web Forms page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, Application_EndRequest, provides you with an opportunity to close or otherwise dispose of resources used for the request.
Session events are similar to application events (there is a Session_OnStart and a Session_OnEnd event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out.

You can create handlers for these types of events in the Global.asax file.

What is Private Constructor , it’s use. Can you create instance of a class which has Private Constructor?

When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or to directly create instances of it. (Except Nested classes)
Make a constructor private if:
*You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method.
*You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.

Thursday, February 25, 2010

What is the managed and unmanaged code in .net?

The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code. it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

Difference between DataReader and DataAdapter / DataSet and DataAdapter?

You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory.
After creating an instance of the Command object you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example.
SqlDataReader myReader = myCommand.ExecuteReader();
You use the Read method of the DataReader object to obtain a row from the results of the query.
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();

DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema.
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.

Saturday, February 20, 2010

Return value from a prompt dialog using Javascript

var choice;
choice= prompt("Choose a number between 1 and 5", "1, 2, 3,4 or 5")
switch (choice)
{
case "1":
alert("You typed in a 1");
break;
case "2":
alert("You typed in a 2");
break;
case "3":
alert("You typed in a 3");
break;
case "4":
alert("You typed in a 4");
break;
case "5":
alert("You typed in a 5");
break;
}

Caching

Caching is a technique widely used to increase performance of the application by keeping the frequently accessed web pages/data in memory.
There are three kinds of caching that can be used by Web applications:
* Output caching
* Fragment caching
* Data caching

Output Caching: increases request/response throughput by caching the content generated from dynamic pages. Every time a page is requested, the subsequent request for that particular page is satisfied by the cache.It is useful where you have static pages.
Syntax :<%@OutputCache Duration="60" VaryByParam="none" %>
@OuputCache is a page directive
Duration parameter specifies how long the HTML output of the Web page should be held in the cache. With the expiration of the duration the cache also become invalid and the ASP.NET Web page then gets generated dynamically, and the cache again gets created with this HTML.
The VaryByParam parameter can be used to cache different views of a dynamic page whose content is generated by GET or POST values.
This type of caching is also known as page level caching.

Fregment Caching: which is also known as partial page level caching allows to cache specific regions of page. Specific regions of your page can be cached with a user control and then @OutputCache directive can be used to cache.The content inside the User Control will be cached for the specified period while the ASP.NET Web page that contains the User Control will continue to serve as a dynamic content.

Data Caching: which is an in-memory cache used for caching objects.The cache is scoped to an application and its lifetime is equivalent to the lifetime of the application.

Caching gives an overall impact on performance of web application.

Wednesday, February 17, 2010

Microsoft Virtual Lab

Learn how to build great applications for Windows and the Web through a series of guided, hands-on labs which can be completed in 90 minutes or less. No need any installation and are available to you immediately for FREE. Start by selecting the lab you’re interested in .Check this url.

http://msdn2.microsoft.com/hi-in/virtuallabs/default(en-us).aspx

Monday, February 8, 2010

Reverse a string.

string str = "This is the string which we have to revert";
char[] step1 = str.ToCharArray();
Array.Reverse(step1);
Console.WriteLine("Original string:" + str);
Console.WriteLine("Reverse of a string:" + new string(step1));

Wednesday, January 27, 2010

Asp.net - How to find last error which occurred?


Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
{
ErrMessage = LastError.Message;
}
else
{
ErrMessage = "No Errors";
}

Response.Write("Last Error = " + ErrMessage);

Monday, January 25, 2010

What is the difference between CONST and READONLY?

A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor.
Therefore readonly fields can have different values depending on the constructor used.For eg.
readonly int a;
public class()
{
a=1;
}
public class(string s)
{
a=5;
}
public class(string s, int i)
{
a=i;
}
A const field is a compile-time constant meaning that it is evaluated at compile time, the readonly field can be used for runtime constants which means value gets evaluated during runtime.

Monday, January 4, 2010

using directive vs using statement :

Create an instance in a using statement to ensure that Dispose is called on the object when the using statement is exited. A using statement can be exited either when the end of the using statement is reached or if foreg an exception is thrown and control leaves the statement block before the end of the statement.

Using directive has two uses:
Create an alias for a namespace.
Permit the use of types in a namespace such that you do not have to qualify the use of a type in that namespace .