Tuesday, February 15, 2011

How to create Stored Procedure in Visual Studio and C#

A stored procedure is code that is written in SQL and saved as part of a database. It is a
method stored in the database itself, and not in your program code; hence the term stored
procedure. table structure as:
Figure 1

























To create a stored procedure, right-click the Stored Procedure folder for the database
in Server Explorer and select Add New Stored Procedure. You'll see an editor appear with
skeleton code for a stored procedure. Modify the code so that it retrieves all of the data
from the Customer table, as shown in Listing. After modifying the template code,
click Save and you'll see the stored procedure appear in the Stored Procedures folder of
the database in Server Explorer.
Listing  Stored procedure example
ALTER PROCEDURE dbo.GetCustomers
    /*
    (
    @parameter1 int = 5,
    @parameter2 datatype OUTPUT
    )
    */
AS
declare @cust_count int
select @cust_count=count(*) from customer
if @cust_count >0
begin                                               /* begin of if statement */
select [Name] from customer
end  /* End of If Statement */
    /* SET NOCOUNT ON */
    RETURN
Listing  declares a variable named @cust_count and runs a select statement to
assign the number of customers, count(*), to @cust_count. If @cust_count is larger than 0,
there are customers and the stored procedure queries for customer names.
To execute this stored procedure, right-click the stored procedure in the database in
Server Explorer and click Execute. You'll see output similar to the following if there are
records in the customer table:
Running [dbo].[GetCustomers].
Name                                              
--------------------------------------------------
Niranjan                                          
Hari Om                                           
Jai                                               
Rinku                                             
Harmeet                                           
Sunny                                             
Vivek                                             
Shyam                                             
No rows affected.
(8 row(s) returned)
@RETURN_VALUE = 0
Finished running [dbo].[GetCustomers].
In addition to execution, you can debug the stored procedure in VS. To debug, set a
breakpoint on any line in the stored procedure, right-click the stored procedure in Server
Explorer, and select Step Into Stored Procedure or click ALT-F5.

Monday, February 14, 2011

How to find Nth maximum or minimum value in SQL Server

Create Database Details

 

use NIR

Go

Create table Employee

(

Eid int,

Name varchar(10),

Salary money

)

Go

 

Insert into Employee values (1,'hari',3500)

Insert into Employee values (2,'ram',2500)

Insert into Employee values (3,'jai',2500)

Insert into Employee values (4,'shree',5500)

Insert into Employee values (5,'amit',7500)

Insert into Employee values (6,'sunil',2400)

Go

 

Query that can find the employee with the maximum salary, would be:

 

select * from employee where salary =(select max(salary) from employee)

 

If the same syntax is applied to find out the 2nd or 3rd or 4th level of salary, the query would
become bit complex to understand. See the example below: 

 

look at the query that captures the Nth maximum value:

Select * From Employee E1 Where

    (N-1) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where

               E2.Salary > E1.Salary)

(Where N is the level of Salary to be determined)

by substituting a value for N i.e. 4,(Idea is to find the 4th maximum salary):

Select * From Employee E1 Where
    (4-1) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where
               E2.Salary > E1.Salary)

the above query works in the same manner in Oracle and Sybase as well. Applying the
same logic, to find out the first maximum salary the query would be:

Select * From Employee E1 Where

    (1-1) = (Select Count(Distinct(E2.Salary)) From Employee E2 Where

            E2.Salary > E1.Salary)

 

if you are able to understand this functionality, you can work out various other queries in the
same manner. For example..

You want 2nd smallest salary then change they symbol and the N value here as:

 

Select * from employee e1 where

(2-1)=(select count(distinct(e2.salary)) from employee e2 where

       E2.salary<e1.salary)

 

Here is another way to write query to find second highest value of a column in a table

 

select top 1 salary from employee

where salary< (select max(salary) from employee)

order by salary desc

 

or using aggregate functions as:

 

SELECT Max(salary) FROM employee

WHERE salary NOT IN (SELECT MAX(salary) FROM employee);

 

Or

SELECT max( value1) FROM val WHERE value1 NOT IN( SELECT max(value1)
FROM val );

 

------------------------------------------

We can avoid TOP by using DENSE_RANK() in SQL Server 2005/2008, If its SQL Server 2000 then N-1
is the best way.

