Faqs on asp.net,c#,vb.net and sqlserver2005

this blog covers all the Faqs related to .net technologies like asp.net,vb.net,c#.net,ajax,javascript and sqlserver2005.

Feb 29, 2008

Registering an Assembly in the GAC

Registering an Assembly in the GAC

1) Create an assembly key file Use the sn.exe tool to create a key file: sn -k StrongNameFile.snk If your path environment variables aren't set, you'll have to go to the C:\Program Files\Microsoft.NET\FrameworkSDK\Bin\ directory to run sn.exe) The filename "StrongNameFile.snk" can be any name you want.

2) Edit your assembly Now you have to add a tag which will link your assembly key to the assembly: using System.Reflection; [assembly:AssemblyKeyFile("StrongNameFile.snk")] Normally this is done in the utility AssemblyInfo.cs (vb) file.

3) Add your assembly to the GAC gacutil /i AssemblyFileName.dll To uninstall this assembly from the GAC, use the command: gacutil /u AssemblyFileName

4) (Opional) Add your assembly to machine.config Locate the tag (for web apps,under ////) Between the tags, enter: You can get the information for the assembly attribute, by running the gacutil /l command which will return a list of all the assemblies in the GAC. You will have to look for the one you just added and copy the entire line (less the Custom=XXX part at the end). At this point, you will be able to place this directive in your aspx pages. <%@Import Namespace="YourNamespace"%> or, you can set a reference in the Visual Studio IDE as you would with other GAC Assemblies.

Happy Programming

regasm.exe, regsvr32.exe,tlbimp.exe and tlbexp.exe

difference among regasm.exe, regsvr32.exe,tlbimp.exe and tlbexp.exe

The difference between regasm and regsvr32:
regasm.exe is used for registering an assembly so that a com client can access its classes and uses them like a com class.
regasm.exe is used to create COM Callable Wrapper (CCW) around .NET assemblies. .NET managed assemblies(EXEs, DLLs) are different from COM DLLs (which are unmanaged, ie. they interact with the OS directly). So to register an unmanaged DLL we use regsvr32.exe.
But if wehave a managed .NET assembly and we want to use it with COM components to use it as if it were a COM assembly, then we need to use regasm.exe.
Regasm.exe creates a type library as well as registers it whereas tlbexp.exe only creates a CCW but does not register it.
Tlbimp.exe:
Tlbimp.exe (Type Library Importer) is used to create a Runtime Callable Wrapper around a COM component so that the unmanaged COM library can be used in .NET.

When do we use Tlbimp and not regasm or regsvr32?

Tlbexp.exe generates a type library that contains definitions of the types defined in the assembly. Applications such as Visual Basic 6.0 can use the generated type library to bind to the .NET types defined in the assembly.
The entire assembly is converted at once. You cannot use Tlbexp.exe to generate type information for a subset of the types defined in an assembly.
You cannot use Tlbexp.exe to produce a type library from an assembly that was imported using the Type Library Importer (Tlbimp.exe). Instead, you should refer to the original type library that was imported with Tlbimp.exe. You can export a type library from an assembly that references assemblies that were imported using Tlbimp.exe.
Tlbexp.exe generates a type library but does not register it. This is in contrast to the Assembly Registration tool (Regasm.exe), which both generates and registers a type library. To generate and register a type library with COM, use Regasm.exe.
Type Library Importer
Tlbimp.exe performs conversions on an entire type library at one time. You cannot use the tool to generate type information for a subset of the types defined within a single type library.

Happy Programming.

Feb 28, 2008

FOREIGN KEY Constraints

FOREIGN KEY Constraints

A foreign key (FK) is a column or combination of columns used to establish and enforce a link between the data in two tables. A link is created between two tables by adding the column or columns that hold one table's primary key values to the other table. This column becomes a foreign key in the second table.

You can create a foreign key by defining a FOREIGN KEY constraint when you create or alter a table.

For example, the titles table in the pubs database has a link to the publishers table because there is a logical relationship between books and publishers. The pub_id column in the titles table matches the primary key column of the publishers table. The pub_id column in the titles table is the foreign key to the publishers table.

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table. A FOREIGN KEY constraint can contain null values; however, if any column of a composite FOREIGN KEY constraint contains null values, then verification of the FOREIGN KEY constraint will be skipped.
Note A FOREIGN KEY constraint can reference columns in tables in the same database or within the same table (self-referencing tables), for example, an employee table that contains three columns: employee_number, employee_name, and manager_employee_number. Because the manager is an employee too, there is a foreign key relationship from the manager_employee_number column to the employee_number column.
Although the primary purpose of a FOREIGN KEY constraint is to control the data that can be stored in the foreign key table, it also controls changes to data in the primary key table. For example, if the row for a publisher is deleted from the publishers table, and the publisher's ID is used for books in the titles table, the relational integrity between the two tables is broken; the deleted publisher's books are orphaned in the titles table without a link to the data in the publishers table. A FOREIGN KEY constraint prevents this situation. The constraint enforces referential integrity by ensuring that changes cannot be made to data in the primary key table if those changes invalidate the link to data in the foreign key table. If an attempt is made to delete the row in a primary key table or to change a primary key value, the action will fail if the deleted or changed primary key value corresponds to a value in the FOREIGN KEY constraint of another table. To change or delete a row in a FOREIGN KEY constraint successfully, you must first either delete the foreign key data in the foreign key table or change the foreign key data in the foreign key table, thereby linking the foreign key to different primary key data.
A FOREIGN KEY constraint is a candidate for an index because:
Changes to PRIMARY KEY constraints are checked with FOREIGN KEY constraints in related tables.
Foreign key columns are often used in join criteria when the data from related tables is combined in queries by matching the column(s) in the FOREIGN KEY constraint of one table with the primary or unique key column(s) in the other table. An index allows Microsoft® SQL Server™ 2000 to find related data in the foreign key table quickly. However, creating this index is not a requirement. Data from two related tables can be combined even if no PRIMARY KEY or FOREIGN KEY constraints are defined between the tables, but a foreign key relationship between two tables indicates that the two tables have been optimized to be combined in a query that uses the keys as its criteria.

Feb 22, 2008

Enterprise Library and .Net 2.0

Using Enterprise DAAB from ASP.NET 2.0 project
Enterprise Library and .Net 2.0

Error parsing application configuration file at line 47. Type '{http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration}ReadOnlyConfigurationSectionData' is not found in Schema. Please correct before processeding. (You might rename the current web.config and add a new one.)

I tossed up a quick example of using the
Enterprise Library Configuration Application Block in your applications, and thought I would give an example of using the Cache Application Block as well. In this case, I am actually using the two application blocks together so we can seem them side-by-side. As always, the code will run in Snippet Compiler, but you need to download and install the Enterprise Library and move over the appropriate DLL's shown in the directory.

In this example, I am using the XML File Storage Provider to save my configuration settings in my sitesettings.config file and using the default storage provider for caching, called the NullBackingStore, which stores the cache information into a Hashtable in memory.

This time when I run the Enterprise Library Configuration tool I need to add both the Caching Application Block and Configuration Application Block to my application (shown below). I keep the default settings, but I do have to specify that sitesettings.config will be the XML file to store my global application settings. If you don't do this, the application will toss an error reminding you to do so.

At first I was a bit confused as to why there is an XML File Storage Provider and XML Serializer Transformer under cachingConfiguration. I didn't add it. It turns out that there is a separate XML file, called by default cachingConfiguration.config, created to store the caching configuration information. It specifies that I am using the NullBackingStore as well as a few other settings.



Here is the code that reads and writes to both the configuration file and cache for testing:



Testing Application Blocks
using System;

using Microsoft.Practices.EnterpriseLibrary.Configuration;

using Microsoft.Practices.EnterpriseLibrary.Caching;



public class SiteSettings

{

#region Private Members



private string _name;

private string _url;

private string _emailAddress;



#endregion



#region Properties



public string Name

{

get { return _name; }

set { _name = value; }

}



public string Url

{

get { return _url; }

set { _url = value; }

}



public string EmailAddress

{

get { return _emailAddress; }

set { _emailAddress = value; }

}



#endregion

}



public class TestClass

{

public static void Main()

{

// Create initial "siteSettings" object

SiteSettings siteSettings = new SiteSettings();



siteSettings.Name
= "DavidHayden.com";

siteSettings.Url
= "http://www.davidhayden.com/";

siteSettings.EmailAddress
= "nospam@nospam.com";





// Save "siteSettings" to the XML config file

ConfigurationManager.WriteConfiguration("SiteSettings", siteSettings);





// Retrieve settings from the XML config file

SiteSettings mySettings = ConfigurationManager.GetConfiguration("SiteSettings") as SiteSettings;



if (mySettings != null)

{

Console.WriteLine(
"Name = {0}", mySettings.Name);

Console.WriteLine(
"Url = {0}", mySettings.Url);

Console.WriteLine(
"Email Address = {0}", mySettings.EmailAddress);

Console.ReadLine();

}





// Get the CacheManager

CacheManager myCacheManager = CacheFactory.GetCacheManager();





// Save the settings to the Cache

myCacheManager.Add("SiteSettings",mySettings);





// Retrieve settings from the cache

SiteSettings cachedSettings = (SiteSettings)myCacheManager.GetData("SiteSettings");



if (cachedSettings != null)

{

Console.WriteLine(
"Name = {0}", cachedSettings.Name);

Console.WriteLine(
"Url = {0}", cachedSettings.Url);

Console.WriteLine(
"Email Address = {0}", cachedSettings.EmailAddress);

Console.ReadLine();

}

}

}




Although the configuration settings might be a bit ugly in the backend, the code is pretty straight forward. I have added comments above so you can see what is happening. Here are the configuration files:

cachetest.exe.config
<configuration>

<configSections>

<section name="enterpriselibrary.configurationSettings"

type
="Microsoft.Practices.EnterpriseLibrary.Configuration.

ConfigurationManagerSectionHandler,

Microsoft.Practices.EnterpriseLibrary.Configuration,

Version
=1.0.0.0, Culture=neutral, PublicKeyToken=null" />

</configSections>

<enterpriselibrary.configurationSettings

xmlns:xsd
="http://www.w3.org/2001/XMLSchema"

xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"

applicationName
="EntLibTest"

xmlns
="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration">

<configurationSections>

<configurationSection xsi:type="ReadOnlyConfigurationSectionData"

name
="cachingConfiguration" encrypt="false">

<storageProvider xsi:type="XmlFileStorageProviderData"

name
="XML File Storage Provider" path="cachingConfiguration.config" />

<dataTransformer xsi:type="XmlSerializerTransformerData"

name
="Xml Serializer Transformer">

<includeTypes />

</dataTransformer>

</configurationSection>

<configurationSection name="SiteSettings" encrypt="false">

<storageProvider xsi:type="XmlFileStorageProviderData"

name
="XML File Storage Provider" path="sitesettings.config" />

<dataTransformer xsi:type="XmlSerializerTransformerData"

name
="Xml Serializer Transformer">

<includeTypes />

</dataTransformer>

</configurationSection>

</configurationSections>

<keyAlgorithmStorageProvider xsi:nil="true" />

<includeTypes />

</enterpriselibrary.configurationSettings>

</configuration>




cacheConfiguration.config
<?xml version="1.0" encoding="utf-8"?>

<cachingConfiguration>

<xmlSerializerSection type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings,

Microsoft.Practices.EnterpriseLibrary.Caching, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">

<enterpriseLibrary.cacheSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" defaultCacheManager="Cache Manager"

xmlns
="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/cache">

<cacheManagers>

<cacheManager name="Cache Manager" expirationPollFrequencyInSeconds="60"

maximumElementsInCacheBeforeScavenging
="1000" numberToRemoveWhenScavenging="10">

<cacheStorage xsi:type="CustomCacheStorageData" name="Null Storage"

type
="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore,

Microsoft.Practices.EnterpriseLibrary.Caching, Version=1.0.0.0, Culture=neutral,

PublicKeyToken
=null">

<extensions />

</cacheStorage>

</cacheManager>

</cacheManagers>

</enterpriseLibrary.cacheSettings>

</xmlSerializerSection>

</cachingConfiguration>


sitesettings.config
<?xml version="1.0" encoding="utf-8"?>

<SiteSettings>

<xmlSerializerSection type="SiteSettings, cachetest, Version=0.0.0.0,

Culture=neutral, PublicKeyToken=null">

<SiteSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance">

<Name>DavidHayden.com</Name>

<Url>http://www.davidhayden.com/</Url>

<EmailAddress>nospam@nospam.com</EmailAddress>

</SiteSettings>

</xmlSerializerSection>

</SiteSettings>




As you can see, there is certainly a lot of flexiblity with the Enterprise Library as literally you could change the configuration in the backend to specify different storage providers and theoretically never change a single line of code. There has got to be some price to this flexiblity, which is a couple of XML files to specify settings. It looks a bit daunting at first if you aren't used to XML and the plug-in type architecture, but by playing with it more and more one can get comfortable with it pretty quickly.

Feb 19, 2008

What are delegates and why are they required?

Working with Delegates in C#

Introduction

Delegates in C# are like functions pointers in C/C++. A multi cast delegate can refer to several methods. A delegate can be used to invoke a method, the call to which can only be resolved or determined at runtime. This article discusses what delegates are and how they can be used in C# with lucid code examples.

What are delegates and why are they required?

Delegates are function pointers in C# that are managed and type safe and can refer to one or more methods that have identical signatures. Delegates in C# are reference types. They are type safe, managed function pointers in C# that can be used to invoke a method that the delegate refers to. The signature of the delegate should be the same as the signature of the method to which it refers. According to MSDN, "A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure."
C# provides support for Delegates through the class called Delegate in the System namespace. Delegates are of two types.
Single-cast delegates
Multi-cast delegates
A Single-cast delegate is one that can refer to a single method whereas a Multi-cast delegate can refer to and eventually fire off multiple methods that have the same signature.
The signature of a delegate type comprises are the following.
The name of the delegate
The arguments that the delegate would accept as parameters
The return type of the delegate
A delegate is either public or internal if no specifier is included in its signature. Further, you should instantiate a delegate prior to using the same.
The following is an example of how a delegate is declared.
Listing 1: Declaring a delegate public delegate void TestDelegate(string message);
The return type of the delegate shown in the above example is "void" and it accepts a string argument. Note that the keyword "delegate" identifies the above declaration as a delegate to a method. This delegate can refer to and eventually invoke a method that can accept a string argument and has a return type of void, i.e., it does not return any value. You can use a delegate to make it refer to and invoke a method that has identical signature as the delegate only. Even if you are using multi-cast delegates, remember that you can use your delegate to refer to and then fire off multiple methods that have identical signatures only.
A delegate should always be instantiated before it is used. The following statement in Listing 2 shows how you can instantiate a delegate.
Listing 2: Instantiating a delegate
TestDelegate t = new TestDelegate(Display);
Implementing Delegates in C#
This section illustrates how we can implement and use delegates in C#. The following is an example of a delegate that is used to refer to a method of identical signature as the delegate and eventually invoke the method using the delegate.
Listing 3: Implementing a single-cast delegate using System;

public delegate void TestDelegate(string message); //Declare the delegate
class Test
{
public static void Display(string message)
{
Console.WriteLine("The string entered is : " + message);
}
static void Main()
{
TestDelegate t = new TestDelegate(Display); //Instantiate the delegate
Console.WriteLine("Please enter a string");
string message = Console.ReadLine();
t(message); //Invoke the delegate
Console.ReadLine();
}
}


Refer to the code in Listing 3 above. Note how the delegate has been instantiated. The delegate should be passed the method name as argument when instantiating it to indicate the method that it would be referring to. Further, note that the signature of the delegate "TestDelegate" and the method that it refers to, i.e., "Display", have identical signatures.
You can also assign the references of multiple methods to a delegate and use it to invoke multiple methods. Such a delegate is called a multi-cast delegate as multiple method references are cast to it and then the delegate is used to invoke these methods. The following code example illustrates how a multi-cast delegate can be implemented and used.
Listing 4: Implementing a multi-cast delegate using System;

public delegate void TestDelegate();
class Test
{
public static void Display1()
{
Console.WriteLine("This is the first method");
}
public static void Display2()
{
Console.WriteLine("This is the second method");
}
static void Main()
{
TestDelegate t1 = new TestDelegate(Display1);
TestDelegate t2 = new TestDelegate(Display2);
t1 = t1 + t2; // Make t1 a multi-cast delegate
t1(); //Invoke delegate
Console.ReadLine();
}
}

On execution of the above program shown in code Listing IV, the following message is displayed:
This is the first method
This is the second method
Note how we have used the delegate instance t1 as a multi-cast delegate by assigning the references of both t1 and t2 to it.

Examples on Delegates in C#

Delegates in C#

Definition:

Delegate is type which holds the method(s) reference in an object. It is also reffered as a type safe function pointers.

Advantages:

  • Encapsulating the method's call from caller.
  • Effective use of Delegat improves the performance of application.
  • Used to call a method asynchronously.
    Declaration:
    public delegate type_of_delegate delegate_name()
    Example : public delegate int mydelegate(int delvar1,int delvar2)
    Note:
    you can use delegeate without parameter or with parameter list.
    you should follow the same syntax as in the method.
    (if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it is reffered as type safe function pointer)
    Sample Program using Delegate :

    public delegate double Delegate_Prod(int a,int b);
    class Class1 {
    static double fn_Prodvalues(int val1,int val2) { return val1*val2; } static void Main(string[] args) {
    //Creating the Delegate Instance Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
    Console.Write("Please Enter Values");
    int v1 = Int32.Parse(Console.ReadLine()); int v2 = Int32.Parse(Console.ReadLine());
    //use a delegate for processing
    double res = delObj(v1,v2); Console.WriteLine ("Result :"+res); Console.ReadLine();
    } }

    Explanation:
    Here I have used a small program which demonstrates the use of delegate.
    The delegate "Delegate_Prod" is declared with double return type and which accepts only two interger parameters.
    Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and parameters type)
    Inside the Main method the delegate instance is created and the function name is passed to the delegae instace as following.
    Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
    After this we are accepting the two values from the user and passing those values to the delegate as we do using method .
    delObj(v1,v2);
    Here delegate object encapsulates the method functionalities and return the result as we specified in the method.
    Multicast DelegateIt is a Delegate which holds the reference of more than one methods.Multicast delegates must contain only methods that return void, else there is a run-time exception.
    Simple Program using Multicast Delegate

    delegate void Delegate_Multicast(int x, int y);
    Class Class2
    {static void Method1(int x, int y) { Console.WriteLine("You r in Method 1");}static void Method2(int x, int y) { Console.WriteLine("You r in Method 2");}public static void Main() { Delegate_Multicast func = new Delegate_Multicast(Method1);
    func += new Delegate_Multicast(Method2); func(1,2); // Method1 and Method2 are called func -= new Delegate_Multicast(Method1); func(2,3); // Only Method2 is called}
    }

    Explanation:
    In the above example you can see that two methods are defined named method1 and method2 whchi takes two integer parameters and return type as void.
    In the main method the Delegate object is created using the following statement
    Delegate_Multicast func = new Delegate_Multicast(Method1);
    Then the Delegate is added using the += operator and removed using -= operator.


  • Delegates example in c#


    Using a delegate to pass data between two forms

    Introduction

    This code demonstrates how you can pass data from one form to another using a delegate. The advantage of using a delegate is that the form from which you want to send the data, doesn't need to know anything about the form that it's sending its data to. This way, you can reuse the same form in other forms or applications.

    Details

    This is form 1. From this form we display form 2. And from form 2 we send a TextBox back to form 1.



    And the code for form 1:



    private void btnForm1_Click(object sender, System.EventArgs e)
    {
    // Create an instance of form 2
    Form2 form2 = new Form2();

    // Create an instance of the delegate
    form2.passControl = new Form2.PassControl(PassData);

    // Show form 2
    form2.Show();
    }

    private void PassData(object sender)
    {
    // Set de text of the textbox to the value of the textbox of form 2
    txtForm1.Text = ((TextBox)sender).Text;
    }

    Form 2 sends the TextBox back to form 1:



    public class Form2 : System.Windows.Forms.Form
    {
    // Define delegate
    public delegate void PassControl(object sender);

    // Create instance (null)
    public PassControl passControl;

    private void btnForm2_Click(object sender, System.EventArgs e)
    {
    if (passControl != null)
    {
    passControl(txtForm2);
    {
    this.Hide();
    }
    }

    Of course, using the delegate, you can not only send back the textbox, but other controls, variables or even the form itself, because they are all objects. I hope this is useful.



    Feb 15, 2008

    Temporary Tables in Sqlserver2000

    Temporary Tables
    The simple answer is yes you can. Let look at a simple CREATE TABLE statement: CREATE TABLE #Yaks (
    YakID int,
    YakName char(30) )
    You'll notice I prefixed the table with a pound sign (#). This tells SQL Server that this table is a local temporary table. This table is only visible to this session of SQL Server. When I close this session, the table will be automatically dropped. You can treat this table just like any other table with a few exceptions. The only real major one is that you can't have foreign key constraints on a temporary table. The others are covered in
    Books Online.
    Temporary tables are created in tempdb. If you run this query: CREATE TABLE #Yaks (
    YakID int,
    YakName char(30) )
    select name
    from tempdb..sysobjects
    where name like '#yak%'
    drop table #yaks
    You'll get something like this: name
    ------------------------------------------------------------------------------------
    #Yaks_________________________ . . . ___________________________________00000000001D
    (1 row(s) affected)
    except that I took about fifty underscores out to make it readable. SQL Server stores the object with a some type of unique number appended on the end of the name. It does all this for you automatically. You just have to refer to #Yaks in your code.
    If two different users both create a #Yaks table each will have their own copy of it. The exact same code will run properly on both connections. Any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temporary table and calls stored procedure B, then B will be able to use the temporary table that A created. It's generally considered good coding practice to explicitly drop every temporary table you create. If you are running scripts through SQL Server Management Studio or Query Analyzer the temporary tables are kept until you explicitly drop them or until you close the session.
    Now let's get back to your question. The best way to use a temporary table is to create it and then fill it with data. This goes something like this:CREATE TABLE #TibetanYaks(
    YakID int,
    YakName char(30) )
    INSERT INTO #TibetanYaks (YakID, YakName)
    SELECT YakID, YakName
    FROM dbo.Yaks
    WHERE YakType = 'Tibetan'
    -- Do some stuff with the table
    drop table #TibetanYaks
    Obviously, this DBA knows their yaks as they're selecting the famed Tibetan yaks, the Cadillac of yaks. Temporary tables are usually pretty quick. Since you are creating and deleting them on the fly, they are usually only cached in memory.
    Table Variables
    If you are using SQL Server 2000 or higher, you can take advantage of the new TABLE variable type. These are similar to temporary tables except with more flexibility and they always stay in memory. The code above using a table variable might look like this:DECLARE @TibetanYaks TABLE (
    YakID int,
    YakName char(30) )
    INSERT INTO @TibetanYaks (YakID, YakName)
    SELECT YakID, YakName
    FROM dbo.Yaks
    WHERE YakType = 'Tibetan'
    -- Do some stuff with the table
    Table variables don't need to be dropped when you are done with them.
    Which to Use
    If you have less than 100 rows generally use a table variable. Otherwise use a temporary table. This is because SQL Server won't create statistics on table variables.
    If you need to create indexes on it then you must use a temporary table.
    When using temporary tables always create them and create any indexes and then use them. This will help reduce recompilations. The impact of this is reduced starting in SQL Server 2005 but it's still a good idea.
    Answering the Question
    And all this brings us back to your question. The final answer to your question might look something like this: DECLARE @TibetanYaks TABLE (
    YakID int,
    YakName char(30) )
    INSERT INTO @TibetanYaks (YakID, YakName)
    SELECT YakID, YakName
    FROM dbo.Yaks
    WHERE YakType = 'Tibetan'
    UPDATE @TibetanYaks
    SET YakName = UPPER(YakName)
    SELECT *
    FROM @TibetanYaks
    Global Temporary Tables
    You can also create global temporary tables. These are named with two pound signs. For example, ##YakHerders is a global temporary table. Global temporary tables are visible to all SQL Server connections. When you create one of these, all the users can see it. These are rarely used in SQL Server.
    Summary
    That shows you an example of creating a temporary table, modifying it, and returning the values to the calling program. I hope this gives you what you were looking for.

    Faqs on asp.net - part1


    2.1 What is ASP.NET?
    ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications.
    For more details refer
    What is ASP.NET ASP.NET OverView

    2.2 Why does my ASP.NET file have multiple
    tag with runat=server?
    This means that ASP.Net is not properly registered with IIS. .Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe
    use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version. use the command: aspnet_regiis.exe -i ---> to install current asp.net version.

    For Windows Server 2003, you must use aspnet_regiis -i -enable This is because of the "Web Service Extensions" feature in IIS 6
    (if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly."
    2.3 How to find out what version of ASP.NET I am using on my machine?
    VB.NET

    Response.Write(System.Environment.Version.ToString() )

    C#
    Response.Write(System.Environment.Version.ToString() );


    2.4 Is it possible to pass a querystring from an .asp page to aspx page?
    Yes you can pass querystring from .asp to ASP.NET page .asp
    <%response.redirect "webform1.aspx?id=11"%>

    .aspxVB.NET
    Response.Write (Request("id").ToString ())

    C#
    Response.Write (Request["id"].ToString ());


    2.5 How to comment out ASP.NET Tags?


    2.6 What is a ViewState?
    In classic ASP, when a form is submitted the form values are cleared. In some cases the form is submitted with huge information. In such cases if the server comes back with error, one has to re-enter correct information in the form. But submitting clears up all form values. This happens as the site does not maintain any state (ViewState).
    In ASP .NET, when the form is submitted the form reappears in the browser with all form values. This is because ASP .NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a control.


    If you want to NOT maintain the ViewState, include the directive at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control. For more details refer The ASP.NET View State
    2.7 Where can I get the details on Migration of existing projects using various technologies to ASP.NET?
    Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration. Below are the Code Migration Assistants
    ASP to ASP.NET Migration Assistant PHP to ASP.NET Migration Assistant JSP to ASP.NET Migration Assistant Refer Migrating to ASP.Net
    2.8 What is the equivalent of date() and time() in ASP.NET?
    VB.NET
    System.DateTime.Now.ToShortDateString() System.DateTime.Now.ToShortTimeString()

    C#
    System.DateTime.Now.ToShortDateString(); System.DateTime.Now.ToShortTimeString();


    2.9 How to prevent a button from validating it's form?
    Set the CauseValidation property of the button control to False
    2.10 How to get the IP address of the host accessing my site?
    VB.NET
    Response.Write (Request.UserHostAddress.ToString ())

    C#
    Response.Write (Request.UserHostAddress.ToString ());


    2.11 How to access the Parameters passed in via the URL?
    Call the Request.QueryStringmethod passing in the key. The method will return the parameter value associated with that key. VB.NET
    Request.QueryString("id")

    C#
    Request.QueryString["id"];


    2.12 How to Set Focus to Web Form Controls By Using Client-Side Script?


    Refer Sample IE Code
    2.13 How to display a Wait page while a query is running?
    Refer Asynchronous Wait State Pattern in ASP.NET
    2.14 How to implement Form based Authentication in ASP.NET application?
    For
    VB.NET C#

    2.15 How to catch the 404 error in my web application and provide more useful information?
    In the global.asax Application_error Event write the following code
    VB.NET
    Dim ex As Exception = Server.GetLastError().GetBaseException() If TypeOf ex Is System.IO.FileNotFoundException Then 'your code 'Response.Redirect("err404.aspx") Else 'your code End If

    C#
    Exception ex = Server.GetLastError().GetBaseException(); if (ex.GetType() == typeof(System.IO.FileNotFoundException)) { //your code Response.Redirect ("err404.aspx"); } else { //your code }


    2.16 Is there a method similar to Response.Redirect that will send variables to the destination page other than using a query string or the post method?
    Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser doesn't update its history and if the user clicks Back, they go to the page previous to the source page.
    Another way to pass values is to use something like a LinkButton. It posts back to the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the target page you can read the Session values as required.
    Refer to Passing Values Between Web Forms Pages for more information.
    2.17 What are the differences between HTML versus Server Control?
    Refer
    ASP.NET Server Controls Recommendations Introduction to ASP.NET Server Controls

    2.18 How can I change the action of a form through code?
    You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.
    For work around refer to Paul Wilson's Multiple Forms and Non-PostBack Forms - Solution
    2.19 Is there any control that allows user to select a time from a clock - in other words is there a clock control?
    Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and DurationTextBox Controls
    2.20 How to Compare time?
    VB.NET
    Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t") Dim t2 As String = DateTime.Now.ToString("t") If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) <> than " & t2.ToString()) End If

    C#
    string t1 = DateTime.Parse("3:30 PM").ToString("t"); string t2 = DateTime.Now.ToString("t"); if (DateTime.Compare(DateTime.Parse (t1), DateTime.Parse (t2)) <> than " + t2.ToString()); }


    2.21 How To work with TimeSpan Class?
    VB.NET
    Dim adate As DateTime = DateTime.Parse("06/24/2003") Dim bdate As DateTime = DateTime.Parse("06/28/2003") Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks) Response.Write(ts.TotalDays & "
    ") Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.TotalSeconds & ":" & ts.TotalMilliseconds)

    C#
    DateTime adate = DateTime.Parse("06/24/2003"); DateTime bdate = DateTime.Parse("06/28/2003"); TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks); Response.Write(ts.TotalDays.ToString () + "
    "); Response.Write(ts.TotalHours.ToString() + ":" + ts.TotalMinutes.ToString() + ":" + ts.TotalSeconds.ToString() + ":" + ts.TotalMilliseconds.ToString() );


    2.22 Where can I get information on Cookies in ASP.NET?
    Refer Mike Pope's article Basics of Cookies in ASP.NET
    2.23 Does ASP.Net still recognize the global.asa file?
    ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the same - plus additional - functionality.
    2.24 How should I destroy my objects in ASP.Net?
    ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous versions of Active Server Pages. Link to more information: Element
    2.25 Are there resources online with tips on ASP to ASP.Net conversions?
    Microsoft has desiged The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.
    The following Code Migration Assistants are discussed in the link below.
    ASP to ASP.NET Migration Assistant PHP to ASP.NET Migration Assistant JSP to ASP.NET Migration Assistant Refer Migrating to ASP.Net Also refer:
    Microsoft's ASP to ASP.NET Code Migration Assistant John Peterson's article Microsoft's ASP to ASP.NET Migration Assistant Paolo Cavone's article From ASP to ASP.NET... Painlessly!

    2.26 How do I publish my ASP.NET application to my ISP's web server?
    Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio .NET, select the "Project Copy Project" menu. Then enter the URL and select the FrontPage web access method. The "Copy Project" feature copies all of the necessary files to your ISP's machine for your ASP.NET application to run.
    You can also FTP your files to your ISP web server. But you must know which files to upload. For more details refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on the Server Computer
    2.27 Why do i get error message "Could not load type" whenever I browse to my ASP.NET web site?
    Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual Studio .NET's "Build Build Solution" menu, or run the command line compiler.
    For more details refer PRB: "Could not load type" error message when you browse to .aspx page
    2.28 Will the WebMatrix SqlDataSourceControl work with a MySQL connection?
    SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity .For Connectivity with MySql refer Accessing MySQL Database with ASP.NET
    2.29 Can I combine classic ASP and ASP.NET pages?
    No. ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET won't share their session.
    2.30 What is the difference between src and Code-Behind?
    Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed. Many people prefer this since they don't have to manually worry about compiling and messing with dlls -- it just works. Of course, the source is now on the server, for anyone with access to the server -- but not just anyone on the web.
    CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better protected, although its always decompilable even then.
    2.31 How can I get the value of input box with type hidden in code-behind?
    You can set the runat= server for the hidden control and you can use ControlName.Value to get its value in CodeBehind file
    2.32 I have created a .NET user control page (.ascx) but I cannot compile and run it.
    User control (ascx) can't be run on it own, but you can drag it onto any web page (aspx) and then run it.
    2.33 What is a .resx file?
    The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. This is useful for localization. For more details refer Resources in .resx files
    2.34 Is it possible to use a style sheet class directly on a control instead of using inline or page-level formatting ?
    Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet.
    2.35 Can I recieve both HTML markup for page and code in the ASP.NET web page's source code portion in the Web browser?
    No. The Web browser receives only HTML markup. No source code or web control syntax is passed back to the web browser.
    2.36 Why can't I put where at the top of an ASPX file and write my server-side scripts in C ?
    The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler.
    2.37 ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why?
    Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager. Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left
    2.38 Why do I get error message "Error creating assembly manifest: Error reading key file 'key.snk' -- The system cannot find the file specified"?
    Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.


    2.39 How to get URL without querystring?
    VB.NET
    Dim stringUri As String = "http://www.funandtech.blogspot.com/?id=1&auid=16" Dim weburi As Uri = New Uri(stringUri) Dim query As String = weburi.Query Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length) Response.Write(weburl)

    C#
    string stringUri = "http://www.funandtech.blogspot.com/?id=1&auid=16"; Uri weburi = new Uri(stringUri); string query = weburi.Query; string weburl = stringUri.Substring(0, stringUri.Length - query.Length); Response.Write (weburl);


    2.40 What is the best way to output only time and not Date?
    Use DateTime as follows VB.NET
    Response.Write(DateTime.Now.ToString("hh:mm:ss"))

    C#
    Response.Write(DateTime.Now.ToString("hh:mm:ss"));


    2.41 Do I have to compile code if I am changing the content of my aspx.cs file?
    Yes if you have used Codebehind="my.aspx.cs". Not if you used src="my.aspx.cs" in your page declaration.
    2.42 How to grab the referring URL?
    VB.NET
    Response.Write ( Request.UrlReferrer.ToString())

    C#
    Response.Write ( Request.UrlReferrer.ToString());


    2.43 My ASP code gives an error "Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed" when changed to .aspx?

    2.58 How to validate that a string is a valid date?
    VB.NET
    Dim blnValid As Boolean = False Try DateTime.Parse(MyString) blnValid = True Catch blnValid = False End Try

    C#
    bool blnValid=false; try { DateTime.Parse(MyString); blnValid=true; } catch { blnValid=false; }



    2.59 Are namespaces and Class names Case Sensitive?
    Namespaces and Class names are case Sensitive. Namespaces imported using the @ Import Directive will cause an error if the correct case is not used.
    2.60 How to convert string to a DateTime and compare it with another DateTime?
    VB.NET
    Dim blntimeIsOk As Boolean = DateTime.Parse("15:00") < blntimeisok =" (DateTime.Parse(">2.61 How to get the url of page dynamically?
    Use Request.Url property
    2.62 How to convert user input in dMy format to Mdy?
    VB.NET
    Dim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing, System.Globalization.DateTimeStyles.None)

    C#
    DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"}, null,System.Globalization.DateTimeStyles.None);

    For more details refer DateTime.ParseExact
    2.63 When the User is prompted a File Download dialogbox, if the user selects "Save" then the "Save as" dialog box is displayed. Is there any way for me to retrieve the filename and directory path specified by the user on the File Download dialog box?
    Clients do not report information back about where the user selects to save the content, so there isn't an easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file path, and then you could specify the filename parameter for the content-disposition header. Still, the user is free to change that path when actually downloading.
    2.64 How to hide or show Controls in server side code?
    In any appropriate event write VB.NET
    TextBox1.Visible =not TextBox1.Visible

    C#
    TextBox1.Visible =!TextBox1.Visible ;


    2.65 How to check if the user is using a secure or non secure connection?
    The Request Object defines a Property called IsSecureConnection, that will indicate whether http:// or https:// has been used.
    2.66 Is it possible to write code in many languages in one ASP.NET project?
    You cannot write the code-behind files in different languages in the same project, but you can write the aspx pages and ascx controls in different languages.
    2.67 What is the difference between Response.Redirect() and Server.Transfer().
    Response.Redirect
    Transfers the page control to the other page, in other words it sends the request to the other page. Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302 response to the client, and the client goes where it's told. Server.Transfer Only transfers the execution to another page and during this you will see the URL of the old page since only execution is transfered to new page and not control. Occurs entirely on the server, no action is needed by the client Sometimes for performance reasons, the server method is more desirable
    2.68 How to get the hostname or IP address of the server?
    You can use either of these:
    HttpContext.Current.Server.MachineName HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] The first one should return the name of the machine, the second returns the local ip address. Note that name of the machine could be different than host, since your site could be using host headers
    2.69 What is the meaning of validateRequest=true in .net framework1.1?
    The value of validateRequest is set to 'true' by default, which means that the framework will automatically deny submission of the '<' and '>' characters.
    2.70 What is the different between <%# %>and <%= %>?
    The <%# %>is used for databinding where as <%= %>is used to output the result of an expression. The expression inside <%# %>will be executed only when you call the page's or control's DataBind method. The expression inside <%= %>will be executed and displayed as and when it appears in the page.
    2.71 What permissions do ASP.NET applications posses by default?
    By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the User Group.
    2.72 How can I specify the relative path for a file?
    Suppose you have following file hierarchy:
    default.aspx Admin/login.aspx Misc/testpage.aspx

    And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.aspx) file. Then you can use
    Response.Redirect ("../default.aspx") Response.Redirect ("../Misc/testpage.aspx")

    2.73 How can I specify the "upload a file" input textbox in a form to be read only so that the user can click on the browse button and pick a file but they cannot type anything into the textbox next to the browse button.

    2.74 How to change the Page Title dynamically?

    VB.NET
    'Declare Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl
    'In Page_Load Title1.InnerText ="Page 1"

    C#
    //Declare protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;
    //In Page_Load Title1.InnerText ="Page 1" ;

    2.75 Why do I get the error message "Object must implement IConvertible". How can I resolve it?
    The common cause for this error is specifying a control as a SqlParameter's Value instead of the control's text value. For example, if you write code as below you'll get the above error:
    VB.NET
    Dim nameParameter As SqlParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50) nameParameter.Value = txtName

    C#
    SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50); nameParameter.Value = txtName ;

    To resolve it, specify the control's Text property instead of the control itself.
    VB.NET
    nameParameter.Value = txtName.Text

    C#
    nameParameter.Value =txtName.Text;


    2.76 Why is default.aspx page not opened if i specify http://localhost. I am able to view this page if i hardcode it as http://localhost/default.aspx?
    If some other default page comes higher in the list, adjust the default.aspx to be the number one entry inside the IIS configuration. If you have multiple websites inside IIS, make sure the configuration is applied on the right website (or on all websites by applying the configuration on the server-level using the properties dialog, configure WWW service).
    2.77 Can ASP.NET work on an NT server?
    No. For more details refer ASP 1.1 version
    2.78 Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET?
    Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET
    2.79 How to automatically get the latest version of all the asp.net solution items from Source Safe when opening the solution?
    In VS.NET you can go to Tools > Options > Source Control > General and check the checkbox for Get everything when a solution opens. This retrieves the latest version of all solution items when you open the solution.
    2.80 How to convert the datetime into a string for use in the SQL ' statement?

    VB.NET
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then Dim cInfo As CultureInfo For Each cInfo In CultureInfo.GetCultures(CultureTypes.SpecificCultures) ddlCulture.Items.Add(cInfo.Name) Next End If End Sub
    Private Sub ddlCulture_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCulture.SelectedIndexChanged ' Get a CultureInfo object based on culture selection in dropdownlist Dim cInfo As CultureInfo = New CultureInfo(ddlCulture.SelectedItem.Text) ' Get a CultureInfo object based on Invariant culture Dim cInfoNeutral As CultureInfo = New CultureInfo("") ' Display the datetime based on the formatting of the selected culture TextBox1.Text = Convert.ToString(Now, cInfo.DateTimeFormat) ' Create a DateTime variable to hold the Invariant time Dim dt As DateTime dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat) 'Convert the datetime into a string for use in the SQL statement Label1.Text = "... WHERE ([Date] < '" & _ Convert.ToString(dt, cInfoNeutral.DateTimeFormat) & "')" End Sub C# private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { foreach(CultureInfo cInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { ddlCulture.Items.Add(cInfo.Name); } } } private void ddlCulture_SelectedIndexChanged(object sender, System.EventArgs e) { // Get a CultureInfo object based on culture selection in dropdownlist CultureInfo cInfo = new CultureInfo(ddlCulture.SelectedItem.Text); // Get a CultureInfo object based on Invariant culture CultureInfo cInfoNeutral = new CultureInfo(""); // Display the datetime based on the formatting of the selected culture TextBox1.Text = Convert.ToString(DateTime.Now , cInfo.DateTimeFormat); // Create a DateTime variable to hold the Invariant time DateTime dt ; dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat); //Convert the datetime into a string for use in the SQL statement Label1.Text = "... WHERE ([Date] < '" + Convert.ToString(dt, cInfoNeutral.DateTimeFormat) + "')"; } 2.81 How to make VS.Net use FlowLayout as the default layout rather than the GridLayout?
    For VB.NET, go to path C:\Program Files\Microsoft Visual Studio .NET\Vb7\VBWizards\WebForm\Templates\1033 Change the following line in the existing WebForm1.aspx


    to



    For C#, go to path C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033 Change the following line in the existing WebForm1.aspx

    to
    Note:Before changing any templates it's a good idea to make backup copies of them Or rather than above approach you can change the behavior for new files on a per project basis in Visual Studio by:
    Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and select "Properties". From project properties window, under Common Properties>Designer Defaults>Page Layout change "Grid" to "Flow".

    2.82 Can I use a DataReader to update/insert/delete a record?
    No. DataReader provides a means of reading a forward-only stream of rows from a database.
    2.83 What is the difference between Server.Transfer and Server.Execute?
    Server.Transfer is used to End the current webform and begin executing a new webform. This method works only when navigating to a Web Forms page (.aspx) Server.Execute is used to begin executing a new webform while still displaying the current web form. The contents of both forms are combined. This method works only when navigating to a webform page(.aspx)

    2.84 How to create a login screen in ASP.NET?
    Here is a sample login screen:


    VB.NET
    Dim myconnection As SqlConnection Dim mycmd As SqlCommand Dim strSql As String Dim myReader As SqlDataReader
    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click myconnection = New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;") strSql = "Select * from usertbl where username=" & "'" & txtUserName.Text & "'" & " and userpassword=" & "'" & txtPassword.Text & "'" mycmd = New SqlCommand(strSql, myconnection) myconnection.Open() myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection) If myReader.Read() Then Response.Write("Welcome") Else Response.Write("Access Denied") End If
    End Sub

    C#
    SqlConnection myconnection ; SqlCommand mycmd ; string strSql ; SqlDataReader myReader ; private void btnLogin_Click(object sender, System.EventArgs e) { myconnection = new SqlConnection("Server=localhost;uid=sa;password=;database=northwind;"); strSql = "Select * from usertbl where username=" + "'" + txtUserName.Text + "'" + " and userpassword=" + "'" + txtPassword.Text + "'"; mycmd = new SqlCommand(strSql, myconnection); myconnection.Open(); myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection); if (myReader.Read() ) { Response.Write("Welcome"); } else { Response.Write("Access Denied"); } }


    2.85 How to format a Telephone number in the xxx-xxx-xxxx format?
    VB.NET
    Dim Telno As Double = Double.Parse(ds.Tables(0).Rows(0)("TelNo").ToString()) Response.Write(Telno.ToString("###-###-####"))

    C#
    double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString()); Response.Write(Telno.ToString("###-###-####"));



    2.86 Can two different programming languages be mixed in a single ASPX file?
    No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived Page classes, and a given parser understands only one language
    2.87 Can I use custom .NET data types in a Web form?
    Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. This is also what happens when you add a custom control from the toolbox to your web form.
    2.88 How can I have a particular Web page in an ASP.NET application which displays its own error page.
    This can be done by setting the ErroPage attribute of Page Directive or ErrorPage property of Page Class to the desired Custom Error Page
    <%@Page Language="C#" ErrorPage="specificerropage.htm"%>

    In web.config
    No. The Web browser receives only HTML markup. No source code or web control syntax is passed back to the web browser.
    2.36 Why can't I put where at the top of an ASPX file and write my server-side scripts in C ?
    The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler.
    2.37 ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why?
    Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager. Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left
    2.38 Why do I get error message "Error creating assembly manifest: Error reading key file 'key.snk' -- The system cannot find the file specified"?
    Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.




    2.39 How to get URL without querystring?
    VB.NET
    Dim stringUri As String = "

    http://www.syncfusion.com/?id=1&auid=16" Dim weburi As Uri = New Uri(stringUri) Dim query As String = weburi.Query Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length) Response.Write(weburl)

    C#
    string stringUri = "
    http://www.syncfusion.com/?id=1&auid=16"; Uri weburi = new Uri(stringUri); string query = weburi.Query; string weburl = stringUri.Substring(0, stringUri.Length - query.Length); Response.Write (weburl);


    2.40 What is the best way to output only time and not Date?
    Use DateTime as follows VB.NET
    Response.Write(DateTime.Now.ToString("hh:mm:ss"))

    C#
    Response.Write(DateTime.Now.ToString("hh:mm:ss"));


    2.41 Do I have to compile code if I am changing the content of my aspx.cs file?
    Yes if you have used Codebehind="my.aspx.cs". Not if you used src="my.aspx.cs" in your page declaration.
    2.42 How to grab the referring URL?
    VB.NET
    Response.Write ( Request.UrlReferrer.ToString())

    C#
    Response.Write ( Request.UrlReferrer.ToString());


    2.43 My ASP code gives an error "Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed" when changed to .aspx?

    2.58 How to validate that a string is a valid date?
    VB.NET
    Dim blnValid As Boolean = False Try DateTime.Parse(MyString) blnValid = True Catch blnValid = False End Try

    C#
    bool blnValid=false; try { DateTime.Parse(MyString); blnValid=true; } catch { blnValid=false; }



    2.59 Are namespaces and Class names Case Sensitive?
    Namespaces and Class names are case Sensitive. Namespaces imported using the @ Import Directive will cause an error if the correct case is not used.
    2.60 How to convert string to a DateTime and compare it with another DateTime?
    VB.NET
    Dim blntimeIsOk As Boolean = DateTime.Parse("15:00") < blntimeisok =" (DateTime.Parse(">2.61 How to get the url of page dynamically?
    Use Request.Url property
    2.62 How to convert user input in dMy format to Mdy?
    VB.NET
    Dim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing, System.Globalization.DateTimeStyles.None)

    C#
    DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"}, null,System.Globalization.DateTimeStyles.None);

    For more details refer DateTime.ParseExact
    2.63 When the User is prompted a File Download dialogbox, if the user selects "Save" then the "Save as" dialog box is displayed. Is there any way for me to retrieve the filename and directory path specified by the user on the File Download dialog box?
    Clients do not report information back about where the user selects to save the content, so there isn't an easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file path, and then you could specify the filename parameter for the content-disposition header. Still, the user is free to change that path when actually downloading.
    2.64 How to hide or show Controls in server side code?
    In any appropriate event write VB.NET
    TextBox1.Visible =not TextBox1.Visible

    C#
    TextBox1.Visible =!TextBox1.Visible ;


    2.65 How to check if the user is using a secure or non secure connection?
    The Request Object defines a Property called IsSecureConnection, that will indicate whether http:// or https:// has been used.
    2.66 Is it possible to write code in many languages in one ASP.NET project?
    You cannot write the code-behind files in different languages in the same project, but you can write the aspx pages and ascx controls in different languages.
    2.67 What is the difference between Response.Redirect() and Server.Transfer().
    Response.Redirect
    Transfers the page control to the other page, in other words it sends the request to the other page. Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302 response to the client, and the client goes where it's told. Server.Transfer Only transfers the execution to another page and during this you will see the URL of the old page since only execution is transfered to new page and not control. Occurs entirely on the server, no action is needed by the client Sometimes for performance reasons, the server method is more desirable
    2.68 How to get the hostname or IP address of the server?
    You can use either of these:
    HttpContext.Current.Server.MachineName HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] The first one should return the name of the machine, the second returns the local ip address. Note that name of the machine could be different than host, since your site could be using host headers
    2.69 What is the meaning of validateRequest=true in .net framework1.1?
    The value of validateRequest is set to 'true' by default, which means that the framework will automatically deny submission of the '<' and '>' characters.
    2.70 What is the different between <%# %>and <%= %>?
    The <%# %>is used for databinding where as <%= %>is used to output the result of an expression. The expression inside <%# %>will be executed only when you call the page's or control's DataBind method. The expression inside <%= %>will be executed and displayed as and when it appears in the page.
    2.71 What permissions do ASP.NET applications posses by default?
    By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the User Group.
    2.72 How can I specify the relative path for a file?
    Suppose you have following file hierarchy:
    default.aspx Admin/login.aspx Misc/testpage.aspx

    And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.aspx) file. Then you can use
    Response.Redirect ("../default.aspx") Response.Redirect ("../Misc/testpage.aspx")

    2.73 How can I specify the "upload a file" input textbox in a form to be read only so that the user can click on the browse button and pick a file but they cannot type anything into the textbox next to the browse button.

    2.74 How to change the Page Title dynamically?

    VB.NET
    'Declare Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl
    'In Page_Load Title1.InnerText ="Page 1"

    C#
    //Declare protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;
    //In Page_Load Title1.InnerText ="Page 1" ;


    2.75 Why do I get the error message "Object must implement IConvertible". How can I resolve it?
    The common cause for this error is specifying a control as a SqlParameter's Value instead of the control's text value. For example, if you write code as below you'll get the above error:
    VB.NET
    Dim nameParameter As SqlParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50) nameParameter.Value = txtName

    C#
    SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50); nameParameter.Value = txtName ;

    To resolve it, specify the control's Text property instead of the control itself.
    VB.NET
    nameParameter.Value = txtName.Text

    C#
    nameParameter.Value =txtName.Text;


    2.76 Why is default.aspx page not opened if i specify
    http://localhost. I am able to view this page if i hardcode it as http://localhost/default.aspx

    ?
    If some other default page comes higher in the list, adjust the default.aspx to be the number one entry inside the IIS configuration. If you have multiple websites inside IIS, make sure the configuration is applied on the right website (or on all websites by applying the configuration on the server-level using the properties dialog, configure WWW service).
    2.77 Can ASP.NET work on an NT server?
    No. For more details refer ASP 1.1 version
    2.78 Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET?
    Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET
    2.79 How to automatically get the latest version of all the asp.net solution items from Source Safe when opening the solution?
    In VS.NET you can go to Tools > Options > Source Control > General and check the checkbox for Get everything when a solution opens. This retrieves the latest version of all solution items when you open the solution.
    2.80 How to convert the datetime into a string for use in the SQL ' statement?


    VB.NET
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then Dim cInfo As CultureInfo For Each cInfo In CultureInfo.GetCultures(CultureTypes.SpecificCultures) ddlCulture.Items.Add(cInfo.Name) Next End If End Sub
    Private Sub ddlCulture_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCulture.SelectedIndexChanged ' Get a CultureInfo object based on culture selection in dropdownlist Dim cInfo As CultureInfo = New CultureInfo(ddlCulture.SelectedItem.Text) ' Get a CultureInfo object based on Invariant culture Dim cInfoNeutral As CultureInfo = New CultureInfo("") ' Display the datetime based on the formatting of the selected culture TextBox1.Text = Convert.ToString(Now, cInfo.DateTimeFormat) ' Create a DateTime variable to hold the Invariant time Dim dt As DateTime dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat) 'Convert the datetime into a string for use in the SQL statement Label1.Text = "... WHERE ([Date] < '" & _ Convert.ToString(dt, cInfoNeutral.DateTimeFormat) & "')" End Sub C# private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { foreach(CultureInfo cInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { ddlCulture.Items.Add(cInfo.Name); } } } private void ddlCulture_SelectedIndexChanged(object sender, System.EventArgs e) { // Get a CultureInfo object based on culture selection in dropdownlist CultureInfo cInfo = new CultureInfo(ddlCulture.SelectedItem.Text); // Get a CultureInfo object based on Invariant culture CultureInfo cInfoNeutral = new CultureInfo(""); // Display the datetime based on the formatting of the selected culture TextBox1.Text = Convert.ToString(DateTime.Now , cInfo.DateTimeFormat); // Create a DateTime variable to hold the Invariant time DateTime dt ; dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat); //Convert the datetime into a string for use in the SQL statement Label1.Text = "... WHERE ([Date] < '" + Convert.ToString(dt, cInfoNeutral.DateTimeFormat) + "')"; } 2.81 How to make VS.Net use FlowLayout as the default layout rather than the GridLayout?
    For VB.NET, go to path C:\Program Files\Microsoft Visual Studio .NET\Vb7\VBWizards\WebForm\Templates\1033 Change the following line in the existing WebForm1.aspx


    to



    For C#, go to path C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033 Change the following line in the existing WebForm1.aspx


    to



    Note:Before changing any templates it's a good idea to make backup copies of them Or rather than above approach you can change the behavior for new files on a per project basis in Visual Studio by:
    Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and select "Properties". From project properties window, under Common Properties>Designer Defaults>Page Layout change "Grid" to "Flow".

    2.82 Can I use a DataReader to update/insert/delete a record?
    No. DataReader provides a means of reading a forward-only stream of rows from a database.
    2.83 What is the difference between Server.Transfer and Server.Execute?
    Server.Transfer is used to End the current webform and begin executing a new webform. This method works only when navigating to a Web Forms page (.aspx) Server.Execute is used to begin executing a new webform while still displaying the current web form. The contents of both forms are combined. This method works only when navigating to a webform page(.aspx)

    2.84 How to create a login screen in ASP.NET?
    Here is a sample login screen:



    VB.NET
    Dim myconnection As SqlConnection Dim mycmd As SqlCommand Dim strSql As String Dim myReader As SqlDataReader
    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click myconnection = New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;") strSql = "Select * from usertbl where username=" & "'" & txtUserName.Text & "'" & " and userpassword=" & "'" & txtPassword.Text & "'" mycmd = New SqlCommand(strSql, myconnection) myconnection.Open() myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection) If myReader.Read() Then Response.Write("Welcome") Else Response.Write("Access Denied") End If
    End Sub

    C#
    SqlConnection myconnection ; SqlCommand mycmd ; string strSql ; SqlDataReader myReader ; private void btnLogin_Click(object sender, System.EventArgs e) { myconnection = new SqlConnection("Server=localhost;uid=sa;password=;database=northwind;"); strSql = "Select * from usertbl where username=" + "'" + txtUserName.Text + "'" + " and userpassword=" + "'" + txtPassword.Text + "'"; mycmd = new SqlCommand(strSql, myconnection); myconnection.Open(); myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection); if (myReader.Read() ) { Response.Write("Welcome"); } else { Response.Write("Access Denied"); } }


    2.85 How to format a Telephone number in the xxx-xxx-xxxx format?
    VB.NET
    Dim Telno As Double = Double.Parse(ds.Tables(0).Rows(0)("TelNo").ToString()) Response.Write(Telno.ToString("###-###-####"))

    C#
    double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString()); Response.Write(Telno.ToString("###-###-####"));



    2.86 Can two different programming languages be mixed in a single ASPX file?
    No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived Page classes, and a given parser understands only one language
    2.87 Can I use custom .NET data types in a Web form?
    Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. This is also what happens when you add a custom control from the toolbox to your web form.
    2.88 How can I have a particular Web page in an ASP.NET application which displays its own error page.
    This can be done by setting the ErroPage attribute of Page Directive or ErrorPage property of Page Class to the desired Custom Error Page
    <
    %@Page Language="C#" ErrorPage="specificerropage.htm"%>

    In web.config