DotNet Academy of Rajesh Rolen

Solutions by Rajesh Rolen

Not able to open Server Explorer in VS2008

if you not able to open server Explorer in vs2008 you can perform below step to make it open:
Go to visual studio command prompt
run below command:
devenv /setup

and its done....

you can use "devenv /resetsettings" command to reset all settings of visual studio

Truncate Database/ Delete data from all tables of database

-- disable all constraints
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'

-- delete data in all tables
EXEC sp_MSForEachTable 'DELETE FROM ?'

-- enable all constraints
exec sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'

Adding or Removing values from Array using javascript

We can add or remove values from an array using splice() function.

the splice() function returns the removed element(s).
syntex: arrayName.splice(Startindex,HowManyElements,element1,.....,elementX)

eg.
< script type="text/javascript" >

var employes = ["Rolen", "Pankaj", "JS", "Bhupendra"];
document.write("Removed: " + employes.splice(2,1,"Pankaj") + "< br / >");
document.write(employes);

< /script >

Solution By: Rajesh Rolen

Disable Autocomplete in Textbox / form in asp.net

to disable auto complete in textbox you will have to set autocomplete="off" for textbox. this is not in its property so you will have to write it in aspx page by own.

or in code behind write : Textbox1.Attributes.Add("autocomplete", "off");

To turn off auto-complete for your entire form, all you need to do is add an attribute to your form tag, like this:

< form id="Form1" method="post" runat="server" autocomplete="off" >

Show Text Vertical in Crystal Reports in Asp.Net

sometimes we need to show our text or we can say header text in vertical. and we try using rotate property but it not works.. so to do so we have got a perfect solution to make browser fool.

we can do be using below steps:
1. take a label/text.
2. set your font size as required
3. now set make its height large and set width in such a manner so only one character can be displayed.
4. go to format font->spacing->character spacing exactly: and enter something like 20/25

and done....

solution by: Rajesh Rolen

Crystal Report in asp.net

To create crystal report in asp.net follow below steps
1. take a crystal report viewer on page (i have given name "crv" to it)
then write below code in code behind file.

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;

private void showreport()
{
ReportDocument report = new ReportDocument();
report.Load(Server.MapPath("MyReportName.rpt"));
report.SetDataSource(objrep.ReportDataSource);
SetTableLocation(report.Database.Tables);
crv.ReportSource = report; //crv is your Crystal report viewer's name.
}


private void SetTableLocation(Tables tables)
{
ConnectionInfo connectionInfo = new ConnectionInfo();

connectionInfo.ServerName = @"DBSERVER2\SQL2005";
connectionInfo.DatabaseName = "dbMEAVer5web";
connectionInfo.UserID = "sa";
connectionInfo.Password = "admin55";

foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
tableLogOnInfo.ConnectionInfo = connectionInfo;
table.ApplyLogOnInfo(tableLogOnInfo);
}
}



Solution by: Rajesh Rolen

very nice time picker (jquery)

here u can find very good time picker build in jquery.

http://pttimeselect.sourceforge.net/example/index.html


date and time picker using user control (very good)
http://www.markbeaton.com/DateTimePicker.aspx

Disable all controls of asp.net page

call it like this: DisableControls(Page ,false);

below code is to disable all controls of a asp.net page.

protected void DisableControls(Control parent,bool status)
{
foreach (Control ctrl in parent.Controls)
{

if (ctrl is TextBox)

((TextBox)ctrl).Enabled = status;

else if (ctrl is Button)

((Button)ctrl).Enabled = status;

else if (ctrl is RadioButton)

((RadioButton)ctrl).Enabled = status;

else if (ctrl is ImageButton)

((ImageButton)ctrl).Enabled = status;

else if (ctrl is CheckBox)

((CheckBox)ctrl).Enabled = status;

else if (ctrl is DropDownList)

((DropDownList)ctrl).Enabled = status;

else if (ctrl is HyperLink)

((HyperLink)ctrl).Enabled = status;

DisableControls(ctrl,status);
}
}

set date format in ajax CalendarExtender

you can set date format in ajax's calendar extender using below way:
just specify your required format and its done:


