Wednesday, 14 December 2011

How to import excel sheet into gridview using c# code in asp.net

.aspx page

  1. <table width="100%" cellpadding="0" cellspacing="0">  
  2.                     <tr>  
  3.                         <td align="left" class="text" style="width: 114px;">  
  4.                            Import Data from Excel File  
  5.                         </td>  
  6.                         <td align="left">  
  7.                             <asp:FileUpload ID="uploadExcel" runat="server" />  
  8.                             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
  9.                             <asp:Button ID="btnImport" runat="server" Text="Import Data" OnClick="btnImport_Click" />  
  10.                         </td>  
  11.                     </tr>  
  12.                     <tr>  
  13.                         <td>  
  14.                             <asp:GridView ID="GridView1" runat="server">  
  15.                                 <Columns>  
  16.                                     <asp:TemplateField HeaderText="First Name">  
  17.                                         <ItemTemplate>  
  18.                                             <asp:Label ID="lblFirstName" runat="server" Text='<%# Bind("first_name") %>'></asp:Label>  
  19.                                         </ItemTemplate>  
  20.                                         <ItemStyle HorizontalAlign="Left" />  
  21.                                     </asp:TemplateField>  
  22.                                     <asp:TemplateField  HeaderText="Last Name  
  23.                                         <ItemTemplate>  
  24.                                             <asp:Label ID="lblLastName" runat="server" Text='<%# Bind("last_name") %>'></asp:Label>  
  25.                                         </ItemTemplate>  
  26.                                         <ItemStyle HorizontalAlign="Left" />  
  27.                                     </asp:TemplateField>  
  28.                                     <asp:TemplateField  HeaderText="Gender">  
  29.                                         <ItemTemplate>  
  30.                                             <asp:Label ID="lblGender" runat="server" Text='<%# Bind("gender") %>'></asp:Label>  
  31.                                         </ItemTemplate>  
  32.                                         <ItemStyle HorizontalAlign="Center" />  
  33.                                     </asp:TemplateField>  
  34.                                 </Columns>  
  35.                             </asp:GridView>  
  36.                         </td>  
  37.                     </tr>  
  38.                 </table>  


.cs file code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web;  
  4. using System.Web.UI;  
  5. using System.Web.UI.WebControls;  
  6. using System.Data.OleDb;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.Data.Common;  
  10. using System.Configuration;  
  11.   
  12. protected void btnImport_Click(object sender, EventArgs e)  
  13.     {  
  14.         try  
  15.         {  
  16.             string path = uploadExcel.FileName;  
  17.             uploadExcel.SaveAs(Server.MapPath("~/Upload/" + path));  
  18.             OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0");                  
  19.             oconn.Open();      
  20. //Getting records from Sheet1 of excel file. As you know one excel file may have many sheets                      
  21.             OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);  
  22.             DataSet ds = new DataSet();  
  23.             OleDbDataAdapter odapt = new OleDbDataAdapter(ocmd);  
  24.             odapt.Fill(ds);  
  25.             GridView1.DataSource = ds;  
  26.             GridView1.DataBind();  
  27.             oconn.Close();              
  28.         }  
  29.         catch(Exception exp)  
  30.         {  
  31.             throw exp;  
  32.         }              
  33.     }  

Tuesday, 6 December 2011

SQL Server DO's and DON'Ts



So, you are now the leader of a SQL Server based project and this is your first one, perhaps migrating from Access. Or maybe you have performance problems with your SQL Server and don't know what to do next. Or maybe you simply want to know of some design guidelines for solutions using SQL Server and designingDatabase Access Layers (DAL): this article is for you.
Even if you are not using SQL Server, most of these design guidelines apply to other DBMS, too: Sybase is a very similar environment for the programmer, and Oracle designs may benefit from this too. I won't show here how to use specific T-SQL tricks, nor won't give you miracle solutions for your SQL Server problem. This is by no means a complete, closed issue. What I intend to do is give you some advices for a sound design, with lessons learned through the last years of my life, seeing the same design errors being done again and again.

DO know your tools.

Please, don't underestimate this tip. This is the best of all of those you'll see in this article. You'd be surprised of how many SQL Server programmers don't even know all T-SQL commands and all of those effective tools SQLServer has.
"What? I need to spend a month learning all those SQL commands I'll never use???" you might say. No, you don't need to. But spend a weekend at MSDN and browse through all T-SQL commands: the mission here is to learn a lot of what can and what can't be done. And, in the future, when designing a query, you'll remember "Hey, there's this command that does exactly what I need", and then you'll refer again to MSDN to see its exact syntax.
In this article I'll assume that you already know the T-SQL syntax or can find about it on MSDN.

