Subscribe For Free Updates!

We'll not spam mate! We promise.

Showing posts with label C # data base. Show all posts
Showing posts with label C # data base. Show all posts

Dec 23, 2012

ADO.Net Interview Questions

Views:

ADO.Net Interview Questions
To day i will share with you , ADO.net Important Questions which is normally Ask by the interviewer at the Time of Interview.


ADO.NET is the new database technology of the .NET (Dot Net) platform, and it builds on Microsoft ActiveX® Data Objects (ADO).
ADO is a language-neutral object model that is the keystone of Microsoft's Universal Data Access strategy.
ADO.NET is an integral part of the .NET Compact Framework, providing access to relational data, XML documents, and application data. ADO.NET supports a variety of development needs. You can create database-client applications and middle-tier business objects used by applications, tools, languages or Internet browsers.

Nov 24, 2012

Database is very slow, Why ?

Views:

Database is very slow, Why ?
To Day I will Explain you  Some Reasons, why a Data base Become slow (Normally When there is more Data).

In Student Life Projects we can not experience this kinds of issues because in student life Normally our Data Base may contain 10-30 tables maximum and Each table may contain 100-300 rows or above .Data base has no over head and we cannot experience Serious Issues.

But What Happen when there is a data base that may have at least 900-1000 table and each table may contain 10,000- 1,000,00 or above rows then we can Faces Serious issue like Data base is Slow....
Data base Performance is not good. Data retrieval time is too high and etc.

Following are some Issue which may Help you situation like above.

May 23, 2012

How to Make Back and Restore Data base

Views:

How to Make Back and Restore Data base
To day I show You how To

HOW TO MAKE DATA BASE BACKUP AND HOW TO RESTORE IT IN SQL SERVER Management Studio.

Normally Data back can be Done very easily but there is some Confusion in restoring the data base.
In previous post I show you how to connect Manage studio with Visual studio .

Following Step is Involve to take Back up of data base

First, you need to configure the Microsoft SQL Server Management Studio on your local machine. If you don’t have it, you can download it from the following location.



Step 1: Open your Microsoft SQL Server Management Studio, whichever you prefer, standard or express edition.
Step 2: Using your Database Username and Password, simply login to your MS SQL server database.
Step 3: Select the database >> Right-click >> Tasks >> Back Up [as shown in the image below]:
Backup MS SQL Server 2008 Database
Once you click on the “Backup” the following Backup Database window will appear [as shown in the image below]:
Backup MS SQL Server 2008 Database Folow Step 2
Step 4: Select the following options:
  1. Backup type: Full
  2. Under Destination, Backup to: Disk
Step 5: Now, by clicking on the “Add” button the following window will appear to select the path and file name for the database backup file [as shown in the image below]:
Backup MS SQL Server 2008 Database - Select Backup Destination
Step 6: Select the destination folder for the backup file and enter the “File name” with .bak extension [as shown in the image below]:
Backup MS SQL Server 2008 Database - Locate A Database Files

Make sure you place your MS SQL database .bak file under the MSSQL backup folder.
Step 7: Hit the OK button to finish the backup of your MS SQL Server 2008 Database. Upon the successful completion of database backup, the following confirmation window will appear with a message “The backup of database “yourdatabasename” completed successfully. [as shown in the image below]:
Backup MS SQL Server 2008 Database - Confirmation Screen
Following the above shown steps, you will be able to create a successful backup of your MS SQL Server 2008 Database into the desired folder.
How to Restore MS SQL Server 2008 Database Backup File ?
In order to restore a database from a backup file, follow the steps shown below:
Step 1: Open your Microsoft SQL Server Management Studio Express and connect to your database.
Step 2: Select the database >> Right-click >> Tasks >> Restore >> Database [as shown in the image below]:
Restore MS SQL Server 2008 Database
Step 3:  The following “Restore Database“ windows will appear. Select “From device” mentioned under the “Source for restore” and click the button infront of that to specify the file location [as shown in the image below]:
Restore MS SQL Server 2008 Database - Step 2
Step 4: Select the option “Backup media as File” and click on the Add button to add the backup file location [as shown in the image below]:
Restore MS SQL Server 2008 Database - Specify Backup
Step 5: Select the backup file you wish to restore and Hit the OK button [as shown in the image below]:
Restore MS SQL Server 2008 Database Locate The Backup File
That’s it! You will get the confirmation windows with a message “The restoration of database “yourdatabasename” completed successfully.” Now you know the procedure of backing up and restoring MS SQL Server 2008 Database.

VIDEO




Oct 7, 2011

How TO Get return value from stored procedure

Views:


Recently we changed our DAC layer from using inline SQL to stored procedures in the database. On some of these SQL, we did record deletion (usually only 1 record), and we just execute it via IDBCommand.ExecuteNonQuery() and then check the return value to see how many records were affected (which should be 1) for verification that the query actually does something. With the change to stored procedure, we just return 1 in the stored procedure if the delete is successful. However, the calling code then started to show these deletions as errors. Apparently ExecuteNonQuery only returns the number of affected rows on SELECT, INSERT and DELETE statements; for everything else it returns -1.  So I tried to figure out how to get a return value from a stored procedure. Let's assume a simplistic stored procedure as follows:
ALTER PROC ReturnOnly
AS
BEGIN
      RETURN 5
END
You can't use ExecuteScalar to get the returned value, and ExecuteNonQuery will always return -1.  To get the value back, you need to add a return value parameter to the command.  The name of the parameter is not important.  The code to get the value returned by that procedure will be as follows:
private int ExecuteStoredProcedure(string storedProcedureName)
{
   SqlConnection connection = new SqlConnection(connectionString);
   // Command - specify as StoredProcedure
   SqlCommand command = new SqlCommand(storedProcedureName, connection);
   command.CommandType = CommandType.StoredProcedure;
   // Return value as parameter
   SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
   returnValue.Direction = ParameterDirection.ReturnValue;
   command.Parameters.Add(returnValue);
    // Execute the stored procedure
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();
   return Convert.ToInt32(returnValue.Value);
}

Sep 28, 2011

How to reset the value of identity Column in SQL Server ?

Views:

Here’s a way to reset the value of the identity column in SQL Server . The scenario is explained below .
For example , when the table “Customers” has a identity column with the initial value of 1 and seed 1 .Each time when you start an App and perform an operation , you might want to delete  all the records
inside the table and perform the new inserts . ( Not the best of the methods , but the App had to do it ) .

Now Each time i wanted to have the identity value start from 1 .
The Delete statement alone is not enough to reset the identity value .
After the Deletion of the records we should execute the DBCC command along with the CHECKIDENT switch along with the table name and the seed value .
Like this
  1. DELETE FROM CUSTOMERS  
  2. DBCC CHECKIDENT (CUSTOMERS,RESEED, 0)  
Here comes a better approach , instead of using the DELETE and DBCC commands , the Truncate will do the job for you .
  1. TRUNCATE TABLE CUSTOMERS  
This will delete the records as well as reset the identity value :)

How to Insert Update Edit Delete Record in GridView

Views:

In this example i am going to describe how to Insert record or edit or delete record in GridView using SqlDataSource.

For inserting record, i've put textboxes in footer row of GridView using ItemTemplate and FooterTemaplete.




Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose new datasource
Select Database and click Ok
 
In next screen, Enter your SqlServer name , username and password and pick Database name from the dropdown , Test the connection
 
 
 In next screen, select the table name and fields , Click on Advance tab and check Generate Insert,Edit and Delete statements checkbox , alternatively you can specify your custom sql statements 
 
 
Click on ok to finish 
Check Enable Editing , enable deleting checkbox in gridView smart tag 
Now go to html source of page and define DatakeyNames field in gridview source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
</asp:GridView>
Remove the boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:CommandField ShowDeleteButton="True" 
                      ShowEditButton="True" />
    <asp:TemplateField HeaderText="ID" SortExpression="ID">
    <ItemTemplate>
    <asp:Label ID="lblID" runat="server" 
                          Text='<%#Eval("ID") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:Button ID="btnInsert" runat="server" 
                Text="Insert" CommandName="Add" />
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="FirstName" 
                       SortExpression="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblFirstName" runat="server" 
               Text='<%#Eval("FirstName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtFirstName" runat="server" 
                 Text='<%#Bind("FirstName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="LastName" 
                       SortExpression="LastName">
    <ItemTemplate>
    <asp:Label ID="lblLastName" runat="server" 
               Text='<%#Eval("LastName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLastName" runat="server" 
                 Text='<%#Bind("LastName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Department" 
                       SortExpression="Department">
    <ItemTemplate>
    <asp:Label ID="lblDepartment" runat="server" 
               Text='<%#Eval("Department") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtDepartmentName" runat="server" 
                 Text='<%#Bind("Department") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtDept" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="Location">
    <ItemTemplate>
    <asp:Label ID="lblLocation" runat="server" 
               Text='<%#Eval("Location") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLocation" runat="server" 
                 Text='<%#Bind("Location") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLoc" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DBConString%>"
DeleteCommand="DELETE FROM [Employees] WHERE [ID] = @ID" 
InsertCommand="INSERT INTO [Employees] ([FirstName], 
[LastName],[Department], [Location]) 
VALUES (@FirstName, @LastName, @Department, @Location)"
SelectCommand="SELECT [ID], [FirstName], [LastName], 
[Department], [Location] FROM [Employees]"
UpdateCommand="UPDATE [Employees] SET 
[FirstName] = @FirstName, [LastName] = @LastName, 
[Department] = @Department, [Location] = @Location 
WHERE [ID] = @ID" OnInserted="SqlDataSource1_Inserted">

<DeleteParameters>
    <asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
    <asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:Label ID="lblMessage" runat="server" 
           Font-Bold="True"></asp:Label><br />
</div>
</form>
Write this code in RowCommand Event of GridView in codebehind
C# code Behind
protected void GridView1_RowCommand
(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Add")
  {
   string strFirstName = ((TextBox)
   GridView1.FooterRow.FindControl("txtFname")).Text;

   string strLastName = 
   ((TextBox)GridView1.FooterRow.FindControl
                         ("txtLname")).Text;

   string strDepartment = 
   ((TextBox)GridView1.FooterRow.FindControl
                            ("txtDept")).Text;
   string strLocation = ((TextBox)GridView1.FooterRow.
                          FindControl("txtLoc")).Text;
   //SqlDataSource1.InsertParameters.Clear();
   //SqlDataSource1.InsertParameters.Add
                       //("FirstName", strFirstName);
   //SqlDataSource1.InsertParameters.Add
                          //("LastName", strLastName);
   //SqlDataSource1.InsertParameters.Add
                         //("Department", strDepartment);
   //SqlDataSource1.InsertParameters.Add
                              //("Location", strLocation);

  SqlDataSource1.InsertParameters["FirstName"].DefaultValue 
                                             = strFirstName;
  SqlDataSource1.InsertParameters["LastName"].DefaultValue 
                                             = strLastName;
  SqlDataSource1.InsertParameters["Department"].DefaultValue 
                                             = strDepartment;
  SqlDataSource1.InsertParameters["Location"].DefaultValue
                                            = strLocation;
  SqlDataSource1.Insert();
  }
}

VB.NET Code Behind

Protected Sub GridView1_RowCommand(ByVal sender As Object, 
                       ByVal e As GridViewCommandEventArgs)
        If e.CommandName = "Add" Then
            Dim strFirstName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtFname"), TextBox).Text()

            Dim strLastName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLname"), TextBox).Text()

            Dim strDepartment As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtDept"), TextBox).Text()
            Dim strLocation As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLoc"), TextBox).Text()

            'SqlDataSource1.InsertParameters.Clear();
            'SqlDataSource1.InsertParameters.Add
            '("FirstName", strFirstName);
            'SqlDataSource1.InsertParameters.Add
            '("LastName", strLastName);
            'SqlDataSource1.InsertParameters.Add
            '("Department", strDepartment);
            'SqlDataSource1.InsertParameters.Add
            '("Location", strLocation);

            SqlDataSource1.InsertParameters("FirstName").
            DefaultValue = strFirstName
            SqlDataSource1.InsertParameters("LastName").
            DefaultValue = strLastName
            SqlDataSource1.InsertParameters("Department").
            DefaultValue = strDepartment
            SqlDataSource1.InsertParameters("Location").
            DefaultValue = strLocation
            SqlDataSource1.Insert()
        End If
    End Sub

Download the sample code attached

FileUpload Controle in ASP.NET Save Images in Database C# VB.NET

Views:

In this example i am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.


Database is having a table named Images with three columns.
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of Image.
3. Image Image to store image in binary format.

After uploading and saving images in database, images are displayed in GridView.













Become a Fan

visual studio learn