< cc1:CalendarExtender ID="txtrequiredby_CalendarExtender" Format="dd/MM/yyyy" runat="server" Enabled="True" TargetControlID="txtrequiredby" >
< /cc1:CalendarExtender >

Attach double click event on listbox in asp.net

when we want to attach double click event on asp.net listbox we can make by using javascipt.


protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "myListBox_Dblclk")
{

//your code to perform task or to call desired function

}
myListBox.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(myListBox, "myListBox_Dblclk"));
}
by: Rajesh Rolen

Code to download a file on Buttton click

Some times we have need like when user click on a button then we want to perform some server side operation and then a automatic download file prompt should be shown to user to download a file..
below code will help you in above situation:
write it at server side on any event.

create below class or place functions in same page but its recommended to take separate class for it
class DownloadLibrary
{
public static string getContentType(string Fileext)
{
string contenttype = "";
switch (Fileext)
{
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".doc":
contenttype = "application/msword";
break;
case ".ppt":
contenttype = "application/vnd.ms-powerpoint";
break;
case ".pdf":
contenttype = "application/pdf";
break;
case ".jpg":
case ".jpeg":
contenttype = "image/jpeg";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".ico":
contenttype = "image/vnd.microsoft.icon";
break;
case ".zip":
contenttype = "application/zip";
break;
default: contenttype = "";
break;
}
return contenttype;
}

public static void downloadFile(System.Web.UI.Page pg, string filepath)
{
pg.Response.AppendHeader("content-disposition", "attachment; filename=" + new FileInfo(filepath).Name);
pg.Response.ContentType = clsGeneral.getContentType(new FileInfo(filepath).Extension);
pg.Response.WriteFile(filepath);
pg.Response.End();
}
}


now write below code in ur aspx page
DownloadLibrary.downloadFile(this.Page,filepath);

Commonly Used Types and Namespaces of .NET Framework 3.5 :

Microsoft.Aspnet.Snapin

Contains classes that are necessary for the ASP.NET management console application to interact with the Microsoft Management Console (MMC).

Microsoft.Build.BuildEngine

Contains the classes that represent the MSBuild engine.

Microsoft.Build.Framework

Contains classes that make up the tasks, loggers, and events of MSBuild.

Microsoft.Build.Tasks

Contains the implementation of all tasks shipping with MSBuild.

Microsoft.Build.Tasks.Deployment.Bootstrapper

Contains classes used internally by MSBuild.

Microsoft.Build.Tasks.Deployment.ManifestUtilities

Contains classes used internally by MSBuild.

Microsoft.Build.Utilities

Provides helper classes that you can use to create your own MSBuild loggers and tasks.

Microsoft.Csharp

Contains classes that support compilation and code generation using the C# language.

Microsoft.JScript

Contains classes that support compilation and code generation using the JScript language.

Microsoft.SqlServer.Server

Contains classes that are specific to the integration of the Microsoft .NET Framework common language runtime (CLR) component into Microsoft SQL Server, and the SQL Server database engine process execution environment.

Microsoft.VisualBasic

Contains classes that support compilation and code generation using the Visual Basic language.

Microsoft.VisualBasic.ApplicationServices

Contains types that support the Visual Basic Application Model and provide access to application information.

Microsoft.VisualBasic.CompilerServices

Contains internal-use only types that support the Visual Basic compiler.

Microsoft.VisualBasic.Devices

Contains types that support the My objects related to devices in Visual Basic.

Microsoft.VisualBasic.FileIO

Contains types that support the My file system object in Visual Basic.

Microsoft.VisualBasic.Logging

Contains types that support the My logging objects in Visual Basic and provides a simple log listener that directs logging output to file.

Microsoft.VisualBasic.MyServices

Contains types that support My in Visual Basic.

Microsoft.VisualBasic.MyServices.Internal

Contains internal-use only types that support My in Visual Basic.

Microsoft.VisualBasic.Vsa

Microsoft.VisualC

Microsoft.Vsa

Contains interfaces that allow you to integrate script for the .NET Framework script engines into applications, and to compile and execute code at run time.

Microsoft.Vsa.Vb.CodeDOM

Microsoft.Win32

Provides two types of classes: those that handle events raised by the operating system and those that manipulate the system registry.

Microsoft.Win32.SafeHandles