DON'T use cursors

Let me say it again: DON'T use cursors. They should be your preferred way of killing the performance of an entire system. Most beginners use cursors and don't realize the performance hit they have. They use memory; they lock tables in weird ways, and they are slow. Worst of all, they defeat most of the performance optimization your DBA can do. Did you know that every FETCH being executed has about the same performance of executing a SELECT? This means that if your cursor has 10,000 records, it will execute about 10,000 SELECTs! If you can do this in a couple of SELECT, UPDATE or DELETE, it will be much faster.
Beginner SQL programmers find in cursors a comfortable and familiar way of coding. Well, unfortunately this lead to bad performance. The whole purpose of SQL is specifying what you want, not how it should be done.
I've once rewritten a cursor-based stored procedure and substituted some code for a pair of traditional SQLqueries. The table had only 100,000 records and the stored procedure used to take 40 minutes to process. You should see the face of the poor programmer when the new stored procedure took 10 seconds to run!
Sometimes it's even faster to create a small application that gets all the data, proccess it and update theserver. T-SQL was not done with loop performance in mind.
If you are reading this article, I need to mention: there is no good use for cursors; I have never seen cursors being well used, except for DBA work. And good DBAs, most of the time, know what they are doing. But, if you are reading this, you are not a DBA, right?

DO normalize your tables

There are two common excuses for not normalizing databases: performance and pure laziness. You'll pay for the second one sooner or later; and, about performance, don't optimize what's not slow. Often I see programmers de-normalizing databases because "this will be slow". And, more frequent than the inverse, the resulting design is slower. DBMSs were designed to be used with normalized databases, so design with normalization in mind.

DON'T SELECT *

This is hard to get used, I know. And I confess: often I use it; but try to specify only the columns you'll need. This will:
  1. Reduce memory consumption and network bandwidth
  2. Ease security design
  3. Gives the query optimizer a chance to read all the needed columns from the indexes

DO know how your data will be/is being acessed

A robust index design is one of the good things you can do for your database. And doing this is almost an art form. Everytime you add an index to a table, things get faster on SELECT, but INSERT and DELETE will be much slower. There's a lot of work in building and mantaining indexes. If you add several indexes to a table to speed your SELECT, you'll soon notice locks being held for a long time while updating indexes. So, the question is: what is being done with this table? Reading or Updating data? This question is tricky, specially with theDELETE and UPDATE, because they often involve a SELECT for the WHERE part and after this they update the table.

DON'T create an index on the "Sex" column

This is useless. First, let's understand how indexes speed up table access. You can see indexes as a way of quickly partitioning a table based on a criteria. If you create an index with a column like "Sex", you'll have only two partitions: Male and Female. What optimization will you have on a table with 1,000,000 rows? Remember, mantaining an index is slow. Always design your indexes with the most sparse columns first and the least sparse columns last, e.g, Name + Province + Sex.

DO use transactions

Specially on long-running queries. This will save you when things get wrong. Working with data for some time you'll soon discover some unexpected situation which will make your stored procured crash.

DO beware of deadlocks

Always access your tables on the same order. When working with stored procedures and transactions, you may find this soon. If you lock the table A then table B, always lock them in this very same order in all stored procedures. If you, by accident, lock the table B and then table A in another procedure some day you'll have a deadlock. Deadlocks can be tricky to find if the lock sequence is not carefully designed.

DON'T open large recordsets

A common request on programming forums is: "How can I quickly fill this combo with 100,00 items?". Well, this is an error. You can't and you shouldn't. First, your user will hate browsing through 100,000 records to find the right one. A better UI is needed here, because you should ideally show no more that 100 or 200 records to your users.

DON'T use server side cursors

Unless you know what your are doing. Client side cursors often (not always) put less overhead on the network and on the server, and reduce locking time.

DO use parametrized queries

Sometimes I see in programming forums, questions like: "My queries are failing with some chars, e.g. quotes. How can I avoid it?". And a common answer is: "Replace it by double quotes". Wrong. This is only a workaround and will still fail with other chars, and will introduce serious security bugs. Besides this, it will trash the SQL Servercaching system, which will cache several similar queries, instead of caching only one. Learn how to use parameterized queries (in ADO, through the use of the Command Object, or in ADO.NET the SqlCommand) and never have these problems again.

DO always test with large databases

It's a common pattern programmers developing with a small test database, and the end user using largedatabases. This is an error: disk is cheap, and performance problems will only be noticed when it's too late.

DON'T import bulk data with INSERT

Unless strictly necessary. Use DTS or the BCP utility and you'll have both a flexible and fast solution.

DO beware of timeouts

When querying a database, the default timeout is often low, like 15 seconds or 30 seconds. Remember that report queries may run longer than this, specially when your database grows.

DON'T ignore simultaneous editing

Sometimes two users will edit the same record at the same time. When writing, the last writer wins and some of the updates will be lost. It's easy to detect this situation: create a timestamp column and check it before you write. If possible, merge changes. If there is a conflict, prompt the user for some action.

DON'T do SELECT max(ID) from Master when inserting in a Detail table.

This is another common mistake, and will fail when two users are inserting data at the same time. Use one ofSCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY. Avoid @@IDENTITY if possible because it can introduce some nasty bugs with triggers.

DO Avoid NULLable columns

When possible. They consume an extra byte on each NULLable column in each row and have more overhead associated when querying data. The DAL will be harder to code, too, because everytime you access this column you'll need to check
I'm not saying that NULLs are the evil incarnation, like some people say. I believe they can have good uses and simplify coding when "missing data" is part of your business rules. But sometimes NULLable columns are used in situations like this:
CustomerName1
CustomerAddress1
CustomerEmail1
CustomerName2
CustomerAddress2
CustomerEmail3
CustomerName1
CustomerAddress2
CustomerEmail3
This is horrible. Please, don't do this, normalize your table. It will be more flexible and faster, and will reduce the NULLable columns.

DON'T use the TEXT datatype

Unless you are using it for really large data. The TEXT datatype is not flexible to query, is slow and wastes a lot of space if used incorrectly. Sometimes a VARCHAR will handle your data better.

DON'T use temporary tables

Unless strictly necessary. Often a subquery can substitute a temporary table. They induce overhead and will give you a big headache when programming under COM+ because it uses a database connection pool and temporary tables will last forever. In SQL Server 2000, there are alternatives like the TABLE data type which can provide in-memory solutions for small tables inside stored procedures too.

DO learn how to read a query execution plan

The SQL Server query analyzer is your friend, and you'll learn a lot of how it works and how the query and index design can affect performance through it.

DO use referential integrity

This can be a great time saver. Define all your keys, unique constraints and foreign keys. Every validation you create on the server will save you time in the future.

Selecting Rows Randomly from a Large Table


If you use Microsoft SQL Server 2000, you likely have run into the following problem: You want to select a random sampling of rows from a large table with lots of rows, but you are unsure of how to do so. Having a random sampling of rows can be useful when you want to make a smaller version of the table or if you want to troubleshoot a problem by seeing what kinds of rows are in the table.
To get a random sampling, you might be tempted to select the top n rows from the table. However, this sample is not random, and the first n rows are not necessarily representative of the whole table. Other solutions exist that involve adding columns to the tables; however, adding columns is not always possible or practical.
The standard way to grab random rows from a small table is to use a query such as the following:
  SELECT TOP 10 PERCENT *
  FROM Table1
  ORDER BY NEWID()

The key here is the NEWID function, which generates a globally unique identifier (GUID) in memory for each row. By definition, the GUID is unique and fairly random; so, when you sort by that GUID with theORDER BY clause, you get a random ordering of the rows in the table. Taking the top 10 percent (or whatever percentage you want) will give you a random sampling of the rows in the table.
Often, when questions about how to select random rows are asked in discussion groups, the NEWIDquery is proposed; it is simple and works very well for small tables. However, the NEWID query has a big drawback when you use it for large tables. The ORDER BY clause causes all of the rows in the table to be copied into the tempdb database, where they are sorted. This causes two problems:
  1. The sorting operation usually has a high cost associated with it. Sorting can use a lot of disk I/O and can run for a long time.
  2. In the worst-case scenario, tempdb can run out of space. In the best-case scenario, tempdb can take up a large amount of disk space that never will be reclaimed without a manual shrink command.

