Database connectivity using silverlight

Silverlight is a new cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and Rich Interactive Applications(RIA) for the web. It runs in all popular browsers, including Microsoft Internet Explorer, Mozilla Firefox, Apple Safari, Opera. The plugin required to run Silverlight is very small in size hence gets installed very quickly.

It is combination of different technolgoies into a single development platform that allows you to select tools and the programming language you want to use. Silverlight integrates seamlessly with your existing Javascript and ASP.NET AJAX code to complement functionality which you have already created.

Silverlight aims to compete with Adobe Flash and the presentation components of Ajax. It also competes with Sun Microsystems’ JavaFX, which was launched a few days after Silverlight.

In this article I m going to discuss how to do database connectivity and show data in DataGrid using Silverlight Enables Web Service.

As you all know just create a new project using Silverlight Application.

image1

Figure 1.

And by default “Add a new Web to the solution for hosting the control” radio button is checked. And click OK.

image2

Figure 2.

Add a new LINQ to SQL class in App_Code folder.

image3

Figure 3.

And using server explorer drag and drop your table in DataClass. And you will see like this.

image4

Figure 4.

Now add a new Silverlight-enabled WCF Service in Web Project.

image5

Figure 5.

Now let’s write some code on Service.cs. I am wriring all code here

using System;
using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.Collections.Generic;

using System.Text;

[ServiceContract(Namespace = “”)]

[AspNetCompatibilityRequirements(RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed)]

public class Service

{

[OperationContract]

public List<Vendor> GetVendors()

{

DataClassesDataContext db = new DataClassesDataContext();

var mVendors = from vendor in db.Vendors

select vendor;

return mVendors.ToList();

}

}

I am fetching all data from my Vendor table. You can put your condition according to your requirment.

NOTE – I am putting my database file in APP_Data folder. If you want use my Vendot data.

Now add service reference in References folder.

image6

Figure 6.

Now let’s drag and drop DataGrid on Page.xaml, and bind data using DisplayMemberBinding property.

<UserControl xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data” x:Class=”DatabaseConnectivity.Page”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

Width=”800″ Height=”300″ Loaded=”UserControl_Loaded”>

<Grid x:Name=”LayoutRoot” Background=”White” ShowGridLines=”True”>

<Grid.RowDefinitions>

<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”*” />

</Grid.ColumnDefinitions>

<my:DataGrid x:Name=”VendorDataGrid” AlternatingRowBackground=”Beige”

AutoGenerateColumns=”False”

Width=”800″ Height=”300″

Grid.Row=”1″ Grid.Column=”1″

CanUserResizeColumns=”True”>

<my:DataGrid.Columns>

<my:DataGridTextColumn Header=”VendorId” Width=”50″  DisplayMemberBinding=”{BindingVendorId}” FontSize=”11″ />

<my:DataGridTextColumn Header=”First Name” Width=”120″  DisplayMemberBinding=”{BindingVendorFName}” FontSize=”11″ />

<my:DataGridTextColumn Header=”Last Name” Width=”120″ DisplayMemberBinding=”{BindingVendorLName}” FontSize=”11″ />

<my:DataGridTextColumn Header=”City” Width=”120″ DisplayMemberBinding=”{BindingVendorCity}” FontSize=”11″ />

<my:DataGridTextColumn Header=”State” Width=”120″ DisplayMemberBinding=”{BindingVendorState}” FontSize=”11″ />

<my:DataGridTextColumn Header=”Country” Width=”120″ DisplayMemberBinding=”{BindingVendorCountry}” FontSize=”11″ />

<my:DataGridTextColumn Header=”Join Date” Width=”120″ DisplayMemberBinding=”{BindingPostedDate}” FontSize=”11″ />

</my:DataGrid.Columns>

</my:DataGrid>

</Grid>

</UserControl>
And this code on Page.xaml.cs

private void UserControl_Loaded(object sender, RoutedEventArgs e)

{

ServiceReference1.ServiceClient webService = new ServiceReference1.ServiceClient();

webService.GetVendorsCompleted += newEventHandler<DatabaseConnectivity.ServiceReference1.GetVendorsCompletedEventArgs>(webService_GetVendorsCompleted);

webService.GetVendorsAsync();

}

void webService_GetVendorsCompleted(Object sender, ServiceReference1.GetVendorsCompletedEventArgs e)

{

VendorDataGrid.ItemsSource = e.Result;

}

Now debug your project and you will get this error message.

image7

Figure 7.

For remove this error message you need to go in propery of Web Project and Do “Use Dyanamic Ports = False”.

image8

Figure 8.

And now set Web Project as startup project and TestPage as set as start page. And debug now. Result will look like this.

image9

Figure 9.

ListView Control in ASP.NET 3.5

The ListView is an extremely flexible data-bound control that renders its content based on the templates you define. Unlike the Repeater, the ListView adds higher level features such as selection and editing, which work in the same way as those in the GridView. But unlike the GridView, the ListView does’t support a field based model for creating quick and easy grids with a minimum of markup.

ListView is a new addition in ASP.NET 3.5. ListView can literally replace all other data binding controls in ASP.NET. ListView control makes data binding easier than previous controls. It has included styling with CSS, flexible pagination, and sorting, inserting, deleting, and updating features.

The most common reason for using the ListView is to create an unusual layout. For Example , to create a table that places more than one item in the same row, or to break free from table based rendering altogether. When building a page to display large amounts of data, ASP.NET developers usually turn to the GridView first and use the ListView in most specialized scenarios.

ListView Templates:

Templates control certain aspects of the ListView control’s generated HTML. Templates are required with ListView; they are optional with other data controls. These templates provide complete control over the output; that is, all aspects of the ListView’s generated markup are controlled via templates.

The following list offers details about the numerous templates available with ListView.

  1. AlternatingItemTemplate: Defines how alternating items are displayed.
  2. EditItemTemplate: Defines the presentation for an item when it is edited.
  3. EmptyDataTemplate: Specifies the content to display for empty individual items.
  4. EmptyItemTemplate: Specifies the content to display for empty group items.
  5. GroupSeparatorTemplate: Specifies the content to display between groups.
  6. GroupTemplate: Defines the content for groups. This template is a placeholder for the data displayed for individual group items (when data is grouped).
  7. InsertItemTemplate: Defines the presentation for a new item being inserted into the data set.
  8. ItemSeparatorTemplate: Defines the content to display between individual data items.
  9. ItemTemplate: Defines the data to display for single items.
  10. LayoutTemplate: Defines the main presentation features for the control. This root template contains placeholders that are replaced by what is defined by ItemTemplate and GroupTemplate.
  11. SelectedItemTemplate: Specifies the content to display when users select items.

In this article we will discuss features in ListView step by step.

  1. Data Binding
  2. Data Pager
  3. Add, Edit and Delete

In Data Binding we will bind ListView from database. To show data use ItemTemplate and AlternateItemTemplate show alternative row with different styles.

Data Binding –

AlternateItemTemplate & ItemTemplate :

<asp:ListView ID=”VendorListView” runat=”server” DataKeyNames=”VendorId”

DataSourceID=”SqlDataSource1″ onitemcommand=”VendorListView_ItemCommand”

onsorting=”VendorListView_Sorting” InsertItemPosition=”LastItem”>

<AlternatingItemTemplate>

<tr style=”background-color: #FFFFFF; color: #284775;”>

<td><asp:Label ID=”VendorIdLabel” runat=”server” Text='<%# Eval(“VendorId”)%>’ /></td>

<td><asp:Label ID=”VendorFNameLabel” runat=”server” Text='<%# Eval(“VendorFName”) %>’ /></td>

<td><asp:Label ID=”VendorLNameLabel” runat=”server” Text='<%# Eval(“VendorLName”) %>’ /></td>

<td><asp:Label ID=”VendorCityLabel” runat=”server” Text='<%# Eval(“VendorCity”) %>’ /></td>

<td><asp:Label ID=”VendorStateLabel” runat=”server” Text='<%# Eval(“VendorState”) %>’ /></td>

<td><asp:Label ID=”VendorCountryLabel” runat=”server” Text='<%# Eval(“VendorCountry”) %>’ /></td>

<td><asp:Label ID=”PostedDateLabel” runat=”server” Text='<%# Eval(“PostedDate”) %>’ /></td>

<td><asp:Label ID=”VendorDescriptionLabel” runat=”server” Text='<%# Eval(“VendorDescription”) %>’ /></td>

<td><asp:LinkButton ID=”LinkButtonEdit” runat=”server”CommandName=”Edit”>Edit</asp:LinkButton></td>

</tr>

</AlternatingItemTemplate>

<ItemTemplate>

<tr style=”background-color: #E0FFFF; color: #333333;”>

<td><asp:Label ID=”VendorIdLabel” runat=”server” Text='<%# Eval(“VendorId”)%>’ /></td>

<td><asp:Label ID=”VendorFNameLabel” runat=”server” Text='<%# Eval(“VendorFName”) %>’ /></td>

<td><asp:Label ID=”VendorLNameLabel” runat=”server” Text='<%# Eval(“VendorLName”) %>’ /></td>

<td><asp:Label ID=”VendorCityLabel” runat=”server” Text='<%# Eval(“VendorCity”) %>’ /></td>

<td><asp:Label ID=”VendorStateLabel” runat=”server” Text='<%# Eval(“VendorState”) %>’ /></td>

<td><asp:Label ID=”VendorCountryLabel” runat=”server” Text='<%# Eval(“VendorCountry”) %>’ /></td>

<td><asp:Label ID=”PostedDateLabel” runat=”server” Text='<%# Eval(“PostedDate”) %>’ /></td>

<td><asp:Label ID=”VendorDescriptionLabel” runat=”server” Text='<%# Eval(“VendorDescription”) %>’ /></td>

<td><asp:LinkButton ID=”LinkButtonEdit” runat=”server”CommandName=”Edit”>Edit</asp:LinkButton></td>

</tr>

</ItemTemplate>

</asp:ListView>

image1Figure 1.

Data Paging –

If you want to add Paging you have to use the new DataPager control. This control is a free standing control and what’s nice about it is that you can put it anywhere on the page – it doesn’t have to be directly visually associated with the control it’s actually doing the paging.

<tr runat=”server”>

<td runat=”server” style=”text-align: center; background-color: #5D7B9D; font-family: Verdana, Arial, Helvetica, sans-serif;

color: #FFFFFF”>

<asp:DataPager ID=”DataPager1″ runat=”server”>

<Fields>

<asp:NextPreviousPagerField ButtonType=”Button” ShowFirstPageButton=”True”ShowLastPageButton=”True” />

</Fields>

</asp:DataPager>

</td>

</tr>

image2

Figure 2.

Add, Edit and Delete:

The ListView also supports editing and adding of data via the EditItemTemplate and InsertItemTemplate. This functionality works very similar to the way it works in a GridView for editing, but it’s all done with custom templates:

This is .aspx code.

SQLDataSource :

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:VendorConnectionString %>”

SelectCommand=”SELECT [VendorId], [VendorFName], [VendorLName], [VendorCity], [VendorState], [VendorCountry], [PostedDate], [VendorDescription] FROM [Vendor]”>

</asp:SqlDataSource>

ListView :

<asp:ListView ID=”VendorListView” runat=”server” DataKeyNames=”VendorId”

DataSourceID=”SqlDataSource1″ onitemcommand=”VendorListView_ItemCommand”

onsorting=”VendorListView_Sorting” InsertItemPosition=”LastItem”>

<InsertItemTemplate>

<tr style=””>

<td></td>

<td><asp:TextBox ID=”TextBoxFName” Width=”100″ runat=”server” Text='<%# Bind(“VendorFName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxLName” Width=”100″  runat=”server” Text='<%# Bind(“VendorLName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCity” Width=”100″  runat=”server” Text='<%# Bind(“VendorCity”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxState” Width=”100″  runat=”server” Text='<%# Bind(“VendorState”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCountry” Width=”100″  runat=”server” Text='<%# Bind(“VendorCountry”) %>’ /></td>

<td></td>

<td><asp:TextBox ID=”TextBoxDescription” Width=”150″ TextMode=”MultiLine”runat=”server” Text='<%# Bind(“VendorDescription”) %>’ /></td>

<td><asp:Button ID=”ButtonInsert” runat=”server” CommandName=”Insert”Text=”Insert” /></td>

</tr>

</InsertItemTemplate>

<EditItemTemplate>

<tr style=”background-color: #999999;”>

<td><asp:TextBox ID=”TextBoxVendorId” Width=”100″   runat=”server” Text='<%# Bind(“VendorId”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxFName” Width=”100″  runat=”server” Text='<%# Bind(“VendorFName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxLName” Width=”100″  runat=”server” Text='<%# Bind(“VendorLName”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCity” Width=”100″  runat=”server” Text='<%# Bind(“VendorCity”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxState” Width=”100″  runat=”server” Text='<%# Bind(“VendorState”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxCountry” Width=”100″  runat=”server” Text='<%# Bind(“VendorCountry”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxPostedDate”  Width=”100″ runat=”server” Text='<%# Bind(“PostedDate”) %>’ /></td>

<td><asp:TextBox ID=”TextBoxDescription” TextMode=”MultiLine”  Width=”150″ runat=”server” Text='<%# Bind(“VendorDescription”) %>’ /></td>

<td>

<asp:LinkButton ID=”LinkButtonUpdate” runat=”server”CommandName=”Update”>Update</asp:LinkButton>

<asp:LinkButton ID=”LinkButtonDelete” runat=”server”CommandName=”Delete”>Delete</asp:LinkButton>

<asp:LinkButton ID=”LinkButtonCancel” runat=”server”CommandName=”Cancel”>Cancel</asp:LinkButton>

</td>

</tr>

</EditItemTemplate>

</asp:ListView>

.CS Code:

protected void VendorListView_ItemCommand(object sender, ListViewCommandEventArgs e)

{

if (e.CommandName == “Insert”)

{

TextBox TextBoxFName = (TextBox)e.Item.FindControl(“TextBoxFName”);

TextBox TextBoxLName = (TextBox)e.Item.FindControl(“TextBoxLName”);

TextBox TextBoxCity = (TextBox)e.Item.FindControl(“TextBoxCity”);

TextBox TextBoxState = (TextBox)e.Item.FindControl(“TextBoxState”);

TextBox TextBoxCountry = (TextBox)e.Item.FindControl(“TextBoxCountry”);

TextBox TextBoxDescription = (TextBox)e.Item.FindControl(“TextBoxDescription”);

string insertCommand = “INSERT INTO Vendor ([VendorFName],[VendorLName],[VendorCity],[VendorState],[VendorCountry], [VendorDescription]) VALUES(‘” + TextBoxFName.Text + “‘, ‘” + TextBoxLName.Text + “‘, ‘” + TextBoxCity.Text +”‘, ‘” + TextBoxState.Text + “‘, ‘” + TextBoxCountry.Text + “‘, ‘” + TextBoxDescription.Text + “‘);”;

SqlDataSource1.InsertCommand = insertCommand;

}

else if (e.CommandName == “Update”)

{

TextBox TextBoxVendorId = (TextBox)e.Item.FindControl(“TextBoxVendorId”);

TextBox TextBoxFName = (TextBox)e.Item.FindControl(“TextBoxFName”);

TextBox TextBoxLName = (TextBox)e.Item.FindControl(“TextBoxLName”);

TextBox TextBoxCity = (TextBox)e.Item.FindControl(“TextBoxCity”);

TextBox TextBoxState = (TextBox)e.Item.FindControl(“TextBoxState”);

TextBox TextBoxCountry = (TextBox)e.Item.FindControl(“TextBoxCountry”);

TextBox TextBoxPostedDate = (TextBox)e.Item.FindControl(“TextBoxPostedDate”);

TextBox TextBoxDescription = (TextBox)e.Item.FindControl(“TextBoxDescription”);

string updateCommand = “UPDATE [Vendor] set [VendorFName]='” + TextBoxFName.Text + “‘, [VendorLName]='” + TextBoxLName.Text + “‘, [VendorCity]='” + TextBoxCity.Text + “‘, [VendorState]='” + TextBoxState.Text + “‘, [VendorCountry]='” + TextBoxCountry.Text + “‘, [PostedDate] = ‘” + TextBoxPostedDate.Text + “‘, [VendorDescription] = ‘” + TextBoxDescription.Text + “‘ WHERE VendorId=” +Convert.ToInt32(TextBoxVendorId.Text) + “;”;

SqlDataSource1.UpdateCommand = updateCommand;

}

else if (e.CommandName == “Delete”)

{

TextBox TextBoxVendorId = (TextBox)e.Item.FindControl(“TextBoxVendorId”);

string deleteCommand = “DELETE FROM [Vendor] WHERE VendorId=” +Convert.ToInt32(TextBoxVendorId.Text);

SqlDataSource1.DeleteCommand = deleteCommand;

}

}

image3

Figure 3.

image4

Figure 4.

image5

Figure 5.

 

 

 

 

How to Enable Remote Connections in SQL Server 2005

First time when I tried to make remote connection, I got this error message.

“An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connection …?”

By default, SQL Server 2005 doesn’t allow remote connection so you have to enable it manually. If you try to connect to remote SQL Server without enable remote connection first. This is a security precautions that prevents other computers from connection to this instance of SQL Server before it has been properly secured. If you have seccessfully installed SQL Server 2005 and you want to allow other computers to be able to access your instance of database then you have to be enable remote connection in your system.

Here we go step by step, how to do enable remote connection.

  1. Use Surface Area Configuration Tool to enable remote connetion. See in snapshot how?

    What is Surface Area Configuration Tool?

    Microsoft SQL Server 2005 selectively installs and starts key services and features. This helps reduce the attackable surface area of a system. In the default configuration of new installations, many features are not enabled. A system administrator can change these defaults at installation time and also selectively enable or disable features of a running instance of SQL Server 2005.

    image11

  2. Now click on the Surface Area Configuration for Services and Connections.

    pic2

  3. Now click on SQLEXPRESS/Database Engine/RemoteConnections/ or MSSQLSERVER.
  4. Now enable Local and remote connections.
    pic3

Hope it will help.

How to Start and Stop Database Engine in SQL 2005

A service is a type of application (executable) that runs in the system background. Services usually provide core operating system features, such as Web serving, event logging, or file serving. Services can run without showing a user interface on the computer desktop. The SQL Server Database Engine, SQL Server Agent, and several other SQL Server components run as services. These services typically are started when the operating system starts. This depends on what is specified during setup; some services are not started by default.

This article describes the management of the various SQL Server services on your machine. Before you log in to an instance of SQL Server, you need to know how to start, stop, pause, resume, and restart an instance of SQL Server. After you are logged in, you can perform tasks such as administering the server or querying a database.

First of all make sure you have installed SQL Express in your system.  Also, make sure you are the admin on the server. After install SQL Express Server database server will start automatically each time you start your computer by default.

Let’s start now, select start/All Programs/Microsoft SQL Server2005/Configuration Tools/SQL Server Configuration Manager. It should look like Figure 1.

image1

Figure 1.

And you will see the Window in Figure 2. You can see all started and stopped services.

img5

Figure 2.

To start or stop a service, select the service in the right pane and use the buttons in the toolbar to start or stop the service.

If you want change start mode of any service then Click on the property on that service and click on service tab. Then you will see this window.  There are three start mode in a service.

image3

I hope this will help.

AutoComplete in ASP.NET using Ajax

Introduction:

AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup DropDown like list of words that begin with the prefix typed into the textbox.

Create a new website using ASP.NET Ajax-Enabled Web Site:
Now drag and drop three controls on page. ScriptManager, Textbox, AutoCompleteExtender.

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″%>

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

<div>

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<cc1:AutoCompleteExtender ID=”AutoCompleteExtender1″

runat=”server”

ServicePath=”WebService.asmx”

ServiceMethod=”FindName”

MinimumPrefixLength=”1″

TargetControlID=”TextBox1″>

</cc1:AutoCompleteExtender>

</div>

</form>

Now add a new WebService class:
Here is web service code.

Imports System

Imports System.Collections.Generic

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports System.Data.SqlClient

Imports System.Data

Imports System.Data.Common

Imports AtlasTextBoxAutoComplete.DL

Imports System.Collections

<WebService(Namespace:=”http://tempuri.org/&#8221;)> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<System.Web.Script.Services.ScriptService()> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class WebService

Inherits System.Web.Services.WebService

<WebMethod()> _

<System.Web.Script.Services.ScriptMethod()> _

Public Function FindName(ByVal prefixText As String, ByVal count As Integer) As String()

‘return all records whose Title starts with the prefix input string

Dim titleArList As New List(Of String)()

Dim drProducts As SqlDataReader = sqlProductProvider.GetNameList(prefixText)

While drProducts.Read()

Dim strTemp As String = Convert.ToString(drProducts(“Name”))

titleArList.Add(strTemp)

End While

Return titleArList.ToArray()

End Function

End Class

Result will look like this:


I am adding two classes in App_Code folder for database connectivity. You shoudl change your web.config key for database connection string. I am attaching my database in App_Code folder.

AJAX DragPanelExtender Control

Using DragPanel control, you can move your panel one place to another place in a Web page on client site. the web page. The DragPanelEtender control allows you to add drag and drop feature to your controls.

Here are two commong properties of

1 – TargetControlID – The ID of that Panel which should be drag.

2 – DragHandleID – The ID of a control that will serve as the “drag handle” for the panel. When the user clicks and drags this control, the panel will move.

.aspx code

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit”TagPrefix=”cc1″ %>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />

<br />

<cc1:DragPanelExtender ID=”DragPanelExtender1″

runat=”server” TargetControlID=”PanelContainer”

DragHandleID=”PanelBody”>

</cc1:DragPanelExtender>

<div>

<asp:Panel ID=”PanelContainer” runat=”server”CssClass=”dragContainer” Width=”215px” >

<asp:Panel ID=”PanelBody” runat=”server” CssClass=”dragBody”Width=”215px”>

<asp:GridView ID=”GridView1″ runat=”server”

AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1″

AllowPaging=”True” PageSize=”7″ CellPadding=”4″ForeColor=”#333333″

GridLines=”None” Width=”215px”>

<Columns>

<asp:BoundField DataField=”ContactName”HeaderText=”ContactName” SortExpression=”ContactName” />

</Columns>

<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True”ForeColor=”White” />

<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />

<EditRowStyle BackColor=”#999999″ />

<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True”ForeColor=”#333333″ />

<PagerStyle BackColor=”#284775″ ForeColor=”White”HorizontalAlign=”Center” />

<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True”ForeColor=”White” />

<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″/>

</asp:GridView>

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”ConnectionString=”<%$ ConnectionStrings:C:\USERS\MAHESH\DESKTOP\AUTOCOMPLETE_SRC\ATLASTEXTBOXAUTOCOMPLETE\APP_DATA\NORTHWND.MDFConnectionString%>”

SelectCommand=”SELECT [CompanyName], [ContactName], [Address], [City], [Country] FROM [Customers]”>

</asp:SqlDataSource>

</asp:Panel>

</asp:Panel>

</div>

</form>

<script type=”text/javascript”>

function setBodyHeightToContentHeight() {

document.body.style.height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)+”px”;

}

setBodyHeightToContentHeight();

window.attachEvent(‘onresize’, setBodyHeightToContentHeight);

</script>

NOTE: In the above code, make sure to change your connection string.

DetailsView Rich Data Control

Introduction:

In this article we are going to discuss about DetailsView data control.  In ASP.NET 2.0, DetailsView is a data-bound control that renders a single record at a time from its associated data source. It can optionally provide paging buttons to navigate between records, and a command bar to execute basic operations on the current record (Insert, Update, Delete). DetailsView generates a user interface similar to the Form View of a Microsoft Access database, and is typically used for updating/deleting any currently displayed record or for inserting new records.  The difference between the DetailsView and FormView is their support for templates. The DetailsView is build out of field objects, in the same way that the Grid View is build out of column objects.

You can configure the DetailsView control to display a Delete and an Insert button so that you can delete the corresponding data record from the data source or insert a new data record. Similar to the AutoGenerateInsertButton property, when the  AutoGenerateInsertButton property is set to true on the DetaillsView control, it renders a New button. When the New button is clicked, the DetaillsView control’s CurrentMode property changes to Insert. The DetaillsView control renders appropriate UI input controls for each bound field, unless the InsertVisible property of the bound field is set to false.

I am going to show use of all command bar in details.

NOTE I am using northwind database for this sample.

1

Figure 1: is showing one records at a time and paging is enabled.

2

Figure 2: when click on new command bar then should be look like this. Here you can insert record in database.

3

Figure 3: You can update existing record using update command bar.

So don’t you think it’s very useful control. I did not write one like code during insert, delete, update. For more information I am writing .aspx page code and attaching my sample application you need to only change connection string in web.config. And I am using SqlDataSource. You can use whatever you want according to your need.

. aspx code

DetailsView:

<asp:DetailsView ID=”DetailsView1″ runat=”server” Height=”50px”

Width=”532px” AllowPaging=”True” AutoGenerateRows=”False”

CellPadding=”4″ DataKeyNames=”EmployeeID” DataSourceID=”SqlDataSource1″

ForeColor=”#333333″ GridLines=”None” AutoGenerateDeleteButton=”True”

AutoGenerateEditButton=”True” AutoGenerateInsertButton=”True”>

<FooterStyle BackColor=”#990000″ Font-Bold=”True” ForeColor=”White” />

<CommandRowStyle BackColor=”#FFFFC0″ Font-Bold=”True” />

<RowStyle BackColor=”#FFFBD6″ ForeColor=”#333333″ />

<PagerStyle BackColor=”#FFCC66″ Font-Names=”Georgia” Font-Size=”Medium”ForeColor=”#333333″

HorizontalAlign=”Center” />

<Fields>

<asp:BoundField DataField=”EmployeeID” HeaderText=”EmployeeID”InsertVisible=”False” ReadOnly=”True” SortExpression=”EmployeeID” />

<asp:BoundField DataField=”LastName” HeaderText=”LastName”SortExpression=”LastName” />

<asp:BoundField DataField=”FirstName” HeaderText=”FirstName”SortExpression=”FirstName” />

<asp:BoundField DataField=”Title” HeaderText=”Title” SortExpression=”Title” />

<asp:BoundField DataField=”TitleOfCourtesy” HeaderText=”TitleOfCourtesy”SortExpression=”TitleOfCourtesy” />

<asp:BoundField DataField=”BirthDate” HeaderText=”BirthDate”SortExpression=”BirthDate” />

<asp:BoundField DataField=”HireDate” HeaderText=”HireDate” SortExpression=”HireDate”/>

<asp:BoundField DataField=”Address” HeaderText=”Address” SortExpression=”Address”/>

<asp:BoundField DataField=”City” HeaderText=”City” SortExpression=”City” />

<asp:BoundField DataField=”Region” HeaderText=”Region” SortExpression=”Region” />

<asp:BoundField DataField=”PostalCode” HeaderText=”PostalCode”SortExpression=”PostalCode” />

<asp:BoundField DataField=”Country” HeaderText=”Country” SortExpression=”Country” />

<asp:BoundField DataField=”HomePhone” HeaderText=”HomePhone”SortExpression=”HomePhone” />

<asp:BoundField DataField=”Extension” HeaderText=”Extension”SortExpression=”Extension” />

<asp:BoundField DataField=”Notes” HeaderText=”Notes” SortExpression=”Notes” />

</Fields>

<FieldHeaderStyle BackColor=”#FFFF99″ Font-Bold=”True” />

<HeaderStyle BackColor=”#990000″ Font-Bold=”True” Font-Names=”Georgia”ForeColor=”White” />

<AlternatingRowStyle BackColor=”White” />

<EditRowStyle Font-Names=”Georgia” Font-Size=”Small” />

</asp:DetailsView>

SqlDataSource:

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:NorthwindConnectionString %>”

SelectCommand=”SELECT * FROM [Employees] ORDER BY [EmployeeID]”

DeleteCommand=”DELETE FROM [Employees] WHERE EmployeeID = @EmployeeID”

InsertCommand = “INSERT INTO [Employees] ([LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City],[Region], [PostalCode], [Country], [HomePhone], [Extension], [Notes]) VALUES (@LastName, @FirstName, @Title, @TitleOfCourtesy, @BirthDate, @HireDate, @Address, @City, @Region, @PostalCode, @Country, @HomePhone, @Extension, @Notes)”

UpdateCommand = “UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Title] = @Title, [TitleOfCourtesy] = @TitleOfCourtesy, [BirthDate] = @BirthDate, [HireDate] = @HireDate,[Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country, [HomePhone] = @HomePhone, [Extension] = @Extension, [Notes] = @Notes  WHERE [EmployeeID] = @EmployeeID”>

<DeleteParameters>

<asp:Parameter Name=”EmployeeID” Type=”int32″  />

</DeleteParameters>

<InsertParameters>

<asp:Parameter Name=”LastName” Type=”String”  />

<asp:Parameter Name=”FirstName” Type=”String”  />

<asp:Parameter Name=”Title” Type=”String”  />

<asp:Parameter Name=”TitleOfCourtesy” Type=”String”  />

<asp:Parameter Name=”BirthDate” Type=”datetime”  />

<asp:Parameter Name=”HireDate” Type=”datetime”  />

<asp:Parameter Name=”Address” Type=”String”  />

<asp:Parameter Name=”City” Type=”String”  />

<asp:Parameter Name=”Region” Type=”String”  />

<asp:Parameter Name=”PostalCode” Type=”String”  />

<asp:Parameter Name=”Country” Type=”String”  />

<asp:Parameter Name=”HomePhone” Type=”String”  />

<asp:Parameter Name=”Extension” Type=”String”  />

<asp:Parameter Name=”Notes” Type=”String”  />

<asp:Parameter Name=”ReportsTo” Type=”int32″  />

<asp:Parameter Name=”PhotoPath” Type=”String”  />

</InsertParameters>

<UpdateParameters>

<asp:Parameter Name=”EmployeeID” Type=”int32″  />

<asp:Parameter Name=”LastName” Type=”String”  />

<asp:Parameter Name=”FirstName” Type=”String”  />

<asp:Parameter Name=”Title” Type=”String”  />

<asp:Parameter Name=”TitleOfCourtesy” Type=”String”  />

<asp:Parameter Name=”BirthDate” Type=”datetime”  />

<asp:Parameter Name=”HireDate” Type=”datetime”  />

<asp:Parameter Name=”Address” Type=”String”  />

<asp:Parameter Name=”City” Type=”String”  />

<asp:Parameter Name=”Region” Type=”String”  />

<asp:Parameter Name=”PostalCode” Type=”String”  />

<asp:Parameter Name=”Country” Type=”String”  />

<asp:Parameter Name=”HomePhone” Type=”String”  />

<asp:Parameter Name=”Extension” Type=”String”  />

<asp:Parameter Name=”Notes” Type=”String”  />

<asp:Parameter Name=”ReportsTo” Type=”int32″  />

<asp:Parameter Name=”PhotoPath” Type=”String”  />

</UpdateParameters>

</asp:SqlDataSource>

So what are you waiting for just implement this control.

Ajax AnimationExtender Control

In this article we are going to discuss about AJAX AnimationExtender control.

If you want to use animation to the web pages, then you have to use AnimationExtender control. It provides good animation effect such as moving an ASP Control to a new place, resizing it, modifying its color, or making it fade in or fade out. In this article I m going to use fade in or fade out animation.

The animation behavior can be applied with the following extender (the italic properties are optional, and the ellipses represent a generic animation description

TargetControlID: ID of the target control whose events are used to animate (this is also the default target of the animations)

OnLoad: Generic animation played as soon as the page is loaded.

OnClick: Generic animation played when the target control is clicked.

OnMouseOver: Generic animation played when the mouse moves over the target control.

OnMouseOut: Generic animation played when the mouse moves out of the target control.

OnHoverOver: Generic animation similar to OnMouseOver except it will stop the OnHoverOut animation before it plays.

OnHoverOut: Generic animation similar to OnMouseOut except it will stop the OnHoverOver animation before it plays.

First of all make a new website using Ajax Enabled website. The advantage to using Ajax enabled website is no need to add ScriptManager control on page and no need to add Ajax Control toolkit. Like this:

First of all drag and drop Animation control on page.

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″%>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
<cc1:AnimationExtender ID=”AnimationExtender1″ runat=”server” TargetControlID=”Image1″>
<Animations>
<OnLoad>
<FadeOut Duration=”.5″ MinimumOpacity=”.2″ MaximumOpacity=”1″ />
</OnLoad>
<OnHoverOut>
<Sequence>
<FadeOut Duration=”.5″ MinimumOpacity=”.2″ MaximumOpacity=”1″ />
</Sequence>
</OnHoverOut>
<OnHoverOver>
<FadeIn Duration=”.5″ MinimumOpacity=”.2″ MaximumOpacity=”1″ />
</OnHoverOver>
</Animations>
</cc1:AnimationExtender>
<asp:Image runat=”server” ID=”Image1″ ImageUrl=”~/Sunset.jpg” BorderWidth=”0px”Width=”342px” />

After running result should be look like this:



Now check result on MouseHover on this picture. Result should be look like this:

Database Connectivity using WebService

Introduction:

This article shows how to use Web Service and how to get data from database using Web Service. The Web Service behavior enables a client-side script to invoke remote methods exposed by Web Services or other web servers that support the SOAP and Web Services Description Language (WSDL) 1.1. This behavior provides developers the opportunity to use and leverage SOAP without requiring expert knowledge of its implementation. The Web Service behavior supports the use of a wide variety of data types, including intrinsic SOAP data types, arrays, objects and XML data.

Web Services have Two Uses:

Reusable application components
Web Services can offer application components as services such as currency conversion, weather reports or even language translation.

Ideally, there will only be one type of each application component, and anyone can use it in his or her application.

Connect existing software

Web Services help solve the interoperability problem by giving different applications a way to link their data.

Using Web Services you can exchange data between different applications and different platforms.

Let’s starts now by adding a new class in your application (Web Service) using the following information:

1

I am using default a database in my application; you can use whatever data you want to use. Put this web method in your web service class. I am using the Northwind database and customer table.

[WebMethod(Description = “Get all customers from customer table”)]

public DataSet GetLatestCustomers()

{
using (SqlConnection connection = new SqlConnection
(ConfigurationManager.ConnectionString”dataConnectionString”].ConnectionString))

{
string Query = “SELECT * FROM [Customers] ORDER BY [CustomerID] DESC”;

SqlCommand command = new SqlCommand(Query, connection);

command.CommandType = CommandType.Text;

connection.Open();

SqlDataReader reader = command.ExecuteReader();

DataTable myTable = new DataTable(“myTable”);

myTable.Columns.Add(“CustomerID”, typeof(string));

myTable.Columns.Add(“CompanyName”, typeof(string));

myTable.Columns.Add(“ContactName”, typeof(string));

myTable.Columns.Add(“ContactTitle”, typeof(string));

myTable.Columns.Add(“Address”, typeof(string));

myTable.Columns.Add(“City”, typeof(string));

myTable.Columns.Add(“Region”, typeof(string));

myTable.Columns.Add(“PostalCode”, typeof(string));

myTable.Columns.Add(“Country”, typeof(string));

myTable.Columns.Add(“Phone”, typeof(string));

myTable.Columns.Add(“Fax”, typeof(string));

while (reader.Read())

{
myTable.Rows.Add(new object[]

{

reader[“CustomerID”].ToString(), reader[“CompanyName”].ToString(),
reader[“ContactName”].ToString(), reader[“ContactTitle”], reader
[“Address”], reader[“City”], reader[“Region”], reader[“PostalCode”],
reader[“Country”],reader[“Phone”], reader[“Fax”] });

}

//myTable.Load(reader);

myTable.AcceptChanges();

DataSet ds = new DataSet();

ds.Tables.Add(myTable);

ds.AcceptChanges();

return ds;

}
}

Put your class in the App_Code folder. I am using a GridView control to show data on the page.

Now make an object to call your class like this:

Service service = new Service();

And put these two lines of code on the page load event.

GridView1.DataSource = service.GetLatestCustomers();
GridView1.DataBind();

@2

That’s it.