Contains classes that are abstract derivations of safe handle classes that provide common functionality supporting file and operating system handles.

Microsoft.WindowsCE.Forms

Contains classes for developing Pocket PC and Smartphone Windows Forms applications using the .NET Compact Framework.

Microsoft.WindowsMobile.DirectX

Contains classes for developing DirectX applications on devices with the .NET Compact Framework. Requires a future release of Windows Mobile to run the applications.

Microsoft.WindowsMobile.DirectX.Direct3D

Contains classes for developing Direct3D applications on devices with the .NET Compact Framework. Requires a future release of Windows Mobile to run the applications.

Microsoft_VsaVb

System

Contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications.

System.CodeDom

Contains classes that can be used to represent the elements and structure of a source code document. These elements can be used to model the structure of a source code document that can be output as source code in a supported language using the functionality provided by the System.CodeDom.Compiler namespace.

System.CodeDom.Compiler

Contains types for managing the generation and compilation of source code in supported programming languages. Code generators can each produce source code in a particular programming language based on the structure of Code Document Object Model (CodeDOM) source code models consisting of elements provided by the System.CodeDom namespace.

System.Collections

Contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

System.Collections.Generic

Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

System.Collections.ObjectModel

Contains classes that can be used as collections in the object model of a reusable library. Use these classes when properties or methods return collections.

System.Collections.Specialized

Contains specialized and strongly typed collections; for example, a linked list dictionary, a bit vector, and collections that contain only strings.

System.ComponentModel

Provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components.

System.ComponentModel.Design

Contains classes that developers can use to build custom design-time behavior for components and user interfaces for configuring components at design time. The design time environment provides systems that enable developers to arrange components and configure their properties.

System.ComponentModel.Design.Data

Contains classes for implementing design-time behavior of data-related components.

System.ComponentModel.Design.Serialization

Provides types that support customization and control of serialization at design time.

System.Configuration

Contains the types that provide the programming model for handling configuration data.

System.Configuration.Assemblies

Contains classes that are used to configure an assembly.

System.Configuration.Install

Provides classes that allow you to write custom installers for your own components. The Installer class is the base class for all custom installers in the .NET Framework.

System.Configuration.Provider

Contains the base classes shared by both server and client applications to support a pluggable model to easily add or remove functionality.

System.Data

Contains classes that constitute most of the ADO.NET architecture. The ADO.NET architecture enables you to build components that efficiently manage data from multiple data sources. In a disconnected scenario (such as the Internet), ADO.NET provides the tools to request, update, and reconcile data in multiple tier systems. The ADO.NET architecture is also implemented in client applications, such as Windows Forms, or HTML pages created by ASP.NET.

System.Data.Common

Contains classes shared by the .NET Framework data providers. A .NET Framework data provider describes a collection of classes used to access a data source, such as a database, in the managed space.

System.Data.Design

Contains classes that can be used to generate a custom typed-dataset.

System.Data.Linq

Contains classes to access relational data as objects. DataContext and related classes can be used for Reading, Creating, Updating and Deleting objects mapped to a database using mapping specified as attributes in your object model or in a separate external XML file.

System.Data.Linq.Mapping

Provides programmatic access to mapping information used by LINQ to SQL.

System.Data.Odbc

Contains classes that encapsulate the .NET Framework Data Provider for ODBC. The .NET Framework Data Provider for ODBC describes a collection of classes used to access an ODBC data source in the managed space.

System.Data.OleDb

Contains classes that encapsulate the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB describes a collection of classes used to access an OLE DB data source in the managed space.

System.Data.OracleClient

Contains classes that encapsulate the .NET Framework Data Provider for Oracle. The .NET Framework Data Provider for Oracle describes a collection of classes used to access an Oracle data source in the managed space.

System.Data.Sql

Contains classes that support SQL Server-specific functionality. The API extensions in this class add to the .NET Framework Data Provider for SQL Server (System.Data.SqlClient).

System.Data.SqlClient

Contains classes that encapsulate the .NET Framework Data Provider for SQL Server. The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space.

System.Data.SqlServerCE

Describes a collection of classes that can be used to access a database in SQL Server CE from Windows CE-based devices in the managed environment. With this namespace you can create SQL Server CE databases on a device and also establish connections to SQL Server databases that are on a device or on a remote server.