Monday, 5 December 2011

how to create sql server database table from c# code


Creating a database table.
private void CreateTableBtn_Click(object sender, System.EventArgs e)
{
// Open the connectionif( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString ="Integrated Security=SSPI;" +
"Initial Catalog=mydb;" +
"Data Source=localhost;";
conn.ConnectionString = ConnectionString;
conn.Open();
sql = "CREATE TABLE myTable"+
"(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY,"+
"myName CHAR(50), myAddress CHAR(255), myBalance FLOAT)" ;
cmd = new SqlCommand(sql, conn);
try{
cmd.ExecuteNonQuery();
// Adding records the tablesql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+
"VALUES (1001, 'Puneet Nehra', 'A 449 Sect 19, DELHI', 23.98 ) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+
"VALUES (1002, 'Anoop Singh', 'Lodi Road, DELHI', 353.64) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+
"VALUES (1003, 'Rakesh M', 'Nag Chowk, Jabalpur M.P.', 43.43) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) "+
"VALUES (1004, 'Madan Kesh', '4th Street, Lane 3, DELHI', 23.00) " ;
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch(SqlException ae)
{
MessageBox.Show(ae.Message.ToString());
}
}
As you can see from Listing 5, I also add data to the table using INSERT INTO SQL statement.
The CREATE PROCEDURE statement creates a stored procedure as you can see in Listing 10-18, I create a stored procedure myPoc which returs data result of SELECT myName and myAddress column.
Listing 5. Creating a stored procedure programmatically. 
Private void CreateSPBtn_Click(object sender, System.EventArgs e)
{
sql = "CREATE PROCEDURE myProc AS"+
" SELECT myName, myAddress FROM myTable GO";
ExecuteSQLStmt(sql);
}
Now I show you how to create views programmatically using CREATE VIEW SQL statement. As you can see from Listing 6, I create a view myView which is result of myName column rows from myTable.
Listing 6. Creating a view using CREATE VIEW
private void CreateViewBtn_Click(object sender, System.EventArgs e)
{
sql = "CREATE VIEW myView AS SELECT myName FROM myTable";
ExecuteSQLStmt(sql);
}
The ALTER TABLE is a useful SQL statement if you need to change your database schema programmatically. The ALTER TABLE statement can be used to add and remove new columns to a table, changing column properties, data types and constraints. The Listing 7 show that I change the database schema of myTable by first change column data type range from 50 to 100 characters and by adding a new column newCol of TIMESTAMP type.  
Listing 7. Using ALTER TABLE to change a database schema programmatically. 
Private void AlterTableBtn_Click(object sender, System.EventArgs e)
{
sql = "ALTER TABLE MyTable ALTER COLUMN"+
"myName CHAR(100) NOT NULL";
ExecuteSQLStmt(sql);
}

The new table schema looks like Table 2. 
Table 2. MyTable after ALTER TABLE
Column NameType               Size                         Property
myId                    integer4Primary Key
myNamechar 50Allow Null
myAddresschar255Allow Null
myBalance float8Allow Null
newColtimestamp 8Allow Null
You can also create other database object such as index, rule, and users. The code listed in Listing 8 creates one rule and index on myTable.
Note: Create Index can only create an index if you don't have an index on a table. Otherwise you will get an error message. 
Listing 8. Creating rules and indexes using SQL statement.

private void CreateOthersBtn_Click(object sender, System.EventArgs e)
{
sql = "CREATE UNIQUE CLUSTERED INDEX "+
"myIdx ON myTable(myName)";
ExecuteSQLStmt(sql);
sql = "CREATE RULE myRule "+
"AS @myBalance >= 32 AND @myBalance < 60";
ExecuteSQLStmt(sql);
}
The DROP TABLE command can be used to delete a table and its data permanently. The code listed in Listing 9 deletes myTable. 
Listing 9. Deleting table using DROP TABLE.
Private void DropTableBtn_Click(object sender, System.EventArgs e)
{
string sql = "DROP TABLE MyTable ";
ExecuteSQLStmt(sql);
}
Now next step is to view data from the table, view and stored procedure. The ViewDataBtn_Click method listed in Listing 10 shows the entire data from the table. The ViewSPBtn_Click and ViewViewBtn_Click methods view stored procedure and view data we have created earlier. As you can see using views and stored procedures work same as you use a SQL Statement. We have discussed working with Views and stored procedures in the beginning of this chapter. As you can see from Listing 10, 11, and 12, I view data from stored procedure and view.  
Listing 10. Viewing data from a database table.  
private void ViewDataBtn_Click(object sender, System.EventArgs e)
{
/// Open the connectionif( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString ="Integrated Security=SSPI;" +
"Initial Catalog=mydb;" +
"Data Source=localhost;";
conn.ConnectionString = ConnectionString;
conn.Open(); 
// Create a data adapterSqlDataAdapter da = new SqlDataAdapter
("SELECT * FROM myTable", conn); 
// Create DataSet, fill it and view in data gridDataSet ds = new DataSet("myTable");
da.Fill(ds, "myTable");
dataGrid1.DataSource = ds.Tables["myTable"].DefaultView;
}
Listing 11.Using a stored procedure to view data from a table.  
private void ViewSPBtn_Click(object sender, System.EventArgs e)
{ 
/// Open the connectionif( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString ="Integrated Security=SSPI;" +
"Initial Catalog=mydb;" +"Data Source=localhost;";
conn.ConnectionString = ConnectionString;
conn.Open(); 
// Create a data adapterSqlDataAdapter da = new SqlDataAdapter("myProc", conn); // Create DataSet, fill it and view in data gridDataSet ds = new DataSet("SP");
da.Fill(ds, "SP");
dataGrid1.DataSource = ds.DefaultViewManager;
}
Listing 12.Using a view to view data from a table.  
private void ViewViewBtn_Click(object sender, System.EventArgs e)
{ 
/// Open the connectionif( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString ="Integrated Security=SSPI;" +
"Initial Catalog=mydb;" +
"Data Source=localhost;";
conn.ConnectionString = ConnectionString;
conn.Open(); 
// Create a data adapterSqlDataAdapter da = new SqlDataAdapter
("SELECT * FROM myView", conn); 
// Create DataSet, fill it and view in data gridDataSet ds = new DataSet();
da.Fill(ds);
dataGrid1.DataSource = ds.DefaultViewManager;
}
Finally, I create AppExit method which releases the connection and reader objects and I call them from the Dispose method as you can see in Listing 13. 
Listing 13. AppExit method 
protected override void Dispose( bool disposing )
{
AppExit();
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
// Called when you are done with the applicaton// Or from Close buttonprivate void AppExit()
{
if (reader != null)
reader.Close();
if (conn.State == ConnectionState.Open)
conn.Close();
}

How to make web page to be printer friendly


As you can see, window.print() method will print everything in your page, including navigation or Print button. Because of that, possible solution is to have two versions of page, one for displaying on screen and second version for printing. Version for printing will not contain buttons or navigation, but only the report formated for printing. In this case, your print button will have HTML code like this:
<input type="button" value="Print" onclick="window.open('YourPrintPage.aspx')" />
Print button on first page only opens a new window and navigate to print version of the page. At the end of YourPrintPage.aspx, you can add javascript code for printing, like this:
<script language="javascript">
window.print();
</script>
This javascript will execute when page loads and you don't need any button on your printing version.
It is not just about hiding navigations, buttons and other unwanted elements. You need to use different metric units. For screen version it is best to use pixels to define size of fonts, tables, images etc., as you probably already do. But, for print version use points instead of pixels. For example:
body {
   font: 12pt;
}

Avoid "printer friendly" version of the same content

It is unnecessary to make another page just for printing. Instead of two versions of the same content, it is often better to solve print format problems with css styles and have only one page for both printing and showing on screen. Take a look at bellow html code snippet, you can place it inside page's <head> tag:
<LINK rel="stylesheet" href="style-for-screen.css" type="text/css" media="screen">
<LINK rel="stylesheet" href="style-for-print.css" type="text/css" media="print">
As you can see, there is media attribute inside the LINK tag. Web browser will use style-for-screen.css to show page on screen or style-for-print.css when print the page. Now you can simply hide elements like navigation, buttons etc. For example, let say your navigation menu is inside <div> tag with id = "navigation". To hide it, inside style-for-print.css file code should be:
#navigation { display : none }
Or, if you don't want to have two css files, you can do it all in one file, with code like this:
@media print
{
    /*****   Styles for print   ******/
      h1, h2, h3 {color:black;}
      #navigation {display:none}
}

@media screen {
      /*****   Styles for screen  ******/
}
Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft