Monday, September 26, 2011

Dataview example

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

public partial class dataviewsample : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

DataTable dt = new DataTable();

dt.TableName = "Books";

DataColumn dc1 = new DataColumn();

dc1.ColumnName = "BookID";

dc1.DataType = typeof(int);

dc1.AllowDBNull = false;

dc1.Unique = true;

DataColumn dc2 = new DataColumn();

dc2.ColumnName = "Category";

dc2.DataType = typeof(string);

DataColumn dc3 = new DataColumn();

dc3.ColumnName = "BookName";

dc3.DataType = typeof(string);

DataColumn dc4 = new DataColumn();

dc4.ColumnName = "Author";

dc4.DataType = typeof(string);

dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

dt.Rows.Add(new object[] { 1, "iPhone", "iPhone User Interface Cookbook: RAW", "Cameron Banga" });

dt.Rows.Add(new object[] { 2, "MySQL", "MySQL 5.1 Plugin Development", "Andrew Hutchings, Sergei Golubchik" });

dt.Rows.Add(new object[] { 3, "MySQL", "MySQL Admin Cookbook", "Daniel Schneller, Udo Schwedt" });

dt.Rows.Add(new object[] { 4, "Asp.net", "Asp.net Admin Cookbook", "Daniel Schneller, Udo Schwedt" });

dt.Rows.Add(new object[] { 5, "C#.net", "C#.net Admin Cookbook", "Daniel Schneller, Udo Schwedt" });

dt.Rows.Add(new object[] { 6, "Asp.net", "WCF Admin Cookbook", "Daniel Schneller, Udo Schwedt" });

dt.AcceptChanges();

Label1.Text = "Source DataTable";

GridView1.DataSource = dt.DefaultView;

GridView1.DataBind();

//this line create a new DataView

DataView dView = new DataView(dt);

dView.RowFilter = "Category = 'MySQL'";

Label2.Text = "Here we create a new DataView
"
+

"and set the RowFilter (Category = 'MySQL')";

GridView2.DataSource = dView;

GridView2.DataBind();

//this line create a new DataView

DataTable dt2 = dView.ToTable();

dView.RowFilter = "Category = 'Asp.net'";

Label3.Text = "Here we create a new DataTable from DataView";

GridView3.DataSource = dView;

GridView3.DataBind();

//this line create a new DataTable from DataView

DataTable dt2 = dView.ToTable();

Label3.Text = "Here we create a new DataTable from DataView";

GridView4.DataSource = dt2;

GridView4.DataBind();

}

}

.....................................

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dataviewsample.aspx.cs" Inherits="dataviewsample" %>





Untitled Page






How to use DataView ToTable method

to create a new DataTable in ado.net




































A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.

A DataView provides you with a dynamic view of a single set of data to which you can apply different sorting and filtering criteria, similar to the view provided by a database.

However, a DataView differs significantly from a database view in that the DataView cannot be treated as a table and cannot provide a view of joined tables.

You also cannot exclude columns that exist in the source table, nor can you append columns, such as computational columns, that do not exist in the source table.



C# Code for ASP.Net Convert DataSet to DataView

// SQL Select Command

SqlCommand mySqlSelect = new SqlCommand("select * from categories", mySQLconnection);

mySqlSelect.CommandType = CommandType.Text;

SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);

DataSet myDataSet = new DataSet();

mySqlAdapter.Fill(myDataSet);

// Convert DataSet to DataView using DefaultView property associated with DataTable stored inside the DataSet

DataView dView = myDataSet.Tables[0].DefaultView;


Thursday, September 22, 2011

Silverlight DataGrid

Silverlight DataGrid Control

This article shows you how to work with a DataGrid control available in Silverlight 2.0. Article also demonstrates some formatting and data binding techniques.

Introduction

The DataGrid tag represents a Silverlight DataGrid control in XAML. The DataGrid control is found in System.Windows.Controls namespace. When you drag and drop a DataGrid control from Toolbox to your XAML code, the action adds following tag for the DataGrid control.

<my:DataGrid>my:DataGrid>

And at the top of the XAML file, the designer adds the following line that adds a namespace System.Windows.Controls and assembly reference to System.Windows.Controls.Data.

xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

The Width and Height attributes represent the width and the height of a DataGrid. The x:Name attribute represents the name of the control, which is a unique identifier of a control. The Margin attribute sets the margin of the DataGrid being displayed from the top left corner.

The following code snippet sets the name, height, width, and margin of a DataGrid control.

<my:DataGrid x:Name="McDataGrid" Width="400" Height="300" Margin="10,10,10,10">

my:DataGrid>

Another way to create a DataGrid control is by dragging a DataGrid control from Toolbox to the XAML code in Visual Studio XAML editor. Once you drag and drop a DataGrid control to the XAML page, you will see the following namespace reference is added to the XAML code.

xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

And the following code is added to the XAML code for the DataGrid.

<data:DataGrid>data:DataGrid>

Figure 1 shows Toolbox and XAML code preview after a DataGrid is added to a page.

DataGridImg1.gif

Figure 1

Data Binding

The ItemSource property of DataGrid is the key to data binding. You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects.

Listing 1 sets the ItemsSource property of a DataGrid to an array of strings.

public MainPage()

{

InitializeComponent();

McDataGrid.ItemsSource = LoadStringData();

}

///

/// Load a string collection

///

///

private string[] LoadStringData()

{

return "One Two Three Four Five Six Seven Eight".Split();

}

Listing 1

Figure 2 is the result of Listing 1. As you may see from Listing 1, the default column of the DataGrid shows all the strings in the array.

DataGridImg2.gif

Figure 2

This was a simple example. Now let's build a little complex example.

ItemsSource and Data Binding

In this example, we will create a collection of objects and bind it to a DataGrid control.

First, we are going to add a class to the project. Right click on the project, select Add New Item and select Class. I give my class name Author.cs. After that, we are going to add some public properties to the class. The simplest way to add a property to a class is type "prop" and hit TAB twice. This action will add an automatic property to the class. See Figure 3.

DataGridImg3.gif

Figure 3

The final Author class looks like Listing 2.

public class Author

{

public int ID { get; set; }

public string Name { get; set; }

public DateTime DOB { get; set; }

public string BookTitle { get; set; }

public bool IsMVP { get; set; }

}

Listing 2

Now let's create a collection of Author objects by using the List class. The LoadCollectionData method in Listing 3 creates a List of Author objects.

///

/// List of Authors

///

///

private List<Author> LoadCollectionData()

{

List<Author> authors = new List<Author>();

authors.Add(new Author(){

ID = 101,

Name = "Mahesh Chand",

BookTitle = "Graphics Programming with GDI+",

DOB = new DateTime(1975, 2, 23),

IsMVP = false });

authors.Add(new Author()

{

ID = 201,

Name = "Mike Gold",

BookTitle = "Programming C#",

DOB = new DateTime(1982, 4, 12),

IsMVP = true

});

authors.Add(new Author()

{

ID = 244,

Name = "Mathew Cochran",

BookTitle = "LINQ in Vista",

DOB = new DateTime(1985, 9, 11),

IsMVP = true

});

return authors;

}

Listing 3

The following code snippet sets the ItemsSource property of a DataGrid to List of Authors.

McDataGrid.ItemsSource = LoadCollectionData();

The new DataGrid looks like Figure 4, which shows the properties of the Author class a column names.

DataGridImg4.gif

Figure 4

As you saw in Figure 4, all public properties of the Author object are represented as columns of the DataGrid. This is because by default, the AutoGenerateColumns property of DataGrid is true. If you do not wish to generate automatic columns, you simply need to set this property to false.

McDataGrid.AutoGenerateColumns = false;

Setting Column Width and Row Height

The ColumnWidth and RowHeight properties of DataGrid are used to set the default column width and row height of DataGrid columns and rows.

The following code snippet sets column width and row height to 100 and 40 respectively.

<data:DataGrid x:Name="McDataGrid" Width="580" Height="270"

Margin="10,10,0,0" Background="Bisque"

ColumnWidth="100" RowHeight="40">

data:DataGrid>

The new DataGrid looks like Figure 5.

DataGridImg5.gif

Figure 5

The MaxWidth and MaxHeight properties represent the maximum width and maximum height of a DataGrid. The MinWidth and MinHeight properties represent the minimum width and maximum height of a DataGrid. The MaxColumnWidth and MinColumnWidth properties represent the maximum width and minimum width of columns in a DataGrid.

Grid Lines Visibility and Header Visibility

The GridLinesVisibility property is used to make grid lines visible. Using this option you can show and hide vertical, horizontal, all, or none lines. The HeaderVisibility property is used to show and hide row and column headers.

The following code snippet makes vertical grid lines visible and header visible for both rows and columns.

GridLinesVisibility="Vertical" HeadersVisibility="All"

The new DataGrid looks like Figure 6.

DataGridImg6.gif

Figure 6

Grid Background, Row Background, and Alternative Row Background

The Background property is used to set the background color of the DataGrid. The RowBackground and AlternativeRowBackground properties are used to set the background color of rows and alternative of the DataGrid.

The following code snippet sets background, row background, and alternative row background colors of a DataGrid.

Background="LightGray" RowBackground="LightYellow"

AlternatingRowBackground="LightBlue"

The new DataGrid looks like Figure 7.

DataGridImg7.gif

Figure 7

Border Color and Thickness

The BorderBrush and BorderThickness properties are used to set the color and width of the border. The following code snippet sets border color to gray and thickness to 5.

BorderBrush="Gray" BorderThickness="5"

The DataGrid with a new border looks like Figure 8.

DataGridImg8.gif

Figure 8

Sorting

By default, column sorting is enabled on a DataGrid. You can sort a column by simply clicking on the column header. You may disable this feature by setting CanUserSortColumns property to false. The following code snippet sets CanUserSortColumns properties to false.

CanUserSortColumns = "False"

Scrolling

The HorizontalScrollBarVisibility and VerticalScrollBarVisibility properties of type ScrollBarVisibility enumeration control the horizontal and vertical scrollbars of the DataGrid. It has four values - Auto, Disabled, Hidden, and Visible. The default value of these properties is Auto, that means, when scrolling is needed, you will see it, otherwise it will be hidden.

The following code snippet enables the horizontal and vertical scrollbars.

HorizontalScrollBarVisibility="Visible"

VerticalScrollBarVisibility="Visible"

The DataGrid with both scrollbars looks like Figure 9.

DataGridImg9.gif

Figure 9

Summary

In this article, we learnt how to use a DataGrid control in Silverlight. I will add more DataGrid functionality to this article in my next update. If you developed any cool code and want to share here, feel free to post at the bottom.

WCF Terms

WCF Terms

Other concepts and terms used in the WCF documentation include the following.

message:

A self-contained unit of data that can consist of several parts, including a body and headers.
service:

A construct that exposes one or more endpoints, with each endpoint exposing one or more service operations.
endpoint:

A construct at which messages are sent or received (or both). It comprises a location (an address) that defines where messages can be sent, a specification of the communication mechanism (a binding) that described how messages should be sent, and a definition for a set of messages that can be sent or received (or both) at that location (a service contract) that describes what message can be sent. A WCF service is exposed to the world as a collection of endpoints.
application endpoint:

An endpoint exposed by the application and that corresponds to a service contract implemented by the application.
infrastructure endpoint:

An endpoint that is exposed by the infrastructure to facilitate functionality that is needed or provided by the service that does not relate to a service contract. For example, a service might have an infrastructure endpoint that provides metadata information.
address:

Specifies the location where messages are received. It is specified as a Uniform Resource Identifier (URI). The URI schema part names the transport mechanism to use to reach the address, such as HTTP and TCP. The hierarchical part of the URI contains a unique location whose format is dependent on the transport mechanism. The endpoint address enables you to create unique endpoint addresses for each endpoint in a service or, under certain conditions, to share an address across endpoints. The following example shows an address using the HTTPS protocol with a non-default port:
HTTPS://cohowinery:8005/ServiceModelSamples/CalculatorService 
binding:

Defines how an endpoint communicates to the world. It is constructed of a set of components called binding elements that "stack" one on top of the other to create the communication infrastructure. At the very least, a binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint. For more information, see Configuring Services.
binding element:

Represents a particular piece of the binding, such as a transport, an encoding, an implementation of an infrastructure-level protocol (such as WS-ReliableMessaging), or any other component of the communication stack.
behaviors:

A component that controls various run-time aspects of a service, an endpoint, a particular operation, or a client. Behaviors are grouped according to scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations. For example, one service behavior is throttling, which specifies how a service reacts when an excess of messages threaten to overwhelm its handling capabilities. An endpoint behavior, on the other hand, controls only aspects that are relevant to endpoints, such as how and where to find a security credential.
system-provided bindings:

WCF includes a number of system-provided bindings. These are collections of binding elements that are optimized for specific scenarios. For example, the WSHttpBinding is designed for interoperability with services that implement various WS-* specifications. These predefined bindings save time by presenting only those options that can be correctly applied to the specific scenario. If a predefined binding does not meet your requirements, you can create your own custom binding.
configuration versus coding:

Control of an application can be done either through coding, through configuration, or through a combination of both. Configuration has the advantage of allowing someone other than the developer (for example, a network administrator) to set client and service parameters after the code is written and without having to recompile. Configuration not only enables you to set values like endpoint addresses, but also allows further control by enabling you to add endpoints, bindings, and behaviors. Coding allows the developer to retain strict control over all components of the service or client, and any settings done through the configuration can be inspected and if needed overridden by the code.
service operation:

A procedure defined in a service's code that implements the functionality for an operation. This operation is exposed to clients as methods on a WCF client. The method can return a value, and can take an optional number of arguments, or take no arguments, and return no response. For example, an operation that functions as a simple "Hello" can be used as a notification of a client's presence and to begin a series of operations.
service contract:

Ties together multiple related operations into a single functional unit. The contract can define service-level settings, such as the namespace of the service, a corresponding callback contract, and other such settings. In most cases, the contract is defined by creating an interface in the programming language of your choice and applying the ServiceContractAttribute attribute to the interface. The actual service code results by implementing the interface.
operation contract:

An operation contract defines the parameters and return type of an operation. When creating an interface that defines the service contract, you signify an operation contract by applying the OperationContractAttribute attribute to each method definition that is part of the contract. The operations can be modeled as taking a single message and returning a single message, or as taking a set of types and returning a type. In the latter case, the system will determine the format for the messages that need to be exchanged for that operation.
message contract:

Describes the format of a message. For example, it declares whether message elements should go in headers versus the body, what level of security should be applied to what elements of the message, and so on.
fault contract:

Can be associated with a service operation to denote errors that can be returned to the caller. An operation can have zero or more faults associated with it. These errors are SOAP faults that are modeled as exceptions in the programming model.
data contract:

The descriptions in metadata of the data types that a service uses. This enables others to interoperate with the service. The data types can be used in any part of a message, for example, as parameters or return types. If the service is using only simple types, there is no need to explicitly use data contracts.
hosting:

A service must be hosted in some process. A host is an application that controls the lifetime of the service. Services can be self-hosted or managed by an existing hosting process.
self-hosted service:

A service that runs within a process application that the developer created. The developer controls its lifetime, sets the properties of the service, opens the service (which sets it into a listening mode), and closes the service.
hosting process:

An application that is designed to host services. These include Internet Information Services (IIS), Windows Activation Services (WAS), and Windows Services. In these hosted scenarios, the host controls the lifetime of the service. For example, using IIS you can set up a virtual directory that contains the service assembly and configuration file. When a message is received, IIS starts the service and controls its lifetime.
instancing:

A service has an instancing model. There are three instancing models: "single," in which a single CLR object services all the clients; "per call," in which a new CLR object is created to handle each client call; and "per session," in which a set of CLR objects is created, one for each separate session. The choice of an instancing model depends on the application requirements and the expected usage pattern of the service.
client application:

A program that exchanges messages with one or more endpoints. The client application begins by creating an instance of a WCF client and calling methods of the WCF client. It is important to note that a single application can be both a client and a service.
channel:

A concrete implementation of a binding element. The binding represents the configuration, and the channel is the implementation associated with that configuration. Therefore, there is a channel associated with each binding element. Channels stack on top of each other to create the concrete implementation of the binding: the channel stack.
WCF client:
A client-application construct that exposes the service operations as methods (in the .NET Framework programming language of your choice, such as Visual Basic or Visual C#). Any application can host a WCF client, including an application that hosts a service. Therefore, it is possible to create a service that includes WCF clients of other services. A WCF client can be automatically generated by using the ServiceModel Metadata Utility Tool (Svcutil.exe) and pointing it at a running service that publishes metadata.
metadata:

In a service, describes the characteristics of the service that an external entity needs to understand to communicate with the service. Metadata can be consumed by the ServiceModel Metadata Utility Tool (Svcutil.exe) to generate a WCF client and accompanying configuration that a client application can use to interact with the service. The metadata exposed by the service includes XML schema documents, which define the data contract of the service, and WSDL documents, which describe the methods of the service. When enabled, metadata for the service is automatically generated by WCF by inspecting the service and its endpoints. To publish metadata from a service, you must explicitly enable the metadata behavior.
security:

In WCF, includes confidentiality (encryption of messages to prevent eavesdropping), integrity (the means for detection of tampering with the message), authentication (the means for validation of servers and clients), and authorization (the control of access to resources). These functions are provided by either leveraging existing security mechanisms, such as TLS over HTTP (also known as HTTPS), or by implementing one or more of the various WS-* security specifications.
transport security mode:

Specifies that confidentiality, integrity, and authentication are provided by the transport layer mechanisms (such as HTTPS). When using a transport like HTTPS, this mode has the advantage of being efficient in its performance, and well understood because of its prevalence on the Internet. The disadvantage is that this kind of security is applied separately on each hop in the communication path, making the communication susceptible to a "man in the middle" attack.
message security mode:

Specifies that security is provided by implementing one or more of the security specifications, such as the specification named Web Services Security: SOAP Message Security. Each message contains the necessary mechanisms to provide security during its transit, and to enable the receivers to detect tampering and to decrypt the messages. In this sense, the security is encapsulated within every message, providing end-to-end security across multiple hops. Because security information becomes part of the message, it is also possible to include multiple kinds of credentials with the message (these are referred to as claims). This approach also has the advantage of enabling the message to travel securely over any transport, including multiple transports between its origin and destination. The disadvantage of this approach is the complexity of the cryptographic mechanisms employed, resulting in performance implications.
transport with message credential security mode:

Specifies the use of the transport layer to provide confidentiality, authentication, and integrity of the messages, while each of the messages can contain multiple credentials (claims) required by the receivers of the message.
WS-*
Shorthand for the growing set of Web Service (WS) specifications, such as WS-Security, WS-ReliableMessaging, and so on, that are implemented in WCF.