System.Data.SqlTypes

Contains classes for native data types within SQL Server. These classes provide a faster alternative to other data types. Using the classes in this namespace helps prevent type conversion errors caused in situations where loss of precision could occur. Because other data types are converted to and from SqlTypes behind the scenes, explicitly creating and using objects within this namespace results in faster code as well.

System.Diagnostics

Provides classes that allow you to interact with system processes, event logs, and performance counters. This namespace also provides classes that allow you to debug your application and to trace the execution of your code. For more information, see the Trace and Debug classes.

System.Diagnostics.CodeAnalysis

Contains classes for interaction with code analysis tools. Code analysis tools are used to analyze code for conformance to coding conventions such as naming or security rules.

System.Diagnostics.Design

Contains classes that can be used to extend design-time support for application monitoring and instrumentation.

System.Diagnostics.SymbolStore

Provides classes that allow you to read and write debug symbol information, such as source line to Microsoft intermediate language (MSIL) maps. Compilers targeting the .NET Framework can store the debug symbol information into programmer's database (PDB) files. Debuggers and code profiler tools can read the debug symbol information at run time.

System.DirectoryServices

Provides easy access to Active Directory from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers. ADSI gives the administrator the ability to locate and manage resources on a network with relative ease, regardless of the network's size.

System.DirectoryServices.ActiveDirectory

Provides a high level abstraction object model that builds around Microsoft® Active Directory® directory service tasks. The Active Directory® directory service concepts such as forest, domain, site, subnet, partition and schema are part of the object model.

System.DirectoryServices.Protocols

Provides the methods defined in the Lightweight Directory Access Protocol (LDAP) version 3 (V3) and Directory Services Markup Language (DSML) version 2 (V2) standards.

System.Drawing

Provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces.

System.Drawing.Design

Contains classes that extend design-time user interface (UI) logic and drawing. You can further extend this design-time functionality to create custom toolbox items, type-specific value editors that can edit and graphically represent values of their supported types, or type converters that can convert values between certain types. This namespace provides the basic frameworks for developing extensions to the design-time UI.

System.Drawing.Drawing2D

Provides advanced 2-dimensional and vector graphics functionality. This namespace includes the gradient brushes, the Matrix class (used to define geometric transforms), and the GraphicsPath class.

System.Drawing.Imaging

Provides advanced GDI+ imaging functionality. Basic graphics functionality is provided by the System.Drawing namespace.

System.Drawing.Printing

Provides print-related services. Typically, you create a new instance of the PrintDocument class, set the properties that describe what to print, and call the Print method to actually print the document.

System.Drawing.Text

Provides advanced GDI+ typography functionality. Basic graphics functionality is provided by the System.Drawing namespace. The classes in this namespace allow users to create and use collections of fonts.

System.EnterpriseServices

Provides an important infrastructure for enterprise applications. COM+ provides a services architecture for component programming models deployed in an enterprise environment. This namespace provides .NET Framework objects with access to COM+ services, making the .NET Framework objects more practical for enterprise applications.

System.EnterpriseServices.CompensatingResourceManager

Provides classes that allow you to use a Compensating Resource Manager (CRM) in managed code. A CRM is a service provided by COM+ that enables you to include non-transactional objects in Microsoft Distributed Transaction Coordinator (DTC) transactions. Although CRMs do not provide the capabilities of a full resource manager, they do provide transactional atomicity (all-or-nothing behavior) and durability through the recovery log.

System.EnterpriseServices.Internal

Provides infrastructure support for COM+ services. The classes and interfaces in this namespace are specifically intended to support calls into System.EnterpriseServices from the unmanaged COM+ classes.

System.Globalization

Contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. These classes are useful for writing globalized (internationalized) applications.

System.IO

Contains types that allow synchronous and asynchronous reading and writing on data streams and files.

System.IO.Compression

Contains classes that provide basic compression and decompression for streams.

System.IO.IsolatedStorage

Contains types that allow the creation and use of isolated stores. With these stores, you can read and write data that less trusted code cannot access and help prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists.

System.IO.Ports

Contains classes that control serial ports, providing a framework for synchronous and event-driven I/O, access to pin and break states, access to serial driver properties, and enumerations for specifying port characteristics.

System.Linq

Provides classes and interfaces that support queries that use Language-Integrated Query (LINQ).

System.Linq.Expressions

Contains classes, interfaces and enumerations that enable language-level code expressions to be represented as objects in the form of expression trees.

System.Management

Provides access to a rich set of management information and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure.

System.Management.Instrumentation

Provides the classes necessary for instrumenting applications for management and exposing their management information and events through WMI to potential consumers. Consumers such as Microsoft Application Center or Microsoft Operations Manager can then manage your application easily, and monitoring and configuring of your application is available for administrator scripts or other applications, both managed as well as unmanaged.

System.Messaging

Provides classes that allow you to connect to, monitor, and administer message queues on the network and send, receive, or peek messages.

System.Messaging.Design

Contains classes that can be used to extend design-time support for System.Messaging classes.

Trim text using javascript

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}

Add/delete rows in HTML Table at run time using javascript

< script language="javascript" type="text/javascript" >

function addrow()
{
var tbody = document.getElementById("< %= tableName.ClientID % >").getElementsByTagName("TBODY")[0];
var row = document.createElement("TR")
var td1 = document.createElement("TD")
var td2 = document.createElement("TD")
var td3 = document.createElement("TD")

td1.appendChild(document.createTextNode("value"));
td2.appendChild(document.createTextNode("value));

//to add hyper liked cell for delete row
var code = "< a href=\'#\' onClick=\"javascript:deleteCriteria(this.parentNode.parentNode.rowIndex);\" >< img src=\"Images/user_delete.png\" alt=\"Delete\" / >< /a >";

td3.setAttribute("align", "center");
td3.innerHTML = code;

row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);

tbody.appendChild(row);
}

function deleteCriteria(i) {
if (window.confirm('Are you sure you want to delete this record?') == true) {
document.getElementById("< %= tblcriteria.ClientID % >").deleteRow(i);

}
}
< /script >

Taking a SQL Server Database Off-Line/ON-Line

Sometimes you will want to remove all access to a database for a period of time without detaching the database or deleting it. One option to achieve this is to take the database off-line. You can do this using standard SQL Server tools or Transact-SQL.
Using SQL Server Tools

The easiest way to take a SQL Server database off-line is using the graphical user interface tools provided. If you are using either SQL Server Management Studio or Enterprise Manager, you can simply right-click the name of a database. This causes a context-sensitive menu to appear. Within the "All Tasks" or "Tasks" submenu is the "Take Offline" option. Clicking this option takes the database off-line. You can return the database to an operational status by selecting "Bring Online" from the same menu.
ALTER DATABASE Command

The preferred manner in which to take a database off-line using Transact-SQL statements is with the ALTER DATABASE command. This command allows database administrators to modify database settings, files and filegroups.
Taking a Database Off-Line

The T-SQL for taking a database off-line is similar to that for setting restricted access mode. The simplest variation of the command is the following statement:
ALTER DATABASE database-name SET OFFLINE

The above command attempts to take the named database off-line immediately. If a user or a background process is currently connected to the database the command cannot be completed. In this situation, the ALTER DATABASE statement will be blocked and will wait until all connections are closed. This ensures that no transactions are rolled back unexpectedly. During the period of blocking, no new connections to the database will be permitted.

NB: Background processes that are running against SQL Server may cause the command to be indefinitely blocked, as can internal processes. The AUTO_UPDATE_STATISTICS_ASYNC in particular should be checked. If set to ON, the statement will be blocked.
Failing When Blocked

If you run the ALTER DATABASE command whilst users or processes may be connected, but you do not wish the command to be blocked, you can execute the statement with the NO_WAIT option. This causes the command to fail with an error.
ALTER DATABASE database-name SET OFFLINE WITH NO_WAIT
Forcing Disconnection of Users and Processes

In some cases it is appropriate to run the ALTER DATABASE command and allow it to be blocked until all of the current connections are closed. For SQL Servers that are used only internally to an organisation, each user can be contacted and asked to disconnect. Once they have, the command will complete automatically and the database will be inaccessible.

In other situations, for example a publicly accessible web site database, it may not be possible to ask users to disconnect. In these cases you may automatically disconnect users and to roll back their active transactions. This is achieved using the ROLLBACK clause.

The ROLLBACK clause can be used to immediately disconnect users or can be provided with a number of seconds to pause before taking the database off-line. To force the immediate disconnection of general users and processes and the rolling back of their transactions, use the following command:
ALTER DATABASE database-name SET OFFLINE WITH ROLLBACK IMMEDIATE

If desired, you can specify that there should be a pause before disconnecting the users. During this period any attempts to connect to the database are refused but existing connections are given a number of seconds to complete their processing. The following example statement pauses for two minutes before disconnecting users:
ALTER DATABASE database-name SET OFFLINE WITH ROLLBACK AFTER 120 SECONDS

Bringing a Database On-Line

Once you have completed any maintenance work and want to resume the use of the database, you can bring it back on-line using the ALTER DATABASE command:
ALTER DATABASE database-name SET ONLINE

How to check in javascript that string contains a substring or not

many of times we need to find out that a particular string contains a particular (charactor or string ) or not.
so below example will help you.
var varA = "hello how r u";
if(varA.indexOf("How") != -1)
{
alert('it contains How');
}
else
{
alert('it not contains how');
}

Article by: Rajesh Rolen

ASP.net button text to wrap to second line

Some times we have more matter to write on Asp.net Button and the button becomes longer in width.. if we make its width small then text will be truncated (complete text will not be visible). so to do this here is solution:

Lets say you want to write following line on page in this way:

Submit here if you are an
Engineer

to write text in above format in asp button write it in below format:
Submit here if you are an &#10; Engineer

so the answer is use : &#10; to new line in asp button

ASP.net button text to wrap to second line

Some times we have more matter to write on Asp.net Button and the button becomes longer in width.. if we make its width small then text will be truncated (complete text will not be visible). so to do this here is solution:

Lets say you want to write following line on page in this way:

Submit here if you are an
Engineer

to write text in above format in asp button write it in below format:
Submit here if you are an &#10; Engineer

so the answer is use : &#10; to new line in asp button

Multiple Active Result Sets (MARS) in SQL Server 2005

MARS is newly added future in SQL 2005. In earlier version from sql2005 user are not allowed to run more than one SQL batch on an open connection at the same time but sql2005 allows the user to run more than one SQL batch on an open connection at the same time.
private void MARS_Off()
{
SqlConnection conn = new SqlConnection("Server=serverName;
Database=adventureworks;Trusted_Connection=yes;");

string sql1 = "SELECT * FROM [Person].[Address]";
string sql2 = "SELECT * FROM [Production].[TransactionHistory]";

SqlCommand cmd1 = new SqlCommand(sql1, conn);
SqlCommand cmd2 = new SqlCommand(sql2, conn);
cmd1.CommandTimeout = 500;
cmd2.CommandTimeout = 500;
conn.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
// do stuff with dr1 data
conn.Close();

conn.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
// do stuff with dr2 data
conn.Close();
}

Multiple Active Result Sets (MARS) in SQL Server 2005

MARS is newly added future in SQL 2005. In earlier version from sql2005 user are not allowed to run more than one SQL batch on an open connection at the same time but sql2005 allows the user to run more than one SQL batch on an open connection at the same time.
private void MARS_Off()
{
SqlConnection conn = new SqlConnection("Server=serverName;
Database=adventureworks;Trusted_Connection=yes;");

string sql1 = "SELECT * FROM [Person].[Address]";
string sql2 = "SELECT * FROM [Production].[TransactionHistory]";

SqlCommand cmd1 = new SqlCommand(sql1, conn);
SqlCommand cmd2 = new SqlCommand(sql2, conn);
cmd1.CommandTimeout = 500;
cmd2.CommandTimeout = 500;
conn.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
// do stuff with dr1 data
conn.Close();

conn.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
// do stuff with dr2 data
conn.Close();
}

About this blog

My Blog List

Advertise On This Site

Site Info

Advertise on this Site

To advertise on this site please mail on RajeshRolen@gmail.com

Information Source

About

Pages

Dot Net Academy

Advertis in This Area of Site

Powered by Blogger.

Followers

Search This Blog