Friday, September 30, 2011

Online Stock streaming In Asp.net


Online Stock Streaming using ASP.Net

 Download Source Code




Online Stock Streaming

Introduction

It always made me wonder how sites like http://finance.yahoo.com and http://finance.google.com display stock quotes online so quickly and without refreshing entire page. So I decided to implement something similar. It looks very difficult to implement these kind of streaming, but ASP.Net and it's feature rich AJAX controls makes it really simple to implement this. This is my first attempt to build similar streaming web page. This sample may sound fairly easy to you and some of you might think that everyone knows this. But it might provide a good base for those who wants to build similar web sites and still have no idea where to start.

Using Code

Sample code provided in this article includes a web page Default.aspx and Default.aspx.cs code behind.
Default.aspx (UI)
UI code is fairly simple. First component is Script Manager. This component is necessary for AJAX functionality. After Script Manager, next component is UpdatePanel. This ajax control stops ASP.Net page from posting back. Instead of posting back page, it sends control inputs to server using client side javascripts. When it receives response from server, it refreshes content inside it on client side. Next control is an AJAX timer control. It rebinds grid with new quotes every 2 seconds.
Default.aspx.cs (Code Behind)
01.DataTable GetGridData()
02.{
03.DataTable DT = new DataTable();
04.DT.Columns.Add("Symbol",typeof(string));
05.DT.Columns.Add("Company Name",typeof(string));
06.DT.Columns.Add("LastTrade", typeof(float));
07.DT.Columns.Add("Bid", typeof(float));
08.DT.Columns.Add("Ask", typeof(float));
09.DT.Columns.Add("Volume", typeof(int));
10.DT.Columns.Add("Market Capital", typeof(string));
11.DT.Columns.Add("EPS", typeof(float));
12.DT.Columns.Add("P/E", typeof(float));
13. 
14.Random r = new Random();
15. 
16.//Apple
17. 
18.//Get a random value of last trade, bid, ask and volume.
19. 
20.float LastTrade = ((float)r.Next(17222,17434))/100;
21.float Bid = LastTrade - (float)0.34;
22.float Ask = LastTrade + (float)0.43;
23.int Volume = r.Next(23000000, 23600000);
24.DT.Rows.Add("AAPL", "Apple Inc.", LastTrade, Bid, Ask,
25.Volume, "153.88B", 3.93, 44.71);
26. 
27.//Microsoft
28. 
29.LastTrade = ((float)r.Next(3378, 3487)) / 100;
30.Bid = LastTrade - (float)0.34;
31.Ask = LastTrade + (float)0.43;
32.Volume = r.Next(38064903, 40075689);
33.DT.Rows.Add("MSFT", "Microsoft Corporation", LastTrade,
34.Bid, Ask, Volume, "153.88B", 2.13, 21.2);
35. 
36.//Yahoo
37. 
38.LastTrade = ((float)r.Next(2520, 2834)) / 100;
39.Bid = LastTrade - (float)0.34;
40.Ask = LastTrade + (float)0.43;
41.Volume = r.Next(14400000, 15500000);
42.DT.Rows.Add("YHOO", "Yahoo Inc.", LastTrade, Bid, Ask,
43.Volume, "34.48B", 1.42, 10.23);
44. 
45.//Google
46. 
47.LastTrade = ((float)r.Next(67025, 69000)) / 100;
48.Bid = LastTrade - (float)5;
49.Ask = LastTrade + (float)5;
50.Volume = r.Next(4500000, 5000000);
51.DT.Rows.Add("GOOG", "Google Inc.", LastTrade, Bid, Ask,
52.Volume, "213.73B", 12.42, 53.23);
53. 
54.//WYNN
55. 
56.LastTrade = ((float)r.Next(13249, 14022)) / 100;
57.Bid = LastTrade - (float)0.90;
58.Ask = LastTrade + (float)0.89;
59.Volume = r.Next(1222785, 1400000);
60.DT.Rows.Add("WYNN", "Wynn Resorts Ltd.", LastTrade, Bid, Ask,
61.Volume, "15.13B",1.81, 73.15);
62. 
63.return DT;
64.}
65. 
GetGridData() function simulates quotes for different stock symbols. Instead of simulated data you can replace this function to fetch real time quotes from other sources. This function builds a data table using random quotes and returns it.
1.protected void Timer1_Tick(object sender, EventArgs e)
2.{
3.//Bind grid view
4.GridView1.DataSource = GetGridData();
5. 
6.GridView1.DataBind();
7.}
Timer1_Tick() function is a timer function which executes every 2 seconds. It rebinds grid with simulated stock data.

11:37 PM by Dilip kakadiya · 0

Capturing the Webcam in Silverlight

Introduction

Since the first release of Silverlight, the community has been patiently waiting for a version of Silverlight which would allow us to capture video from a user’s webcam, as well as audio from their microphone. This past month at PDC 09, our wait was over with the release of Silverlight 4 Beta 1.
In this article we will explore the ways in which Silverlight can interact with a webcam, as well as the powerful results one can produce by combining live video with pixel shaders, video brushes as well as WriteableBitmaps.
Download Source Code

Getting Started

To get started, let’s create a new Silverlight 4 project in Visual Studio 2010 and draw a 320x240 pixel black Rectangle called “rectVideo” inside of the LayoutRoot of our MainPage.xaml.
1
One of the coolest media features included in Silverlight, is the VideoBrush. A VideoBrush gives us the ability to paint any area of our stage with video content. Back in the earlier versions of Silverlight we were limited to painting the source of a MediaElement, such as a Video Stream being played from an external source. A lot of people used the VideoBrush as a way to create cool effects like reflections of a video playing.
With Silverlight 4 addition of Webcam support, we now have the ability to set the source of our VideoBrush to that of the live video being captured through our webcam. We will use this technique to display our video on the Rectangle we just added to our stage.

Attaching to our Webcam

In order to have some live video to display in our black rectangle, we need to attach to our camera (VideoCaptureDevice) and capture its source. The first step in doing this is to instantiate the System.Windows.Media.CaptureSource object. This class is designed to provide methods and properties used to work with audio and video capture devices. In essence, CaptureSource is like a little media player. We attach a device, such as the camera or microphone, and “Start()” or “Stop()” the capture of content through the device. CaptureSource does not give us direct access to the raw audio or video, but instead can be used as the source of a VideoBrush or a custom VideoSink. In the future we will explore how to leverage a class derived from VideoSink to receive video information and to obtain the capture graph.
The first step in setting up our CaptureSource, is to set its “VideoCaptureDevice” and “AudioCaptureDevice” properties equal to one of our attached audio or video devices. Silverlight has created a helper class called “CaptureDeviceConfiguration” which gives us two choices in how we can get access to a camera or microphone.

All available Camera’s or Microphones

The first option we have is to call CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices. This method will return us a generic Collection containing each available VideoCaptureDevice. From this collection we could allow our users to manually select which device they choose to capture or we could look for the device which has the “IsDefaultDevice” property set to true.

Default Camera or Microphone

A second approach we can use is to request the default VideoCaptureDevice . Most people only have a single camera attached to their computer, so requesting the default will get us access without an additional interaction required by the user. Below is the code I use to attach our default camera to my CaptureSource and use that source to feed live video into my VideoBrush.
 CaptureSource _capture.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
 VideoBrush videoBrush = new VideoBrush();
 videoBrush.Stretch = Stretch.Uniform;
 videoBrush.SetSource(_capture);
 rectVideo.Fill = videoBrush;

Requesting Access

Now that we have our webcam attached, and our rectangle’s Fill being painted by our VideoBrush, it time to request permission to use the camera. For privacy reasons each time that Silverlight wants to access ones camera or microphone, the user must explicitly give Silverlight permission.
2
To get this dialog to appear we need to make the following call. The first part of the condition looks to see if we have already been given access, while the second requests the dialog to appear. A true response from either will allow us to call our CaptureSource.Start() method to begin capturing our live video.
 if (CaptureDeviceConfiguration.AllowedDeviceAccess || 
        CaptureDeviceConfiguration.RequestDeviceAccess())
 {
     _capture.Start();
 }
3

Taking it to the next level

Now that we know how to display our webcam in Silverlight, let’s see what we can do with the video being captured.
In Silverlight 3 we saw the introduction of Pixel Shader’s as a way to provide a custom bitmap effect to an image or video. Creating your own ShaderEffect is a great way to dynamically transform our webcams video as it is being painted on our rectangle. Instead of spending a bunch of time talking about how to create a ShaderEffect I encourage everyone to go to http://wpffx.codeplex.com/ and download the Windows Presentation Foundation Pixel Shader Effects Library. It contains just about every effect one would want to apply to our video.
To apply a ShaderEffect to our rectangle, we can either do it procedurally or simply add an Effect node to our XAML.
 <Rectangle Name="rectVideo" Width="320" Height="240" Fill="Black"  
    MouseLeftButtonDown="rectVideo_MouseLeftButton" VerticalAlignment="Top">
   <Rectangle.Effect>
      <local:InvertColorEffect/>
   </Rectangle.Effect>
 </Rectangle>

In this example I have applied an Invert effect to my video producing the following results. As each frame of the video is painted to the rectangle the ShaderEffect is applied just prior to the render.

4
If I want to give my user access to a bunch of effects, then on cool approach is to create a custom list that previews the effect on a small thumbnail of the live video. Using the same VideoBrush I can paint my webcam video on small 48x36 rectangles that are being rendered with one of each of my ShaderEffects. If a user wants to see the effect on the larger video, then we can tie a MouseLeftButtonDown event on the rectangle that alters our larger rectVideo to display the effect.
 private void Effect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     Rectangle rec = sender as Rectangle;
     switch (rec.Name)
     {
         case "invert":
             var invert = new InvertColorEffect();
             rectVideo.Effect = invert;
             break;
         case "mono":
             var mono = new MonochromeEffect();
             mono.FilterColor = Colors.White;
             rectVideo.Effect = mono;
             break;
         case "swirl":
             var swirl = new SwirlEffect();
             swirl.SwirlStrength = 2.5;
             rectVideo.Effect = swirl;
             break;
         case "tone":
             var tone = new ColorToneEffect();
             tone.Toned = 2;
             tone.LightColor = Colors.Brown;
             rectVideo.Effect = tone;
             break;
         case "emboss":
             var emboss = new EmbossedEffect();
             emboss.Amount = 15;
             emboss.Width = .01;
             rectVideo.Effect = emboss;
             break;
         default:
             rectVideo.Effect = null;
             break;
     }
 }
5

Capturing Stills of our Live Video

Now that we have our Shader’s being applied to our video, It would be really fun to capture still images that we can store both in isolated storage and to our file system.
In most situations, the fastest and easiest way to capture a still is to use the AsyncCaptureImage method exposed on our CaptureSource.
 _capture.AsyncCaptureImage((capturedImage) => 
     _viewModel.Captures.Add(capturedImage));
This method takes an System.Action<T> that generates a WriteableBitmap at the moment the method is called. The result of this call will be a WritableBitmap that we could use as the BitmapSource of an image or the source of an image we write to a second location.
Unfortunately, since this technique goes directly against the CaptureSource, it does not reflect the ShaderEffect that we have applied to our rectangle which has been painted with our VideoBrush. To get our still to have the effect, we simply have to generate the WritableBitmap from rectVideo directly. One possible downside is that the size of the still we capture will be the exact size of the rectangle we have drawn. If this was a problem we could certainly explore other ways to capture a large image using a similar approach.
 WriteableBitmap writeableBitmap = new WriteableBitmap(rectVideo, null);
 string name = Guid.NewGuid().ToString() + ".jpg";
  
 //store the image in a collection in my viewmodel
 _viewModel.Captures.Add(new Capture() { Name = name, Bitmap = writeableBitmap });

Isolated Storage

One of the other cool features I decided to add to my example, is the ability to create a list of thumbnails of each still I capture. This collection of thumbnails is displayed in a WrapPanel that has been applied to a ListBox as its ItemPanelTemplate. As I capture the still, I add it to my ListBox via binding to an “ObservableCollection”, as well as writing the image as a jpeg in isolated storage. This allows the application to maintain a persistent cache of each photo that has been captured. Next time we load the Silverlight app the list of stored image will be redisplayed in the ListBox.
6

Saving Still as Jpeg to File System

Out of the box Silverlight does not have native support of encoding jpegs, but a nice open source library called FJCore has been create that does the trick. http://code.google.com/p/fjcore/
 using (IsolatedStorageFileStream isfs = new 
      IsolatedStorageFileStream(name, FileMode.CreateNew, _isf))
 {
    MemoryStream stream = new MemoryStream();
    writeableBitmap.EncodeJpeg(stream);
    stream.CopyTo(isfs);
 }
The last and final feature I want to demonstrate was the ability to wrte my captures from isolated storage to the file system. Since I store each capture in isolated storage as a jpeg, all I have to do is locate the correct image by name, and copy the “IsolatedStorageFileStream” to the Stream that will be used to write to the file system. .NET 4.0 added a really nice helper function “CopyTo” that allows me to copy the bytes[] from one stream to another.
 private void Button_Click(object sender, RoutedEventArgs e)
 {
      Capture capture = listImages.SelectedItem as Capture;
      if (capture != null)
      {
          if (_saveFileDlg.ShowDialog().Value)
          {
               using (Stream stream = _saveFileDlg.OpenFile())
               {
                  if (_isf.FileExists(capture.Name))
                  {
                     using (IsolatedStorageFileStream isfs = 
                     new IsolatedStorageFileStream(capture.Name, FileMode.Open, _isf))

11:30 PM by Dilip kakadiya · 0

Accessing and Updating Data in ASP.NET: Accessing Database Data

Introduction


One of the coolest new features of ASP.NET 2.0 is its new Data Source controls. The Data Source controls are a collection of Web controls designed to provide a declarative approach to accessing and modifying data. In short, with the Data Source controls you can work with data without having to write a lick of data access code. Compare this to ASP.NET 1.x, which required oft-repeated code to access data. For example, to display the contents of a database table in a web page with ASP.NET 1.x, you'd need to write code to:
  1. Connect to the database,
  2. Issue the command,
  3. Retrieve the results, and
  4. Work with the results / bind them to a data Web control (such as a DataGrid)
While only five to ten lines of code is needed to perform these four steps, and libraries like the Data Access Application Block help reduce the volume of code that you need to write, the fact remains that in order to access or modify data in an ASP.NET 1.x application you must write code. With ASP.NET 2.0, data can be accessed entirely from declarative markup. In this article we'll be examining how to access data from databases with the SqlDataSource and AccessDataSource controls. With both of these controls you can specify the SELECT query to use and any parameters in the WHERE clause as properties of the Data Source controls. The code to connect to the database, issue the command, and retrieve the results is handled internally by the Data Source control. With the declarative, "code free" Data Source controls you can create a page that displays database data in under 15 seconds and without having to write a line of code. Read on to learn more!


Accessing Database Data


ASP.NET 2.0 provides two Data Source controls designed specifically to access data from a database:
  • SqlDataSource - useful for accessing data from any database that resides in a relational database. The "Sql" in the control name does not refer to Microsoft SQL Server, but rather the SQL syntax for querying relational databases, for the SqlDataSource control can be used to access not only Microsoft SQL Server databases, but Microsoft Access databases, Oracle databases... basically any OLE-DB or ODBC-compliant data store.
  • AccessDataSource - the AccessDataSource is very similar to the SqlDataSource. The key difference is that instead of requiring a connection string to the database, the AccessDataSource control allows you to simply specify the file path to the Access .MDB file through its DataFile property.
Both controls have virtually the same featureset, the only difference being how you specify the connection information. In fact, the AccessDataSource control is really superfluous since Microsoft Access databases can be accessed through the SqlDataSource control just as easily. (True, you have to provide a connection string rather than simply the path to the file, but Visual Studio 2005 can automatically create appropriate connection strings for those databases residing in your App_Data folder.) In this article we'll examine the SqlDataSource in detail, just touching upon the one difference in the AccessDataSource. Furthermore, the SqlDataSource and AccessDataSource controls can be used to both access and modify data; however, this article only examines accessing data. We'll see how to use these Data Source controls to modify database data in a future installment. Also, we'll focus on working with these Data Source controls in Visual Studio 2005 through the Design view. While you can set all of these properties by hand in the Source view, the Design view offers a time-saving wizard for quickly specifying which database to connect to and what query to issue.
To get started, fire up Visual Studio 2005 and create a new website or, alternatively, download the code example at the end of this article. For this article I'm going to demonstrate connecting to, retrieving, and displaying data from the Microsoft Access Northwind database, which is included in the download. (Note that I'm using a slightly modified, slimmed down version of Northwind, one whose Forms, Modules, Reports, and Macros have all been deleted to reduce the file size.)
ASP.NET 2.0 introduces the App_Data folder, a folder that you can add to your website specifically for storing data files, such as XML files, Access database files (.mdb), and SQL Server 2000 and SQL Server 2005 Express edition database files (.mdf). In the code download you'll find the Northwind.mdb file in the App_Data folder. Of course, ASP.NET can work with databases that are not in the App_Data folder. When using professional grade database systems, like Microsoft SQL Server, typically the database is registered on a separate database server.
Regardless of where your database is located, once you have a database to work with in order to access its contents you'll want to add a SqlDataSource (or AccessDataSource) control to the page. Start by creating a new ASP.NET page and go to the Design view. Next, drag a SqlDataSource control from the Toolbox onto the Designer. The Data Source controls display in the Designer as a little gray box; they do not emit any HTML markup when a browser visits the page. In order to correctly access data, we must set a variety of SqlDataSource properties that indicate the database to use and the query to execute. While these can be set through the Properties pane, it's usually quicker to use the wizard, which can be reached by clicking on the "Configure Data Source" link in the SqlDataSource control's smart tag.

Configuring the SqlDataSource Control Using the Wizard


When you click the "Configure Data Source" link a wizard appears, prompting you to select the data to retrieve. The first screen, shown below, prompts you to select the database from which the data will be queried. The drop-down list lists existing connection strings defined in the Web.config's <connectionStrings> section and those in the App_Data folder. To connect to a database registered somewhere else, click the New Connection button and specify the database server and authentication information. (For more information on working with the <connectionStrings> section refer to an earlier article of mine, Working with Databases in ASP.NET 2.0 and Visual Studio 2005.)
After selecting your database, click the Next button. If you don't have a <connectionStrings> defined for this database in Web.config, the wizard will kindly do so for you, if you like. There are a plethora of advantages to defining your connection strings in Web.config, the key one being that it makes your application more maintainable. Imagine that, down the road, you move database servers and need to update the connection string. If you have it defined in Web.config, you have one place to update. If not, you have to find each and every page that references the connection string and update it accordingly. Furthermore, by placing your connection string information in Web.config you can encrypt your connection strings to further protect your site. (However, the wizard won't automatically write to the <connectionStrings> section if you have it encrypted.) The screenshot below shows this second step; as you can see, I've opted to save the connection string to Web.config using the name NorthwindConnectionString.


Contrasting the AccessDataSource...
The AccessDataSource differs from the SqlDataSource in one minor aspect - rather than specifying a connection string as with the SqlDataSource, the AccessDataSource prompts for the path to the database file. Therefore, the screen shots above are different for the AccessDataSource. Specifically, the first screen shot examined prompts for a file location; since there is no connection string, the second screen shot does not appear in the AccessDataSource. However, the remaining screen shots are identical for both the AccessDataSource and SqlDataSource.

On the next screen you are asked to choose your SELECT statement. As you can see by the two radio buttons at the top of the screen you can either pick a table or view and select the columns to return (as shown in the screen shot below), or write a custom SQL statement or pick a stored procedure. If you opt to specify columns from a table or view, simply pick the table or view from the drop-down list and then check those columns you want to return. Here you can see that I'm returning the ProductID, ProductName, UnitPrice, and UnitsInStock columns from the Products table. This query will return all records from the Products table; we'll see how to filter the returned records in a future article.

By default the data is returned in the order the database stores the records. If there's a clustered index (such as a primary key constraint) on the table, the data will be ordered by the column(s) that make up that index; otherwise, the data is ordered by order it was entered into the database table. To specify a different ordering, click the ORDER BY button. Here you can choose what columns the data should be sorted by, and if it should be sorted in ascending or descending order. The selections here tack on an ORDER BY clause to the SELECT statement.

If you opt to select the columns to return from a table or view you can only configure simple queries that involve a single table or view. With relational databases, often there's data in related tables that we need to grab, requiring JOINs. Or the data to retrieve might be accessible from a stored procedure. In these cases we must select the "Specify a custom SQL statement of stored procedure" radio button and click Next. Doing so will take us to the screen shot shown below. Here you can type in a SQL query by hand into the SELECT tab, or pick a stored procedure from those listed in the drop-down list.

If you're creating a particularly nasty SQL statement or are a bit rusty on the SQL syntax, you may want to click the Query Builder button. This will launch a graphical tool that lets you select what tables to query and automatically adds the JOIN syntax. The screen shot below shows the Query Builder in action. As you can see, I've added two tables to the query window - Categories and Products - and checked those columns from the tables I want to return. I also specified that the results should be ordered first by the CategoryName column, and then by ProductName. With just a few mouse clicks the Query Builder has kindly created the SELECT query.

After configuring your SELECT statement - either by selecting a table or view or by picking a stored procedure or writing a custom SQL statement, click the Next button to reach the final screen. Here you can run the query you've configured against the database and observe the results. To complete the wizard, click the Finish button.


Configuring the SqlDataSource Through the Properties Pane


Prior to ASP.NET 2.0 I was firmly in the camp "doing things by hand." I didn't like wizards, I felt that they abstracted away too much and were too often used as a crutch and enabled developers to be able to achieve some goal without really learning what it was they just did. This fact often jumps up and bites the head of the wizard-using developer when something goes wrong. Since they've relied on the wizard, they don't know how to fix whatever bug or problem has surfaced. I still have that overall feeling about wizards, in general, but have really been turned on to the wizards in Visual Studio 2005. Partly because they save so much time, but primarily because all they're doing is setting properties. They're not writing oodles of code on your behalf, which is when the wizards become dangerous. However, if you're still a fan of not using wizards, that's quite all right, as configuring the SqlDataSource through its properties is also a walk in the park. Simply set the following properties, either through the Properties pane or as declarative markup:
  • ConnectionString - Set this to your database's connection string. This can either be a fully-qualified connection string or a reference to a connection string name in the Web.config's <connectionStrings> section. If it's a reference to a Web.config connection string use the syntax: ConnectionString="<%$ ConnectionStrings:ConnectionStringName %>". For the AccessDataSource control set the DataFile property to the path to the Access database file, like ~/App_Data/Northwind.mdb.
  • ProviderName - the name of the database provider to use. By default, the SqlDataSource uses the SqlClient provider, which is a provider designed specially for Microsoft SQL Server. If you are using a different database, set this property accordingly. The .NET Framework ships with four database providers:
    • System.Data.SqlClient - used for fast access to Microsoft SQL Server (the default)
    • System.Data.OleDb - used for accessing OLE-DB-compliant data stores, such as Access
    • System.Data.Odbc - used for accessing older, ODBC-compliant data stores
    • System.Data.OracleClient - used for fast access to Oracle databases
    If you define your connection string in Web.config you can use the following syntax to set this property to the value defined there: ProviderName="<%$ ConnectionStrings:ConnectionStringName.ProviderName %>"
  • SelectCommand - the SELECT query to issue to the database, such as SELECT [ProductID], [ProductName] FROM [Products] ORDER BY [ProductName].

Retrieving the Data from a SqlDataSource Control


Typically, when accessing data from a database we want to display or process it in some manner. To simply display the data, use any data Web control (such as the GridView) and set the data Web control's DataSourceID property to the ID of the SqlDataSource. (This can most easily be done through the data Web control's smart tag in the Design view. There you'll find a drop-down list from which you can select the SqlDataSource control to bind to the data Web control.) When the page is visited, the data Web control will automatically grab the data from the associated SqlDataSource control and display it. There's a demo of doing just this in this article's download. The screen shot below shows the GridView when displaying the ProductID, ProductName, UnitPrice, and UnitsInStock columns from the Products table ordered by UnitPrice ascending with ties broken by the alphabetic sorting of ProductName.
You can also programmatically access the contents of a SqlDataSource control and work with the data in code. Before we see how that is accomplished, let's first look at how the data is returned from the underlying database by the SqlDataSource control. If you're familiar with data access in ASP.NET version 1.x you know that there are two techniques/objects for working with data:
  • DataReaders - a DataReader offers forward-only, read-only access to a database, and requires an active connection. More efficient than a DataSets/DataTables/DataViews.
  • DataSet/DataTable/DataView - a DataTable offers a random access, editable representation of a query. A DataSet is a collection of DataTables. DataViews can be used to retrieve a filtered or sorted subset of records in a DataTable.
See Contrasting the ADO.NET DataReader and DataSet for more information on the differences and similarities. The SqlDataSource can return either a DataSet or DataReader. This option is configurable via the SqlDataSource's DataSourceMode property, with the default being DataSet. In order to utilize the GridView's built-in sorting and paging capabilities, or the SqlDataSource's caching capabilities (another topic for a future article!) you'll need to have the SqlDataSource return a DataSet. (The AccessDataSource control also has the DataSourceMode property.)
To programmatically access the contents of a SqlDataSource control call the Select() method. This method expects a single input parameter of type DataSourceSelectArguments. This parameter can be used to pass along requests for the SqlDataSource to message the data before returning it. For example, when working with a sortable GridView, sorting a column calls the Select() method passing in a DataSourceSelectArguments instance with its SortExpression property set to the column name the end user sorted the data by. If you don't want the SqlDataSource to sort, filter, or return only a "page" of data, simply pass in DataSourceSelectArguments.Empty, as shown in the code example below.
The Select() method returns an object that implements IEnumerable. Specifically, it returns a DataView if the DataSourceMode property is set to DataSet, and a DataReader object if its set to DataReader. The following two examples show how to programmatically access the data from a SqlDataSource. The first one, written in VB, returns a DataSet and then is iterated through, displaying a random subset of results. The second example, written in C#, uses a SqlDataSource that returns a scalar value (the average price of all products) and displays that in a Label Web control on the page.


HTML Portion


<asp:Label ID="RandomProductNames" runat="server"></asp:Label>

<asp:SqlDataSource ID="rndProductsDataSource" runat="server"
   ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
   ProviderName="<%$ ConnectionStrings:NorthwindConnectionString.ProviderName %>"
   SelectCommand="SELECT [ProductID], [ProductName] FROM [Products]">
</asp:SqlDataSource>


Page_Load Event Handler


'Programmatically access the SqlDataSource - get back a DataView
Dim dv As DataView = _
   CType(rndProductsDataSource.Select(DataSourceSelectArguments.Empty), DataView)

Dim rndCoinFlip As New Random
RandomProductNames.Text = String.Empty

For Each dr As DataRow In dv.Table.Rows
   'See if we want to show this
   If rndCoinFlip.Next(2) = 0 Then
      'Show
      RandomProductNames.Text &= _
               dr("ProductName").ToString() & "<br />"
   Else
      'Don't show
   End If
Next



HTML Portion


The average price of all products in the Products database table is:
<asp:Label ID="AvgPrice" runat="server" ForeColor="Red"></asp:Label>

<asp:SqlDataSource ID="avgPriceDataSource" runat="server"
   ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
   ProviderName="<%$ ConnectionStrings:NorthwindConnectionString.ProviderName %>"
   SelectCommand="SELECT AVG(UnitPrice) FROM Products">
</asp:SqlDataSource>


Page_Load Event Handler


// Retreive the results from the SqlDataSource as a DataReader
OleDbDataReader reader = (OleDbDataReader)
      avgPriceDataSource.Select(DataSourceSelectArguments.Empty);

// Read in the value
if (reader.Read())
   // Format the price as a currency
   AvgPrice.Text = string.Format("{0:c}", reader[0]);
else
   // Whoops, there were no results!
   AvgPrice.Text = "I don't know!";

// Close the reader
reader.Close();

Note that in both examples I explicitly cast the return value from the Select() method either into a DataView or OleDbDataReader object, depending on the SqlDataSource's DataSourceMode property. (Since DataReaders are provider-specific objects, if I was using the SqlClient provider I'd be using a SqlDataReader instead; if I was using the OracleProvider, I'd be using an OracleDataReader, and so on.)

Conclusion


In this installment we saw the basics of accessing data from databases using the SqlDataSource and AccessDataSource controls. While we only looked at retrieving all records from a table, we'll turn our attention to more useful SqlDataSource tasks in future articles. When querying data with the SqlDataSource control you can indicate the database to connect to and the data to return via the "Configure Data Source" wizard, which is accessible through the SqlDataSource control's smart tag. Once the Data Source control has been configured, the data can be displayed by binding it to a data Web control or processed programmatically by calling the SqlDataSource control's Select() method. The precise code you use for programmatically working with a SqlDataSource control's data depends on how the data is returned (which depends on the DataSourceMode property's value).

11:24 PM by Dilip kakadiya · 0

Passing value from popup window to parent form's TextBox

Passing values from a popup window back to the parent page is an often asked question. Especially when there is a GridView type control in the popup. In the following example we will be using two forms. The parent form will be parent.aspx and the popup will be popup.aspx. Also note that the parent.aspx form is derived from some MasterPage. Code is provided both in VB.Net and C#.Net.
--- .aspx of parent form ---
<script type="text/javascript">
function OpenPopup() {
    window.open("popup.aspx","List","scrollbars=no,resizable=no,width=400,height=280");
    return false;
}
</script>
.      
.
.      
<asp:TextBox ID="txtPopupValue" runat="server" Width="327px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show List" />
--- .vb of parent.aspx if vb.net is the language ---
If Not IsPostBack Then
    Me.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()")
End If
--- .cs of parent.aspx if C#.net is the language ---
if (!IsPostBack) {
    this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
}
--- .aspx of popup form ---
<script language="javascript">
function GetRowValue(val)
{
    // hardcoded value used to minimize the code.
    // ControlID can instead be passed as query string to the popup window
    window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val;
    window.close();
}
</script>


<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
    <Columns>
        <asp:TemplateField>
            <AlternatingItemTemplate>
                <asp:Button ID="btnSelect" runat="server" Text="Select" />
            </AlternatingItemTemplate>
            <ItemTemplate>
                <asp:Button ID="btnSelect" runat="server" Text="Select" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
--- .vb file if vb.net is the language ---
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    If (e.Row.RowType = DataControlRowType.DataRow) Then
        'assuming that the required value column is the second column in gridview
        DirectCast(e.Row.FindControl("btnSelect"), Button).Attributes.Add("onclick", "javascript:GetRowValue('" & e.Row.Cells(1).Text & "')")
    End If
End Sub
--- .cs file if C#.net is the language ---
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
        //assuming that the required value column is the second column in gridview
        ((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells[1].Text + "')");
    }
}

9:12 PM by Dilip kakadiya · 0

Page Life Cycle of an ASP.NET

The life cycle starts when a user requests a web page through his/her browser. The Web server than process the page through a sequence of steps before response is sent back to the user's browser. The steps are as:

1. Page Request
2. Start
3. Page Initialization
4. Load
5. Validation
6. PostBack Event Handling
7. Render
8. Unload

Page Request
The page request occurs before the page life cycle begins. When a user requests the page, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page Initialization
During page initialization, controls on the page are available and each control's UniqueID are generated but not their properties. Any themes are also applied to the page.

Developers have access to the Init, InitComplete and PreLoad methods in this stage. The methods are as follows:

* Init: This event is raised after all controls have been initialized and any skin settings have been applied. This event is used to read or initialize control properties.
* InitComplete: The Page object raises this event. This event is used for processing tasks that require completion of all initialization.
* PreLoad: Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. The OnLoad event method is fired during this stage.
This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

Validation
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

PostBack Event Handling
If the request is a postback, any event handlers are called. The event handling for server controls occurs during this stage.

Render
During rendering, view state is saved to the page and then the page calls on each control to contribute its rendered output to the OutputStream of the page's Response property. Render is not really an event. The HTML of the page and all controls are sent to the browser for rendering.

Unload
Unload is called when the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed. The cleanup includes routines such as closing database connections and file streams, or, event logging and other tasks.

Conclusion
When a Web page is requested, the server creates objects associated with the page and all of its child controls objects and uses these to render the page to the browser. Once the final stage is complete, the web server destroys these objects, to free up resource to handle additional request.

6:10 AM by Dilip kakadiya · 0

Website Deployment


Internet Information Services is used to make your computer a web server. If we want to have a web server for developing dynamic website or want to publish
website on our own server then we install the IIS.Internet Information Server (IIS) is a World Wide Web server, a Gopher server and an FTP server all rolled
into one. IIS means that you can publish WWW pages.
If you want to your web application accessible to any other pc in intranet or internet you need to IIS.

Below are steps for deployment:
1.Right click your website and click on Publish website.All compiles files are ready for deployment.
2.Create a backup for database whichever you are using and restore it on production server.
3.Go to server using ftp or filezila copy all compiles file on server.
4.Open Webconfig and change the connection string according to your Database name and server.
5.Create a virtual directory for this website.
6.Your website is ready.
7.Test website http://192.163.0.234(ServerName)/VDName/Login.aspx

6:09 AM by Dilip kakadiya · 0

CSS For AJAX Tab


.AJAXTab_Theme .tab_header
{
font-family:"Helvetica Neue", Arial, Sans-Serif;
background:url(/PNG/Light-menu.png) repeat-x bottom;
height:20PX ;
font-size:12px;
display:block;
}
.AJAXTab_Theme .tab_header .tab_outer
{
background:url(/Images/Tab/tab.png) no-repeat left top;
border-color:#222;
color:#222;
padding-left:10px;
margin-right:3px;
}
.AJAXTab_Theme .tab_header .ajax__tab_inner
{
background:url(PNG/Dark-menu.png) no-repeat right top;
border-color:#666;
color:#0067CA;
font:bold 10pt verdana;
padding:3px 10px 2px 0px;
}
.AJAXTab_Theme .ajax__tab_hover .ajax__tab_inner
{
color:#B80200;
font:bold 10pt verdana;
}
.AJAXTab_Theme .ajax__tab_active .tab_outer
{
background:url(PNG/Dark-menu.png) no-repeat 0pt -40px;
border-bottom-color:#ffffff;
}
.AJAXTab_Theme .tab_active .tab_inner
{
background:url(PNG/Dark-menu.png) no-repeat right -40px;
color:#B80200;
font:bold 10pt verdana;
border-color:#333
}
.AJAXTab_Theme .tab_body
{
font-family:verdana,tahoma,helvetica;
font-size:10pt;
padding:8px;
background-color:#ffffff;
border:solid 1px #d7d7d7;
border-top-width:0;
}

6:08 AM by Dilip kakadiya · 0