LOWESE 3Rd Salary :
-------------------
;WITH CTEs
AS(SELECT DENSE_RANK() OVER(ORDER BY SALARY) 'Nth',* FROM SAMPLE1)

SELECT Names,Salary FROM CTEs WHERE Nth=3


HIGHEST 3Rd Salary :
-------------------
;WITH CTEs
AS(SELECT DENSE_RANK() OVER(ORDER BY SALARY DESC) 'Nth',* FROM SAMPLE1)

SELECT Names,Salary FROM CTEs WHERE Nth=3

 

 

Wednesday, February 9, 2011

Using Properties in .Net

Properties are class members that you use just like a field, but the difference is that you
can add specialized logic when reading from or writing to a property.example of a property,
"CurrentBalance"
C#:
public decimal CurrentBalance
{
get
{
return accountBalance;
}
set
{
if (value < 0)
{
// charge fee
}
accountBalance = value;
}
VB:
Public Property CurrentBalance() As Decimal
Get
Return accountBalance
End Get
Set(ByVal value As Decimal)
If value < 0 Then
' charge fee
End If
accountBalance = value
End Set
End Property
  • Properties have accessors, named get and set, that allow you to add special logic
    when the property is used.
  • When you read from a property, only the get accessor code executes
  • The set accessor code only executes when you assign a value to a property.
In the preceding example, the get accessor returns the value of currentBalance with no
modifications. If there were some logic to apply, like calculating interest in addition to the
current balance, the get accessor might have contained the logic for that calculation prior
to returning the value. The set accessor does have logic that checks the value to see if it is
less than zero, which could happen if a customer overdrew his or her account. If the value
is less than zero, then you could implement logic to charge the customer a fee for the
overdraft. The value keyword contains the value being assigned to the property, and the
previous set accessor assigns value to the accountBalance field. The following statement
from the Main method  reads from CurrentBalance, effectively executing the
get accessor, which returns the value of currentBalance:
C#:
Console.WriteLine("Balance: " + account.CurrentBalance);
VB:
Console.WriteLine("Balance: " & CurrentBalance)
Since the CurrentBalance property returns the value of the accountBalance field,
the Console.WriteLine statement will print the value read from CurrentBalance to the
command line.

Command Line Tools of .Net Framework 4.0

Assembly, Build, Deployment and Configuration Tools

Tools

Description

Al.exe (Assembly Linker) The Assembly Linker generates a file that has an assembly manifest from one or more files that are either modules or resource files.
Gacutil.exe (Global Assembly Cache Tool) The Global Assembly Cache tool allows you to view and manipulate the contents of the global assembly cache and download cache.
Ilasm.exe (MSIL Assembler) The MSIL Assembler generates a portable executable (PE) file from Microsoft intermediate language (MSIL)
Ildasm.exe (MSIL Disassembler) The MSIL Disassembler is a companion tool to the MSIL Assembler (Ilasm.exe). Ildasm.exe takes a portable executable (PE) file that contains Microsoft intermediate language (MSIL) code and creates a text file suitable as input to Ilasm.exe.
Installutil.exe (Installer Tool) The Installer tool is a command-line utility that allows you to install and uninstall server resources by executing the installer components in specified assemblies
Mage.exe (Manifest Generation and Editing Tool) and MageUI.exe The Manifest Generation and Editing Tool (Mage.exe) is a command-line tool that supports the creation and editing of application and deployment manifests.
Ngen.exe (Native Image Generator) The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer
Regasm.exe (Assembly Registration Tool) The Assembly Registration tool reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create .NET Framework classes transparently.
Regsvcs.exe (.NET Services Installation Tool)

The .NET Services Installation tool loads and registers an assembly, generates, registers, and installs a type library into a specified COM+ application and configures services that you have added programmatically to your class.

Resgen.exe (Resource File Generator) The Resource File Generator converts text (.txt or .restext) files and XML-based resource format (.resx) files to common language runtime binary (.resources) files that can be embedded in a runtime binary executable or compiled into satellite assemblies.
Storeadm.exe (Isolated Storage Tool) The Isolated Storage tool lists or removes all existing stores for the current user.

Security Tools

Tools

Description

Caspol.exe (Code Access Security Policy Tool) The Code Access Security (CAS) Policy tool (Caspol.exe) enables users and administrators to modify security policy for the machine policy level, the user policy level, and the enterprise policy level
Certmgr.exe (Certificate Manager Tool) Manages certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs).
Makecert.exe (Certificate Creation Tool) The Certificate Creation tool generates X.509 certificates for testing purposes only. It creates a public and private key pair for digital signatures and stores it in a certificate file
Mscorcfg.msc (.NET Framework Configuration Tool) The .NET Framework Configuration tool (Mscorcfg.msc) is a Microsoft Management Console (MMC) snap-in that enables you to manage and configure assemblies in the GAC and adjust code access security policy
Peverify.exe (PEVerify Tool) Helps you verify whether your Microsoft intermediate language (MSIL) code and associated metadata meet type safety requirements.
SignTool.exe (Sign Tool) Sign Tool is a command-line tool that digitally signs files, verifies signatures in files, and time-stamps files.
Sn.exe (Strong Name Tool) The Strong Name tool (Sn.exe) helps sign assemblies with strong names. Sn.exe provides options for key management, signature generation, and signature verification.

Debugging Tools

Tools

Description

Fuslogvw.exe (Assembly Binding Log Viewer) Displays information about assembly binds to help you diagnose why the .NET Framework cannot locate an assembly at run time.
MDbg.exe (.NET Framework Command-Line Debugger) and Sos.dll The NET Framework Command-Line Debugger helps tools vendors and application developers find and fix bugs in programs that target the .NET Framework common language runtime.

Interop Tools

Tools

Description

Tlbexp.exe (Type Library Exporter) The Type Library Exporter generates a type library that describes the types defined in a common language runtime assembly.
Tlbimp.exe (Type Library Importer) The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly

I

Thursday, February 3, 2011

Using ASP.NET With SQL Server

If you want to develop web sites with dynamic contents (eCommerce, bulletin boards, etc.), one of the
options is to MS SQL Server to store, modify, and get your data. Data access to SQL Servers is provided
in ASP.NET by ADO.NET. There are five steps in this area below.
 
Creating SQL Connection in .Net and Connection String description

We will use the System.Data.SqlClient and the System.Data namespaces of ADO.NET. The System.Data
contains basic enumerations and classes, which we will use below. The System.Data.SqlClient provides data
access to SQL servers such as MS SQL Server 2000 and higher. Add the next snippet to the beginning of
your code page in order to get easy access to their classes:

using System.Data;
using System.Data.SqlClient;

To begin "communications" with our server we should define the SqlConnection class, initialize a new instance
and set its connection string parameters. There is an example of a connection string below:

string Connection = "server=Niranjan-PC; uid=sa; pwd=sa; database=NIR; Connect Timeout=10000";

Let's understand what each parameter means:

Keyword Description
server The address of a SQL Server. If the server is on a same computer, where your website runs, define it as "local" or place dot (.). If the server is remote, define it as an IP address, a domain name or a netbios name (as in the example string) of the server.
Uid The login name, which is defined at your SQL Server to get access. Our login name is "sa".
Pwd The password, which is defined at your SQL Server to get access. Our password is "sa".
Database The database's name, which you connect to. Our database name is "NIR".
Connect timeout The time in milliseconds. When this time is over and the connection is not established, the timeout exception is thrown. This keyword is not necessary. In our case it equals 10,000 ms. Use so large timeouts when you request a lot of data from the server.

Pay attention: letters' case of the keywords has no matter.

We are ready to create an instance of the SQLConnection class:

SqlConnection DataConnection = new SqlConnection(Connection);

The connection is described; we will use it at next steps.

Execute "non-SELECT" statements

T-SQL "non-SELECT" statements begin with such keywords: INSERT, DELETE and UPDATE.
For example, there is a table, called "myTable", in our database:

myTable
Field
Description
Id
INT, Primary Key
Value
INT

Let's insert a row into it. We will use the SQLCommand class. Initialize a new instance of it with a string
of a T-SQL statement and our SQLConnection instance. Open the connection, execute the statement with
the ExecuteNonQuery method, which is used for "non-Select" statements and procedures, and close the
connection. Here is the code snippet for that:

// the string with T-SQL statement, pay attention: no semicolon at the end of //the statement
string Command = "INSERT INTO myTable VALUES (1,100)";
// create the SQLCommand instance
SQLCommand DataCommand = new SqlCommand(Command, DataConnection);
// open the connection with our database
DataCommand.Connection.Open();
// execute the statement and return the number of affected rows
int i = DataCommand.ExecuteNonQuery();
//close the connection
DataCommand.Connection.Close();

The "I" variable contains the number of affected rows. You will find out how to execute stored
procedures at the next step.

Execute created stored procedures from front end

For example, we have a stored procedure, called "myProc", which does something, and it has a list of
parameters:
 
myProc
Parameter
Description
@Id
Input, INT
@Value
Input, CHAR(10)
@Ret
Output, INT

You can execute it very easy, using the SQLCommand class. There are several differences between
executing "non-Select" statements and stored procedures. The command string contains the procedure's
name now. The CommandType Property has to be set asStoredProcedure (use the CommandType
enumeration), because the default is Text (T-SQL statement).

To create the parameter list we use the SQLParameter class. To set a type of parameters, we use the
SQLDbType enumeration. To set a direction of a parameter we use the ParameterDirection enumeration.
There is the snippet with comments below:

// create the SQLCommand instance with the name of the procedure and the //SQLConnection instance
SqlCommand execproc = new SqlCommand("myProc", DataConnection);
//Set the CommandType property to StoredProcedure. It is necessary in this
//case. The default is Text (T-SQL statement).

execproc.CommandType = CommandType.StoredProcedure;
//open our connection
execproc.Connection.Open();
//Add the parameter to parameters of the procedure with the required type
SqlParameter Param = execproc.Parameters.Add("@Id", SqlDbType.Int);
//Set the parameter`s value
Param.Value = 100;
//Add the next parameter, set its size to 10.
Param = execproc.Parameters.Add("@Value", SqlDbType.NChar, 10);
//Set the parameter`s value
Param.Value = "your_chars";
//Add the next parameter
Param = execproc.Parameters.Add("@Ret", SqlDbType.Int);
//Set the parameter`s value
Param.Value = null;
//Set the Direction property to Output. It is necessary in this case. The //default is Input
Param.Direction = ParameterDirection.Output;
// execute the procedure
execproc.ExecuteNonQuery();
// Get a value of â€Å“@Ret” (it is Output). Don`t forget cast the Value property //to a required type,
cause the Value property has the Object type.

int ret = (int)execproc.Parameters["@Ret"].Value;
//Close our connection
execproc.Connection.Close();

You will find out how to execute "SELECT" statements at the next step.

Execute "SELECT" statements

When we execute "SELECT" statements we get data tables from SQL Server. To provide this process,
we should use the DataSet class. It represents data tables which we will get from a server. The filling of
the DataSet is provided by the SQLDataAdapter class with using its Fill method. A constructor of this
class takes same arguments as the SQLCommand does. There is the snippet with comments below:

//Create the DataSet instance
DataSet ds = new DataSet();
//Assign the â€Å“select” statement string                          
string SelectCommand = "SELECT * FROM myTable WHERE Value = 100";
//Create the SQLDataAdapter instance
SqlDataAdapter DataCommand = new SqlDataAdapter(SelectCommand, DataConnection);
//Get data from a server and fill the DataSet 
DataCommand.Fill(ds);

Pay attention: it is not necessary to open connection "manually". The Fill method provides it automatically.

The "ds" contains findings now. You will find out how to process them at the next step.

Process findings

We have got the "ds" instance of the Dataset with findings at the previous step. So, we should process
them to display at our web site. The Dataset contains the Tables property. It is the collection of tables.
Findings are written to a zero-indexed table. We use two loops to seek all data. The first loop seeks
all rows in a table (DataRow instances); the embedded loop seeks all columns in a row
(DataColumn instances). You can get each element as DataRow[Datacolumn]. There is the snippet with
comments below:

// the main â€Å“foreach” loop seeks all rows in the table
foreach (DataRow row in ds.Tables[0])
    // the embedded &quotforeach" loop seeks all columns in a row
    foreach (DataColumn col in DataRow)
    {
        // do everything you want with row[col]
    }

it is all about using SQL Connection in .Net

Wednesday, February 2, 2011

Detect Browser Types, Browser Url and Browser Capabilities in ASP.NET

Query Browser property, which contains an object HttpBrowserCapabilities. This object gets information
from the browser or client device during an HTTP request, telling her request the type and level of support
offered by the
browser or client device. The object in turn, provides information on the browser capabilities
using strongly typed properties and a generic name-value dictionary.
 
private void btnCheckBrowser_Click (object sender, System.EventArgs e)
{
   
System.Web.HttpBrowserCapabilities browser = Request.Browser;
   
String s = "Browser Capabilities n \"
       
+ "Type =" + browser.Type + "\ n"
       
+ "Name =" + browser.Browser + "\ n"
       
+ "Version =" + browser.Version + "\ n"
       
+ "Major Version =" + browser.MajorVersion + "\ n"
       
+ "Minor Version =" + browser.MinorVersion + "\ n"
       
+ "Platform =" + browser.Platform + "\ n"
       
+ "Is Beta =" + browser.Beta + "\ n"
       
+ "Is string =" + browser.Crawler + "\ n"
       
+ "Is AOL =" + browser.AOL + "\ n"
       
+ "Is Win16 =" + browser.Win16 + "\ n"
       
+ "Is Win32 =" + browser.Win32 + "\ n"
       
+ "Supports Frames =" + browser.Frames + "\ n"
       
+ "Supports Tables =" + browser.Tables + "\ n"
       
+ "Supports Cookies =" + browser.Cookies + "\ n"
       
+ "Supports VBScript =" + browser.VBScript + "\ n"
       
+ "Supports JavaScript =" +
           
browser.EcmaScriptVersion.ToString () + "\ n"
       
+ "Supports Java Applets =" + browser.JavaApplets + "\ n"
       
+ "Supports ActiveX Controls =" + browser.ActiveXControls
             
+ "\ N"
       
+ "Compatible with the version of JavaScript =" +
           
browser ['JavaScriptVersion "] +" \ n ";

   
txtInfo.Text = s;
 
//Get the Brower Address Bar Url
 
Response.Write("<script>alert('"+Request.Url.ToString()+"')</script>");

}
 
NoteNote

The properties exposed by the HttpBrowserCapabilities object indicate inherent capabilities of the browser,
but do not necessarily reflect current browser settings. For example, the Cookies property indicates whether
a browser inherently supports cookies, but it does not indicate whether the browser that made the request has
cookies enabled.

 

String Conversion in Various DateTime Formats

DateTime Various Formats in C#

This example shows how to format DateTime using String.Format method. All formatting can be done also
using
DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24),
m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M)
and
z (time zone).

Following examples demonstrate how are the format specifiers rewritten to the output.

[C#]
// create date time 2008-03-09 16:05:07.123 DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);  year
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008"

month
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March"
day
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday"
hour 12/24
String.Format("{0:h hh H HH}", dt); // "4 04 16 16"

minute
String.Format("{0:m mm}", dt); // "5 05"
second
String.Format("{0:s ss}", dt); // "7 07"
sec.fraction
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230"
without zeroes
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" A.M. or P.M.
String.Format("{0:t tt}", dt); // "P PM"
time zone
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00"

You can use also date separator / (slash) and time sepatator : (colon). These characters will be
rewritten to characters defined in the current
DateTimeForma­tInfo.DateSepa­rator and
DateTimeForma­tInfo.TimeSepa­rator.

[C#]
// date separator in german culture is "." 
(so "/" changes to ".")
- english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);//"9/3/2008 16:05:07" - german (de-DE)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);//"9.3.2008 16:05:07"

Here are some examples of custom date and time formatting:

[C#]
// month/day numbers without/with leading zeroes String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008" String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"  // day/month names // "Sun, Mar 9, 2008"
String
.Format("{0:ddd, MMM d, yyyy}", dt);
// "Sunday, March 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // two/four digit year String.Format("{0:MM/dd/yy}", dt); // "03/09/08" String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property
ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for
de-DE culture.

Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture.
First column contains format specifiers for the
String.Format method.

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
    (*) = culture independent

Following examples show usage of standard format specifiers in String.Format method and the
resulting output.

[C#]
ShortTime
String
.Format("{0:t}", dt); // "4:05 PM"
ShortDate
String.Format("{0:d}", dt); // "3/9/2008"
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime String.Format("{0:m}", dt); // "March 09" MonthDay String.Format("{0:y}", dt); // "March, 2008" YearMonth String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123 String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime