<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>DOT NET RULES</title>
	<atom:link href="https://dotnetstories.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://dotnetstories.wordpress.com</link>
	<description>Yes, to dance beneath the diamond sky with one hand waving free</description>
	<lastBuildDate>Sat, 28 Jan 2012 00:09:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='dotnetstories.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/1a14469d4b7ba9e0f89bffef42cef6b5?s=96&#038;d=https%3A%2F%2Fs-ssl.wordpress.com%2Fi%2Fbuttonw-com.png</url>
		<title>DOT NET RULES</title>
		<link>https://dotnetstories.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://dotnetstories.wordpress.com/osd.xml" title="DOT NET RULES" />
	<atom:link rel='hub' href='https://dotnetstories.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Using WCF Data Services in WPF applications</title>
		<link>https://dotnetstories.wordpress.com/2012/01/22/using-wcf-data-services-in-wpf-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2012/01/22/using-wcf-data-services-in-wpf-applications/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 01:23:00 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>
		<category><![CDATA[VS 2010]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[WCF Service]]></category>
		<category><![CDATA[SOAP]]></category>
		<category><![CDATA[ODATA]]></category>
		<category><![CDATA[POX]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1694</guid>
		<description><![CDATA[In this post I will provide you with hands-on examples on how to retrieve data from a WCF Data Service and bind the data to WPF data bindable controls that reside inside a WPF window.The client application in this case will be a WPF application again.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1694&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I will provide you with hands-on examples on how to retrieve data from a <strong>WCF Data Service</strong> and bind the data to WPF data bindable controls that reside inside a WPF window.The client application in this case will be a WPF application again.</p>
<p>I do not know how familiar people are with WCF Data Services.This technology was formerly known as ADO.Net Data Services,codename -&#8221;Astoria&#8221;. In these days we all come across applications that do not just use ADO.Net code to fetch data over the network from an SQL Server database.Applications use data services to find and manipulate data on the web.We can call this service that lives somewhere on a web server and pass it a message and then it is the service&#8217;s job to complete the task and send back to the client application a result. The client application could be a Windows Form application, a WPF application,Silvelight an Ajax enabled web page e.t.c The service certainly does not care who the client is.You call the service the same way in all those technologies.In a nutshell the goal of WCF Data Services is to create a middle tier and then easily consume it from various clients both Internet and windows clients.WCF Data Services use REST (Representation State Transfer). REST thinks of the the web as a collection of resources. Resources could be Text,images,XML. Resources are identified by URIs.A URI looks like as <strong>http://www.mysite.com/Customers.</strong> We can use HTTP verbs to access resources.Those verbs are GET,POST,PUT,DELETE. Under the hood WCF Data Services use <strong>OData</strong> (Open Data Protocol) that helps to expose data as resources that are addressable by URIs.</p>
<p>In Web services, data is transmitted via POX (plain old XML).Having said that, it becomes clear that we do not the added layer that is called SOAP.  WCF Services use SOAP, web services use SOAP.Not all platforms support SOAP.If you use REST it is much easier to access services. Bear in mind that not all services need support for transactions,security,reliability.All the functionality of WCF Data Services when we talk about the .Net platform resides in the <strong>System.Data.Services</strong> dll.In order to create a WCF data service you need to create a data model based on entities. For example we can use Entity Framework for relational data.Obviously we can use a custom LINQ provider for other data sources. In those models each entity has a unique URI.</p>
<p>Let’s move on with our hands-on examples.Ι will provide several examples. In the first one I will use a custom data object. In the second one I will use a database.</p>
<p>I assume that you have access to a version of <strong>SQL Server</strong> and <strong>AdventureWorkLT</strong> database.</p>
<p>If you do not, you can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>. If you need the installation scripts for the sample <strong>AdventureWorksLT</strong> database, click <a href="http://msftdbprodsamples.codeplex.com/wikipage?title=AWLTDocs&amp;ProjectName=msftdbprodsamples" target="_blank">here</a> . We will use our WCF service to get data from the the Customers table of the <strong>AdventureWorksLT</strong> database.</p>
<p>In order to create a WCF Data Service , first we need to create the <strong>Entity Data Model</strong> and then add a new item that is based on the <strong>WCF Data Service</strong> template.</p>
<p>Then we need to point to the Entity Data Model and grant read/write access to entities</p>
<p>1) Launch Visual Studio. I will be using Visual Studio 2010 Ultimate edition. I will be using C# as the development language.</p>
<p>2) Add a WPF application to your solution. Give it a meaningful name. I named mine <strong>WpfWcfDataServiceApplication</strong>.</p>
<p>3) Add an empty ASP.Net Web application to your solution.This application will host the WCF Data Service.Give it a meaningful name.I have named mine <strong>HostWCFDataService</strong></p>
<p><strong></strong>4) The next step is to create the entity data model.Add this item to your ASP.net Web application project.Add an ADO.NET Entity Data Model. Ι have named mine <strong>AdventureWorksLT.edmx</strong>. I will generate the model from the database. As you see there is a wizard that helps you complete the steps. In the next step of the wizard you need to point to the database. Create a new connection to the database if you do not have one already and click <strong>Next</strong>.Select all the objects in the <em>Tables</em> and click <strong>Finish</strong>.</p>
<p>In the Entity Model Designer window you will see your new entity data model. Have a look at the entities and their relationships.</p>
<p>5) Add a new item (our service) to the ASP.Net Web application project.  Add a  WCF Data Service.Give it a meaningful name.I have named it <strong>WCFDataService.svc</strong>.</p>
<p>6) Now I need to configure my WCF Data Service.I need to specify the class that contains my entities. In my case this is &#8220;<em>AdventureWorksLTEntities</em>&#8220;.We also need to specify some access rules that the client applications will have on the entities through the service. We want all our entities to be visible and readable from all clients.</p>
<p>The source code for the <strong>WCFDataService.svc.cs</strong> file follows.</p>
<p><pre class="brush: csharp;">
namespace HostWCFDataService
{
public class WCFDataService : DataService&lt;&lt;strong&gt;AdventureWorksLTEntities&lt;/strong&gt;&gt;
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
// config.SetEntitySetAccessRule(&quot;MyEntityset&quot;, EntitySetRights.AllRead);
// config.SetServiceOperationAccessRule(&quot;MyServiceOperation&quot;, ServiceOperationRights.All);
&lt;strong&gt; config.SetEntitySetAccessRule(&quot;*&quot;, EntitySetRights.AllRead);&lt;/strong&gt;
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
}
</pre></p>
<p>7) View your web service in the browser. In my case it is (http://localhost:1741/WCFDataService.svc/) and I can view all the entities.</p>
<p>Because according to REST all resources have a URI we can get only the data for the <strong>Customers</strong> entity.We can do that by passing to the service this <strong>URI</strong>.</p>
<p><strong>http://localhost:1741/WCFDataService.svc/Customers</strong></p>
<p>The WCF Data Service will return XML data which contains information about all the customers in the entity. This is plain old XML.</p>
<p>In a similar fashion you can get data for only a customer. The service will send back the correct information in XML format as long as we pass it (through GET) a valid URI.</p>
<p>In this case I will pass it <strong>http://localhost:1741/WCFDataService.svc/Customers(1)</strong> , if I am interested in the first customer.Ηave a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/rest1.jpg"><img class="aligncenter size-large wp-image-1698" title="rest1" src="http://dotnetstories.files.wordpress.com/2012/01/rest1.jpg?w=1024&#038;h=576" alt="" width="1024" height="576" /></a></p>
<p>I hope by now that it is quite evident to all what the similarities / differences of SOAP and REST.</p>
<p>8) Now we need to create our simple WPF application and call the WCF Data service.We need to build our UI first.We will add a <strong>ListBox</strong> control. The value of the <strong>CompanyName</strong> field for each record in the Customer table of the database (CompanyName property of the Customer entity in our EDM) will appear in the <strong>ListBox</strong> control. When the user selects a value the FirstName and LastName values will also appear for that record in a simple <strong>TextBlock</strong> control.</p>
<p>The whole code for the <strong>MainWindow.xaml</strong> follows.</p>
<p><pre class="brush: xml;">

&lt;Window x:Class=&quot;WpfWcfDataServiceApplication.MainWindow&quot;
xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
Title=&quot;Customers&quot; Height=&quot;500&quot; Width=&quot;500&quot;
WindowStartupLocation=&quot;CenterScreen&quot;
Loaded=&quot;Window_Loaded&quot;&gt;
&lt;Grid&gt;
&lt;StackPanel&gt;
&lt;ListBox Name=&quot;customersListBox&quot;
Height=&quot;400&quot; Margin=&quot;10&quot;
BorderBrush=&quot;Black&quot;
DisplayMemberPath=&quot;CompanyName&quot;
SelectionChanged=
&quot;customersListBox_SelectionChanged&quot; /&gt;
&lt;TextBlock Name=&quot;customerTextBlock&quot; Margin=&quot;10&quot; Background=&quot;#FFBAABC1&quot; FontFamily=&quot;Arial&quot; FontSize=&quot;14&quot; /&gt;
&lt;/StackPanel&gt;
&lt;/Grid&gt;
&lt;/Window&gt;
</pre></p>
<p>9) Now we need to add a Service reference to our client application. Click <strong>Add Service Reference</strong> and then hit  <strong>Discover</strong> button (in the new window that will pop up).You will see the service. Give the namespace a meaningful name (e.g <strong>AdventureWorksDataService</strong>). Visual studio will add the necessary references and generate all the necessary proxy classes that will help us talk to the service.Have a look at the <strong>Reference.cs</strong> file that is inside the <strong>Service References</strong> folder.You must have a good look at the <strong>DataServiceContext</strong> class which represents runtime context of data service.After you add a service reference, in this class there is a property for each entity (e.g ctx.Products).Our <strong>AdventureWorksLTEntities </strong>class inherits from <strong>DataServiceContext</strong> class.This class is also responsible for tracking entities. Another class you should look into is <strong>DataServiceQuery</strong> class which represents a request to the service. This class implements the <strong>IQueryable</strong> interface and that is why we wan write LINQ queries (you will see that later on) to talk to the service.Ιt also returns <strong>IEnumerable</strong> of the requested entity type.Αll queries are instances of the DataQueryService class and all queries belong to a data service context.Those queries are translated into HTTP GET requests and when a response comes back this response is translated into instances of the entity classes. Another very important class is the <strong>DataServiceCollection</strong> class that represents a dynamic collection of entity objects. This class inherits from the <strong>ObservableCollection(T)</strong> and also implements <strong>INotifyPropertyChanged</strong> and<strong> INotifyCollectionChanged</strong> interfaces.</p>
<p>10) Now it is time to write some code in the code behind files to handle the <strong>Window_Loaded</strong>  and the<strong> customersListBox_SelectionChanged </strong> events.</p>
<p><pre class="brush: csharp;">

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private AdventureWorksLTEntities ctx = null;

private Customer customer = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
ctx = new AdventureWorksLTEntities(new Uri(&quot;http://localhost:1741/WCFDataService.svc/&quot;));
var customersQuery =from cust in ctx.Customers select cust;
customersListBox.ItemsSource = customersQuery.ToList();
}

private void customersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
customer = (Customer)customersListBox.SelectedItem;
customerTextBlock.Text = string.Format(&quot;The customer's firstname is {0} and his lastname is  {1}&quot;,
customer.FirstName, customer.LastName);
}
}
</pre></p>
<p>The code is very easy to follow. I am just using standard LINQ queries.</p>
<p>11) Run your application and select a customer (CompanyName). You will get more information for this customer in the <strong>TextBlock</strong> Control.</p>
<p>Have a look at the picture below to see what happens when I run my application</p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/application.jpg"><img class="aligncenter size-large wp-image-1699" title="application" src="http://dotnetstories.files.wordpress.com/2012/01/application.jpg?w=1024&#038;h=581" alt="" width="1024" height="581" /></a></p>
<p>12) Obviously we could loop through our customers and rewrite our code. We could write our code in the <strong>Window_Loaded</strong> event handling routine in a different way. Have a look at the code below.</p>
<p><pre class="brush: csharp;">

/// &lt;summary&gt;
/// Interaction logic for MainWindow.xaml
/// &lt;/summary&gt;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private AdventureWorksLTEntities ctx = null;
private Customer customer = null;
private List&lt;Customer&gt; customersList = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
ctx = new AdventureWorksLTEntities(new Uri(
&quot;http://localhost:1741/WCFDataService.svc/&quot;));
//var customersQuery =
//  from cust in ctx.Customers
//  select cust;
//customersListBox.ItemsSource = customersQuery.ToList();

customersList = new List&lt;Customer&gt;();
foreach (Customer cust in ctx.Customers)
{
customersList.Add(cust);
}
customersListBox.ItemsSource = customersList;

}

private void customersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
customer = (Customer)customersListBox.SelectedItem;
customerTextBlock.Text = string.Format(
&quot;The customer's firstname is {0} and his lastname is  {1}&quot;,
customer.FirstName, customer.LastName);
}
}

</pre></p>
<p>13) I will create another window. In this window I will get the information for a specific customer. I will have a textbox control in the UI and the user will insert the <strong>Customer ID</strong> and hit the <strong>Find</strong> button. Then the information for that customer will be displayed in the textbox controls that are also part of the UI.  Add another item in your WPF application, a WPF window. Name it <strong>GetCustomer.xaml</strong>. In order to launch this window from the <strong>MainWindow.xaml</strong> we need to modify the XAML in this window and add a button.The XAML for the <strong>MainWindow.xaml</strong> is</p>
<p><pre class="brush: xml;">

&lt;Grid&gt;
&lt;StackPanel&gt;
&lt;ListBox Name=&quot;customersListBox&quot;
Height=&quot;400&quot; Margin=&quot;10&quot;
BorderBrush=&quot;Black&quot;
DisplayMemberPath=&quot;CompanyName&quot;
SelectionChanged=
&quot;customersListBox_SelectionChanged&quot; /&gt;
&lt;TextBlock Name=&quot;customerTextBlock&quot;
Margin=&quot;10&quot; Background=&quot;#FFBAABC1&quot; FontFamily=&quot;Arial&quot; FontSize=&quot;14&quot; /&gt;
&lt;Button Name=&quot;btnGetCustomer&quot; Background=&quot;Brown&quot; BorderBrush=&quot;Azure&quot; Content=&quot;GetCustomerData&quot;

FontWeight=&quot;Bold&quot; FontFamily=&quot;Batang&quot; FontSize=&quot;14&quot; Width=&quot;200&quot; Height=&quot;100&quot; HorizontalAlignment=&quot;Center&quot;
VerticalAlignment=&quot;Center&quot; Click=&quot;btnGetCustomer_Click&quot;&gt;&lt;/Button&gt;
&lt;/StackPanel&gt;
&lt;/Grid&gt;

</pre></p>
<p>We need to add some code in the button click event handling routine.We need to change the <strong>MainWindow.xaml.cs</strong> code.</p>
<p><pre class="brush: csharp;">

private void btnGetCustomer_Click(object sender, RoutedEventArgs e)
{
var getcustomer = new GetCustomer();

getcustomer.Show();
}

</pre></p>
<p>So when the user clicks the button the new window pops up.</p>
<p>14) Now we need to build the UI for the <strong>GetCustomer</strong> window according to the requirements outlined in the previous paragraphs.</p>
<p><pre class="brush: xml;">
&lt;Grid&gt;
&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;50&quot; /&gt;
&lt;RowDefinition Height=&quot;*&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
&lt;TextBox Name=&quot;findTextBox&quot; Margin=&quot;15,3,3,3&quot;
Width=&quot;50&quot; Height=&quot;25&quot; /&gt;
&lt;Button Name=&quot;findButton&quot;
Content=&quot;Find&quot;
Margin=&quot;10,5,5,5&quot; Width=&quot;50&quot; Height=&quot;25&quot;
Click=&quot;findButton_Click&quot;/&gt;
&lt;/StackPanel&gt;
&lt;Grid Name=&quot;customerGrid&quot;
Grid.Row=&quot;1&quot; Margin=&quot;5,0,0,0&quot;
Width=&quot;450&quot; HorizontalAlignment=&quot;Left&quot;&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;150&quot; /&gt;
&lt;ColumnDefinition Width=&quot;*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;TextBlock Text=&quot;Company Name&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=CompanyName}&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;First Name&quot;
Grid.Row=&quot;1&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=FirstName}&quot;
Grid.Row=&quot;1&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Middle Name&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=MiddleName}&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Last Name&quot;
Grid.Row=&quot;3&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=LastName}&quot;
Grid.Row=&quot;3&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Title&quot; Grid.Row=&quot;4&quot;
Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=Title}&quot;
Grid.Row=&quot;4&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Sales Person&quot;
Grid.Row=&quot;5&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=SalesPerson}&quot;
Grid.Row=&quot;5&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Email Address&quot;
Grid.Row=&quot;6&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=EmailAddress}&quot;
Grid.Row=&quot;6&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Phone&quot;
Grid.Row=&quot;7&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=Phone}&quot;
Grid.Row=&quot;7&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
</pre></p>
<p>We add the <strong>TextBox</strong> controls and the <strong>TextBlock</strong> controls. Those <strong>TextBox</strong> controls have their Text property bound to the value that will return the WCF Data Service and basically are the properties of the <strong>Customer</strong> entity. We also have the<strong> TextBox</strong> control that the user will enter the Customer ID and hit the Find button.This is the code for the <strong>GetCustomer.xaml.cs</strong> file.</p>
<p><pre class="brush: csharp;">
public partial class GetCustomer : Window
{
public GetCustomer()
{
InitializeComponent();
}

private AdventureWorksLTEntities ctx = null;
private Customer customer = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
ctx = new AdventureWorksLTEntities(new Uri(
&quot;http://localhost:1741/WCFDataService.svc/&quot;));
}

private void findButton_Click(object sender, RoutedEventArgs e)
{
try
{
int FindID=Convert.ToInt32(findTextBox.Text);
customer =
(from cust in ctx.Customers
where (cust.CustomerID == FindID)
select cust).Single();
customerGrid.DataContext = customer;

}
catch (Exception ex)
{
customerGrid.DataContext = null;
}
}
}
</pre></p>
<p>I am using a simple LINQ query and set the<strong> Grid&#8217;s DataContext</strong> property to the customer entity that the WCF Service returns as XML raw data and the WCF Data Services Client library converts the XML data to a .Net entity.</p>
<p>15) Run your application and hit the button in the <strong>MainWindow</strong> window.In the new window type &#8220;4&#8243; in the textbox control and hit the <strong>Find</strong> button.</p>
<p>Have a look at the picture below to see what happens when I run the application. I am sure that if you followed all the steps so far you will have similar results.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/getcustomer1.jpg"><img class="aligncenter size-large wp-image-1706" title="getcustomer" src="http://dotnetstories.files.wordpress.com/2012/01/getcustomer1.jpg?w=1024&#038;h=579" alt="" width="1024" height="579" /></a></p>
<p>16) Moving on I would like to show you how to find related data in the database through our middle tier, thus the WCF Data service.In this example we will load some information from the <strong>Customer</strong> (table/entity) and then display the related data in the<strong> SalesOrderHeader</strong> (table/entity).I will create another window. In this window I will have various controls. I will have a <strong>ListBox</strong> control where the <strong>CompanyName</strong> values will appear for the customers.When the user clicks a customer from the top <strong>ListBox</strong> control in the second ListBox control just below it the orders will appear and in the tetboxes some more field with values for this particular order .</p>
<p>Add another item in your WPF application, a WPF window. Name it <strong>GetCustomerOders.xaml</strong>. In order to launch this window from the <strong>MainWindow.xaml</strong> we need to modify the XAML in this window and add a button.The XAML for the <strong>MainWindow.xaml</strong> becomes</p>
<p><pre class="brush: xml;">

&lt;Grid&gt;
&lt;StackPanel&gt;
&lt;ListBox Name=&quot;customersListBox&quot;
Height=&quot;400&quot; Margin=&quot;10&quot;
BorderBrush=&quot;Black&quot;
DisplayMemberPath=&quot;CompanyName&quot;
SelectionChanged=
&quot;customersListBox_SelectionChanged&quot; /&gt;
&lt;TextBlock Name=&quot;customerTextBlock&quot;
Margin=&quot;10&quot; Background=&quot;#FFBAABC1&quot; FontFamily=&quot;Arial&quot; FontSize=&quot;14&quot; /&gt;
&lt;Button Name=&quot;btnGetCustomer&quot; Background=&quot;Brown&quot; BorderBrush=&quot;Azure&quot; Content=&quot;GetCustomerData&quot; FontWeight=&quot;Bold&quot; FontFamily=&quot;Batang&quot; FontSize=&quot;14&quot; Width=&quot;200&quot; Height=&quot;100&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; Click=&quot;btnGetCustomer_Click&quot;&gt;&lt;/Button&gt;
&lt;Button Name=&quot;btnGetCustomerOrders&quot; Background=&quot;DimGray&quot; BorderBrush=&quot;Blue&quot; Content=&quot;GetCustomerOrdersData&quot; FontWeight=&quot;Bold&quot; FontFamily=&quot;Batang&quot; FontSize=&quot;14&quot; Width=&quot;200&quot; Height=&quot;100&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; Click=&quot;btnGetCustomerOrders_Click&quot;&gt;&lt;/Button&gt;
&lt;/StackPanel&gt;
&lt;/Grid&gt;

</pre></p>
<p>We need to add some code in the button click event handling routine.We need to change the <strong>MainWindow.xaml.cs</strong> code.</p>
<p><pre class="brush: csharp;">

private void btnGetCustomerOrders_Click(object sender, RoutedEventArgs e)
{
var getcustomerorders = new GetCustomerOders();

getcustomerorders.Show();
}
</pre></p>
<p>17) Now we need to add the XAML code for the <strong>GetCustomerOders.xaml. </strong>We need to have a functional UI before we move on writing our code<strong><br />
</strong></p>
<p><pre class="brush: xml;">
&lt;Window.Resources&gt;
&lt;DataTemplate x:Key=&quot;CustomerTemplate&quot;&gt;
&lt;StackPanel Margin=&quot;0,0,0,5&quot;
Orientation=&quot;Horizontal&quot;&gt;
&lt;TextBlock Margin=&quot;10,0,0,0&quot;
VerticalAlignment=&quot;Center&quot;
Text=&quot;{Binding Path=CompanyName}&quot; /&gt;

&lt;/StackPanel&gt;
&lt;/DataTemplate&gt;
&lt;DataTemplate x:Key=&quot;OrderTemplate&quot;&gt;
&lt;StackPanel Margin=&quot;0,0,0,5&quot;
Orientation=&quot;Horizontal&quot;&gt;
&lt;TextBlock Margin=&quot;10,0,0,0&quot;
VerticalAlignment=&quot;Center&quot;
Text=&quot;{Binding Path=OrderDate}&quot; /&gt;
&lt;TextBlock Text=&quot; (&quot; /&gt;
&lt;TextBlock VerticalAlignment=&quot;Center&quot;
Text=&quot;{Binding Path=SalesOrderID}&quot; /&gt;
&lt;TextBlock Text=&quot;)&quot; /&gt;
&lt;/StackPanel&gt;
&lt;/DataTemplate&gt;
&lt;/Window.Resources&gt;
&lt;Grid&gt;
&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;3*&quot; /&gt;
&lt;RowDefinition Height=&quot;5*&quot; /&gt;
&lt;RowDefinition Height=&quot;2*&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;ListBox Name=&quot;customersListBox&quot; Grid.Row=&quot;0&quot;
ItemTemplate=&quot;{StaticResource CustomerTemplate}&quot;
SelectionChanged=
&quot;customersListBox_SelectionChanged&quot;
Margin=&quot;10&quot;
BorderBrush=&quot;Black&quot; /&gt;
&lt;ListBox Name=&quot;ordersListBox&quot; Grid.Row=&quot;1&quot;
ItemTemplate=&quot;{StaticResource OrderTemplate}&quot;
SelectionChanged=
&quot;ordersListBox_SelectionChanged&quot;
Margin=&quot;10&quot;
BorderBrush=&quot;Black&quot; /&gt;
&lt;Grid Name=&quot;OrdersGrid&quot; Grid.Row=&quot;2&quot; Margin=&quot;5,0,0,0&quot;
Width=&quot;600&quot; HorizontalAlignment=&quot;Left&quot; &gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;125&quot; /&gt;
&lt;ColumnDefinition Width=&quot;200&quot; /&gt;
&lt;ColumnDefinition Width=&quot;125&quot; /&gt;
&lt;ColumnDefinition Width=&quot;150&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;TextBlock Text=&quot;Due Date&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=DueDate}&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Ship Date&quot;
Grid.Row=&quot;1&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=ShipDate}&quot;
Grid.Row=&quot;1&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Modified Date&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=ModifiedDate}&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Status&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;2&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=Status}&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;3&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Sub Total&quot;
Grid.Row=&quot;1&quot; Grid.Column=&quot;2&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=SubTotal}&quot;
Grid.Row=&quot;1&quot; Grid.Column=&quot;3&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Comment&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;2&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=Comment}&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;3&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
&lt;/Window&gt;
</pre></p>
<p>Now I have my UI in Xaml and I must implement the event handling routines in the code behind. I handle the <strong>Window_Loaded</strong> event where I load the <strong>CompanyName</strong> value for every record in the <strong>Customers</strong> table. Then I handle the <strong>customersListBox_SelectionChanged</strong> event where I load in the <strong>ordersListBox</strong> the <strong>OrderDate</strong> and the <strong>SalesOrderID</strong> for the selected customer.Finally when the value in the <strong>ordersListBox</strong> is selected more information about this order is displayed in the TextBox controls.</p>
<p>This is the code for the <strong>GetCustomerOders.xaml.cs</strong> file</p>
<p><pre class="brush: csharp;">

public partial class GetCustomerOders : Window
{
public GetCustomerOders()
{
InitializeComponent();
}

private AdventureWorksLTEntities ctx = null;
private Customer customer = null;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ctx = new AdventureWorksLTEntities(new Uri(&quot;http://localhost:1741/WCFDataService.svc/&quot;));
var customersQuery =from cust in ctx.Customers
select cust;
customersListBox.ItemsSource = customersQuery.ToList();
}
private void customersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
customer = (Customer)customersListBox.SelectedItem;
ctx.LoadProperty(customer, &quot;SalesOrderHeaders&quot;);
 foreach (var order in customer.SalesOrderHeaders)
 {
ctx.LoadProperty(order, &quot;OrderDate&quot;);
}
ordersListBox.ItemsSource = customer.SalesOrderHeaders;
}
private void ordersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
OrdersGrid.DataContext =(SalesOrderHeader)ordersListBox.SelectedItem;
}
}

</pre></p>
<p>Have a look at the picture below to see what I mean. Run your application and see the results for yourself. You should have similar results.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/related.jpg"><img class="aligncenter size-large wp-image-1709" title="related" src="http://dotnetstories.files.wordpress.com/2012/01/related.jpg?w=1024&#038;h=571" alt="" width="1024" height="571" /></a></p>
<p>Leave a comment if you want the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/vs-2010/'>VS 2010</a>, <a href='https://dotnetstories.wordpress.com/category/wcf-service/'>WCF Service</a>, <a href='https://dotnetstories.wordpress.com/category/wpf/'>WPF</a>, <a href='https://dotnetstories.wordpress.com/category/xaml/'>XAML</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/odata/'>ODATA</a>, <a href='https://dotnetstories.wordpress.com/tag/pox/'>POX</a>, <a href='https://dotnetstories.wordpress.com/tag/soap/'>SOAP</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1694/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1694/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1694&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2012/01/22/using-wcf-data-services-in-wpf-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/rest1.jpg?w=1024" medium="image">
			<media:title type="html">rest1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/application.jpg?w=1024" medium="image">
			<media:title type="html">application</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/getcustomer1.jpg?w=1024" medium="image">
			<media:title type="html">getcustomer</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/related.jpg?w=1024" medium="image">
			<media:title type="html">related</media:title>
		</media:content>
	</item>
		<item>
		<title>Using WCF services in WPF applications</title>
		<link>https://dotnetstories.wordpress.com/2012/01/17/using-wcf-services-in-wpf-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2012/01/17/using-wcf-services-in-wpf-applications/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 19:42:59 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[VS 2010]]></category>
		<category><![CDATA[WCF Service]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1681</guid>
		<description><![CDATA[In this post I will provide you with hands-on examples on how to retrieve data from a WCF service and bind the data to a WPF data bindable control that resides inside a WPF window. This is not going to be a post that will look into WCF Services in great detail. In the near future I will be writing posts on WCF.In a nutshell WCF provides a unified programming model for building service oriented applications. <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1681&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I will provide you with hands-on examples on how to retrieve data from a WCF service and bind the data to a WPF data bindable control that resides inside a WPF window. This is not going to be a post that will look into WCF Services in great detail. In the near future I will be writing posts on WCF.In a nutshell WCF provides a unified programming model for building service oriented applications. You write your service once and you can expose it (through endpoints) to multiple protocols without having to rewrite the service.The service is written in a .Net language and consists of operations that are exposed so clients can execute them.When you host the service you make it available to clients by providing one or more endpoints. Bindings are used to determine how a service endpoint will communicate with a client endpoint.</p>
<p>Obviously we can use other ways to talk to data sources. We can use  ADO.Net, datasets, LinqToSQL, Entity Framework,Web services,WCF data services and custom data objects to fetch data from a data source and bind it our WPF controls.</p>
<p>Let&#8217;s move on with our hands-on examples.Ι will provide several examples. In the first one I will use a custom data object. In the second one I will use a database.</p>
<p>I assume that you have access to a version of <strong>SQL Server</strong> and <strong>AdventureWorkLT</strong> database.</p>
<p>If you do not, you can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>. If you need the installation scripts for the sample <strong>AdventureWorksLT</strong> database, click <a href="http://msftdbprodsamples.codeplex.com/wikipage?title=AWLTDocs&amp;ProjectName=msftdbprodsamples" target="_blank">here</a> . We will use our WCF service to get data from the the Customers table of the <strong>AdventureWorksLT</strong> database.</p>
<p>1) Launch Visual Studio. I will be using Visual Studio 2010 Ultimate edition. I will be using C# as the development language.</p>
<p>2) Add a WPF application to your solution. Give it a meaningful name. Add a  WCF Service application to your solution.Give it a meaningful name.Visual Studio will create the necessary files.Rename the service from Service1 (IService1) to <strong>FootballerService (IFootballerService)</strong>.</p>
<p>3) Now we are ready to write some code in the <strong>IFootballerService.cs</strong> file.We need to define the method will get the customers from the database table.</p>
<p><pre class="brush: csharp;">

[ServiceContract]
public interface IFootballerService
{

[OperationContract]

List&lt;Footballer&gt; GetFootballers();

// TODO: Add your service operations here
}
</pre></p>
<p>4) I will also need to create a <strong>DataContract</strong>.Since I pass instances of the <strong>Footballer</strong> object I need to do that.</p>
<p>This is the code.</p>
<p><pre class="brush: csharp;">
[DataContract]
public class Footballer
{

[DataMember]
public int FootballerID { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Position { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string PlaysFor { get; set; }

public Footballer( int id,string name,string surname,string position,int age,string playsfor)
{
this.FootballerID = id;
this.FirstName = name;
this.LastName = surname;
this.Position = position;
this.Age = age;
this.PlaysFor = playsfor;
}

}

</pre></p>
<p>I am decorating the <strong>Footballer</strong> class as <strong>DataContract</strong>.We need to do that so .Net WCF serialiser can take those .Net objects and serialise them to XML so they can passed back to the clients.It knows how to do that with simple types but not with more complex ones. So that is why we must tell it.Do not forget that we still exchange XML SOAP messages over HTTP(or TCP).</p>
<p>5) Now we are ready to implement the Interface.We open the <strong>FootballerService.svc.cs</strong> file and we write the following code.</p>
<p><pre class="brush: csharp;">
public class FootballerService : IFootballerService
{
public List&lt;Footballer&gt; GetFootballers()
{
   var footballers = new List&lt;Footballer&gt;();
   footballers.Add(new Footballer(1, &quot;Steven&quot;, &quot;Gerrard&quot;, &quot;Attacking Midfielder&quot; ,31 ,&quot;Liverpool&quot;));
   footballers.Add(new Footballer(2, &quot;Lionel&quot;, &quot;Messi&quot;, &quot;Striker&quot;,24,&quot;Barcelona&quot;));
   footballers.Add(new Footballer(3, &quot;Ryan&quot;, &quot;Giggs&quot;, &quot;Winger&quot;, 38, &quot;Man United&quot;));
   return footballers;
}
}

</pre></p>
<p>6) Test your service. The host ( the service must be hosted somewhere ) in our example is the ASP.Net development server.</p>
<p>7) Now let&#8217;s call the service from the client. The first thing to do is to add a <strong>service reference</strong> to the WPF application (client project).</p>
<p>Click <strong>Add Service Reference</strong> and then hit  <strong>Discover</strong> button (in the new window that will pop up).You will see the service. Give the namespace a meaningful name (CustomersServices).Click <strong>Advanced</strong> and then in the <strong>Data type &#8211; Collection type</strong>, select the <strong>System.Collections.ObjectModel.ObservableCollection</strong>  and click <strong>OK</strong>.Visual Studio will generate all the necessary proxy classes.</p>
<p>8) Let&#8217;s add some xaml code on the WPF window.I will use  a ListBox and TextBlock control.</p>
<p><pre class="brush: xml;">

&lt;Grid&gt;
&lt;StackPanel&gt;

&lt;ListBox Name=&quot;FootballerBox&quot; Height=&quot;300&quot; Margin=&quot;28&quot; BorderBrush=&quot;Cyan&quot;
DisplayMemberPath=&quot;FirstName&quot; SelectionChanged=&quot;FootballerBox_SelectionChanged&quot; /&gt;
&lt;TextBlock Name=&quot;FootballerText&quot; Margin=&quot;20,2,2,2&quot;&gt;&lt;/TextBlock&gt;

&lt;/StackPanel&gt;
&lt;/Grid&gt;

</pre></p>
<p>9) Now we need to add some simple code in the code behind file and for the <strong>Window_Loaded</strong> events and <strong>FootballerBox_SelectionChanged</strong> event handling routines.</p>
<p><pre class="brush: csharp;">

/// &lt;summary&gt;
/// Interaction logic for MainWindow.xaml
/// &lt;/summary&gt;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private FootballerServices.FootballerServiceClient footballersService = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{

footballersService = new FootballerServices.FootballerServiceClient();
try
{
FootballerBox.ItemsSource = footballersService.GetFootballers();
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}

}

private void FootballerBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var footballer = (FootballerServices.Footballer)FootballerBox.SelectedItem;

FootballerText.Text = String.Format(&quot;His surname is {0}. His age is {1} and the position he plays is {2}.He plays for {3}&quot;, footballer.LastName,footballer.Age,footballer.Position,footballer.PlaysFor);

}
}

</pre></p>
<p>10) Run your application. You will see the ListBox control populated from the data the <strong>WCF</strong> service sends to it.When you select a name from the listbox you will see more details for the footballer on the textblock control.</p>
<p>11) Now we will move to the second example.In this example we will get data from the <strong>AdventureWorksLT</strong> database. Close your solution and create a new WPF application.Give it an appropriate name.</p>
<p>12) Let me explain what I want to do in the example. I will have my main WPF window (<strong>MainWindow.xaml</strong>). I will place a button on it.Then I will create another WPF window and I will name it <strong>GetCustomers</strong> (<strong>Getcutomers.xaml</strong>).In this window I will have a ListBox control and various textblock and textbox controls. In the ListBox control I will only get the <strong>CompanyName</strong> of the customer.When the user selects the<strong> CompanyName</strong> in the <strong>ListBox</strong> control more information will appear in the TextBox controls.This is our client application.Let&#8217;s have a look in the markup for the <strong>MainWindow.xaml</strong> window.</p>
<p><pre class="brush: xml;">

&lt;Grid&gt;
&lt;StackPanel&gt;

&lt;Button Content=&quot;Get a list of customers&quot;
Name=&quot;listOfCustomersButton&quot;
MaxWidth=&quot;200&quot; MinHeight=&quot;35&quot; Margin=&quot;5,25,5,5&quot;
Click=&quot;listOfCustomersButton_Click&quot;/&gt;

&lt;/StackPanel&gt;
&lt;/Grid&gt;

</pre></p>
<p>Add another window in the WPF application.Name it <strong>GetCustomers</strong> (<strong>GetCustomers.xaml</strong>). Now let&#8217;s have a look at the code behind for the <strong>MainWindow.xaml.cs</strong>.</p>
<p><pre class="brush: csharp;">

private void listOfCustomersButton_Click(object sender, RoutedEventArgs e)
{
        var getCustomers = new GetCustomers();
        getCustomers.Show();
}

</pre></p>
<p>13)We need to create a service that will get the data from the underlying database. Create a WCF Service Application and give it an appropriate name. Now you have two projects in your solution.Name the service <strong>AdventureWorksService</strong> (IAdventureWorksService.cs). Now we need to define the service contract, the public methods that can be accessible from the client and finally the <strong>DataContracts</strong>.The code follows.</p>
<p><pre class="brush: csharp;">

[ServiceContract]
public interface IAdventureWorksService
{
[OperationContract]
List&lt;CustomerSummary&gt; GetCustomers();

[OperationContract]
Customer GetCustomer(int customerID);

}

[DataContract]
public class CustomerSummary
{
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public string CompanyName { get; set; }
//[DataMember]
//public string City { get; set; }
//[DataMember]
//public string Country { get; set; }
}

[DataContract]
public class Customer
{
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string SalesPerson { get; set; }
[DataMember]
public string EmailAddress { get; set; }
[DataMember]
public string Phone { get; set; }

}

</pre></p>
<p>I am going to have two methods.The first one <strong>GetCustomers</strong> (which will be implemented later on and used to bind the company name to the <strong></strong>ListBox control) will return the CustomerID and CompanyName fields from the database.The second method <strong>GetCustomer</strong> will return more information about the Customer when we pass it the CustomerID as an input parameter.The fields we are interested in are<strong> CustomerID,Title,FirstName,MiddleName,LastName,CompanyName,SalesPerson,EmailAddress,Phone</strong></p>
<p>This is the method that will populate the variousTextbox controls in the <strong>GetCustomers</strong> window when the user selects the Company Name from the ListBox control.</p>
<p>That is why need to define two classes <strong>Customer</strong> and <strong>CustomerSummary</strong>.</p>
<p>14) Now we need to implement the methods in the <strong>AdventureWorksService.svc.cs</strong> file.The code follows.</p>
<p><pre class="brush: csharp;">

public class AdventureWorksService : IAdventureWorksService
{

private CustomerSummary customerSummary = null;
private List&lt;CustomerSummary&gt; customers = null;
private Customer customer = null;

string connectionString = ConfigurationManager.ConnectionStrings[&quot;AdventureWorksLTConnectionString&quot;].ConnectionString;

public List&lt;CustomerSummary&gt; GetCustomers()
{
customers = new List&lt;CustomerSummary&gt;();

using (var cnn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(
&quot;SELECT TOP 5  CustomerID, CompanyName &quot; +
&quot;FROM SalesLT.Customer ORDER BY CustomerID&quot;, cnn))
{
cnn.Open();
using (SqlDataReader CustomersReader =
cmd.ExecuteReader())
{
while (CustomersReader.Read())
{
customerSummary = new CustomerSummary();
customerSummary.CustomerId =
CustomersReader.GetInt32(0);
customerSummary.CompanyName =
CustomersReader.GetString(1);

customers.Add(customerSummary);
}
}
}
}
return customers;
}

public Customer GetCustomer(int customerID)
{
customer = new Customer();

using (var cnn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(
&quot;SELECT CustomerID,Title,FirstName,MiddleName,LastName,CompanyName,SalesPerson,EmailAddress,Phone FROM SalesLT.Customer &quot; +
&quot;WHERE CustomerID = @customerId&quot;, cnn))
{
cmd.Parameters.Add(new SqlParameter(
&quot;@customerId&quot;, customerID));
cnn.Open();
using (SqlDataReader CustomersReader =
cmd.ExecuteReader())
{
while (CustomersReader.Read())
{
customer.CustomerId =
CustomersReader.GetInt32(0);

if (CustomersReader.IsDBNull(1) == true)
{
customer.Title = string.Empty;
}
else
{
customer.Title =
CustomersReader.GetString(1);
}

customer.FirstName =
CustomersReader.GetString(2);

if (CustomersReader.IsDBNull(3) == true)
{
customer.MiddleName = string.Empty;
}
else
{
customer.MiddleName =
CustomersReader.GetString(3);
}

customer.LastName =
CustomersReader.GetString(4);

if (CustomersReader.IsDBNull(5) == true)
{
customer.CompanyName = string.Empty;
}
else
{
customer.CompanyName =
CustomersReader.GetString(5);
}
if (CustomersReader.IsDBNull(6) == true)
{
customer.SalesPerson = string.Empty;
}
else
{
customer.SalesPerson =
CustomersReader.GetString(6);
}
if (CustomersReader.IsDBNull(7) == true)
{
customer.EmailAddress = string.Empty;
}
else
{
customer.EmailAddress =
CustomersReader.GetString(7);
}
if (CustomersReader.IsDBNull(8) == true)
{
customer.Phone = string.Empty;
}
else
{
customer.Phone =
CustomersReader.GetString(8);
}

}
}
}
}
return customer;
}

}

</pre></p>
<p>Let me explain what I am doing here.I am getting the connection string</p>
<pre>   string connectionString =
ConfigurationManager.ConnectionStrings["AdventureWorksLTConnectionString"].ConnectionString;</pre>
<p>In the web.config you need to add those lines of code.</p>
<p><pre class="brush: xml;">

&lt;connectionStrings&gt;

&lt;add name=&quot;AdventureWorksLTConnectionString&quot;
connectionString=&quot;Data Source=.;Initial Catalog=AdventureWorksLT;Integrated Security=True&quot; /&gt;

&lt;/connectionStrings&gt;

</pre></p>
<p>For the <strong>GetCustomers</strong> method I create a new connection object and open the connection. I create a new SQLCommand object that holds the query and I execute the query. I loop through the results of the query and get the <strong>CustomerID</strong> and <strong>CompanyName</strong> values for each customer.</p>
<p>For the <strong>GetCustomer</strong> method, I create a new connection object and open the connection. I create a new SQLCommand object that holds the query and I execute the query.In this query I need to pass the parameter as well and I do that.Then I loop through the results.As you see I also take into account if the field has the NULL value.</p>
<p>Finally I return a customer object that holds the values of <strong>CustomerID,Title,FirstName,MiddleName,LastName,CompanyName,SalesPerson,EmailAddress,Phone</strong> for the particular <strong>CustomerID</strong> value I pass as the input parameter.</p>
<p>15) Now we need to add the markup for the <strong>GetCustomers.xaml</strong> page.The markup follows. You need to paste it in your own window and it will make sense.In order for you to understand what is going on it will be handy if you know a few things of how data binding works in WPF.</p>
<p><pre class="brush: xml;">

&lt;Window.Resources&gt;
&lt;DataTemplate x:Key=&quot;CustomerTemplate&quot;&gt;
&lt;StackPanel Margin=&quot;0,0,0,5&quot;
Orientation=&quot;Horizontal&quot;&gt;
&lt;TextBlock Margin=&quot;10,0,0,0&quot;
VerticalAlignment=&quot;Center&quot;
Text=&quot;{Binding Path=CompanyName}&quot; /&gt;
&lt;/StackPanel&gt;
&lt;/DataTemplate&gt;
&lt;/Window.Resources&gt;
&lt;Grid&gt;
&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;250&quot; /&gt;
&lt;RowDefinition Height=&quot;*&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;ListBox Name=&quot;customersListBox&quot;
Grid.Row=&quot;0&quot; Margin=&quot;10&quot;
BorderBrush=&quot;Black&quot;
ItemTemplate=&quot;{StaticResource CustomerTemplate}&quot;
SelectionChanged=&quot;customersListBox_SelectionChanged&quot;/&gt;
&lt;Grid Name=&quot;customerGrid&quot; Grid.Row=&quot;1&quot; Margin=&quot;5,0,0,0&quot; Width=&quot;450&quot; HorizontalAlignment=&quot;Left&quot;&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;150&quot; /&gt;
&lt;ColumnDefinition Width=&quot;*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;RowDefinition Height=&quot;Auto&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;TextBlock Text=&quot;Title&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot;
VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot;
Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=Title}&quot;
Grid.Row=&quot;0&quot; Grid.Column=&quot;1&quot;
Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;First Name&quot;  Grid.Row=&quot;1&quot; Grid.Column=&quot;0&quot;  VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=FirstName}&quot; Grid.Row=&quot;1&quot; Grid.Column=&quot;1&quot; Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Middle Name&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;0&quot; VerticalAlignment=&quot;Center&quot;
HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=MiddleName}&quot;
Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot; Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Last Name&quot; Grid.Row=&quot;3&quot; Grid.Column=&quot;0&quot; VerticalAlignment=&quot;Center&quot;  HorizontalAlignment=&quot;Left&quot;  Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=LastName}&quot; Grid.Row=&quot;3&quot; Grid.Column=&quot;1&quot;Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Company Name&quot; Grid.Row=&quot;4&quot; Grid.Column=&quot;0&quot; VerticalAlignment=&quot;Center&quot;   HorizontalAlignment=&quot;Left&quot;   Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=CompanyName}&quot; Grid.Row=&quot;4&quot; Grid.Column=&quot;1&quot; Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Sales Person&quot; Grid.Row=&quot;5&quot; Grid.Column=&quot;0&quot;  VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Left&quot;  Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=SalesPerson}&quot; Grid.Row=&quot;5&quot; Grid.Column=&quot;1&quot; Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Email&quot; Grid.Row=&quot;6&quot; Grid.Column=&quot;0&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=EmailAddress}&quot; Grid.Row=&quot;6&quot; Grid.Column=&quot;1&quot; Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
&lt;TextBlock Text=&quot;Phone&quot; Grid.Row=&quot;7&quot; Grid.Column=&quot;0&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,0,0,0&quot; /&gt;
&lt;TextBox Text=&quot;{Binding Path=Phone}&quot; Grid.Row=&quot;7&quot; Grid.Column=&quot;1&quot; Margin=&quot;3&quot; Height=&quot;25&quot; /&gt;
HorizontalAlignment=&quot;Left&quot;  Margin=&quot;10,0,0,0&quot; /&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
&lt;/Window&gt;

</pre></p>
<p>16) we need to add a <strong>service reference</strong>to the WPF application (client project).</p>
<p>Click <strong>Add Service Reference</strong> and then hit  <strong>Discover</strong> button (in the new window that will pop up).You will see the service. Give the namespace a meaningful name (WCFAdventureWorksServices).Click <strong>Advanced</strong> and then in the <strong>Data type &#8211; Collection type</strong>, select the <strong>System.Collections.ObjectModel.ObservableCollection</strong>  and click <strong>OK</strong>.Visual Studio will generate all the necessary proxy classes.</p>
<p>17) The code behind for the <strong>GetCustomers.xaml.cs</strong> file follows.The code is extremely easy to follow. I use the Window_Loaded event to bind data to the ListBox control.I do that by setting the <strong>ItemSource</strong> property of the <strong>ListBox</strong> (CustomersListBox) control to the <strong>GetCustomers</strong> method of the service.When the user selects a value from the <strong>ListBox</strong> the <strong>Selection_Changed</strong> event is fired and I set the <strong>DataContext</strong> property of the <strong>Grid</strong> to the values of the <strong>GetCustomer</strong> method.</p>
<p><pre class="brush: csharp;">

private WCFAdventureWorksServices.AdventureWorksServiceClient
advService = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
advService = new
WCFAdventureWorksServices.AdventureWorksServiceClient();
try
{
customersListBox.ItemsSource =
advService.GetCustomers();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void customersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int customerID =
((WCFAdventureWorksServices.CustomerSummary)
((ListBox)sender).SelectedItem).CustomerId;
try
{
customerGrid.DataContext = advService.GetCustomer(customerID);

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

</pre></p>
<p>17) Run your application and make sure that everything works as expected. Click on the Company Names values in the <strong>ListBox</strong> control and see the details for each customer appearing in the <strong>TextBox</strong> controls.</p>
<p>Leave a comment if you need the source code.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/vs-2010/'>VS 2010</a>, <a href='https://dotnetstories.wordpress.com/category/wcf-service/'>WCF Service</a>, <a href='https://dotnetstories.wordpress.com/category/wpf/'>WPF</a>, <a href='https://dotnetstories.wordpress.com/category/xaml/'>XAML</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1681/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1681/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1681/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1681&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2012/01/17/using-wcf-services-in-wpf-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Windows forms and WPF Interoperability</title>
		<link>https://dotnetstories.wordpress.com/2012/01/09/windows-forms-and-wpf-interoperability/</link>
		<comments>https://dotnetstories.wordpress.com/2012/01/09/windows-forms-and-wpf-interoperability/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 11:53:12 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[Interoperability;Windows Forms;]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1658</guid>
		<description><![CDATA[In this post I will not be investigating at what some people call the "Windows single technology applications" which basically means that we build WinForms apps for the windows operating systems using only Windows Forms controls or alternatively build a windows WPF application using only the built-in or 3rd party WPF controls.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1658&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I will not be investigating at what some people call the &#8220;Windows single technology applications&#8221; which basically means that we build WinForms apps for the windows operating systems using <strong>only</strong> Windows Forms controls or alternatively build a windows WPF application using<strong> only</strong> the built-in or 3rd party WPF controls.</p>
<p>I will be looking into the &#8220;Mixed technology applications&#8221;. In other words how to build Windows Forms applications using both Windows Forms and WPF controls.Moreover how to build WPF applications using both WPF and Windows Forms controls.I will be using C# to build those applications.</p>
<p>I know that many people since the introduction of  WPF have designed and implemented using this awesome new technology introduced with .NET 3.0.</p>
<p>But what about our existing WinForms applications? Are we going to rewrite everything?What about the controls we built for a WinForms application? Are we going to rewrite those too? What about 3rd party controls we have purchased? We do not want to spend time and money to write functionality that we already have got.</p>
<p>In a nutshell we want to have interoperability and that it is possible with the current technologies.It is possible to reuse than recreate.</p>
<p>Let&#8217;s start with our first example. In this example I will show how to add an existing Windows Form to a WPF application.</p>
<p>1) Launch Visual Studio. I will be using Visual Studio 2010 Ultimate edition.</p>
<p>2) Create a new WPF application and give it a name of your choice. Choose C# as the development language.</p>
<p>3) Add a new item to your application, a new Window(WPF). Name it <strong>Footballers.xaml</strong></p>
<p>4) Add the following xaml code to the <strong>MainWindow.xaml</strong> file</p>
<p><pre class="brush: xml;">
&lt;StackPanel&gt;
&lt;Button Content=&quot;Log in&quot; Margin=&quot;5,25,5,5&quot;
MaxWidth=&quot;200&quot; MinHeight=&quot;35&quot;
Name=&quot;loginButton&quot;
Click=&quot;loginButton_Click&quot;/&gt;
&lt;Button Content=&quot;Footballers window&quot; Margin=&quot;5,25,5,5&quot;
MaxWidth=&quot;200&quot; MinHeight=&quot;35&quot;
Name=&quot;footballersWindowButton&quot;
Click=&quot;footballersWindowButton_Click&quot;/&gt;
&lt;Button Content=&quot;Footballers form&quot; Margin=&quot;5,25,5,5&quot;
MaxWidth=&quot;200&quot; MinHeight=&quot;35&quot;
Name=&quot;footballersFormButton&quot;
Click=&quot;footballersFormButton_Click&quot;/&gt;
&lt;Button Content=&quot;About&quot; Margin=&quot;5,25,5,5&quot;
MaxWidth=&quot;200&quot; MinHeight=&quot;35&quot;
Name=&quot;aboutButton&quot;
Click=&quot;aboutButton_Click&quot;/&gt;
&lt;/StackPanel&gt;

</pre></p>
<p>5) Run your application so you can have a feeling on what we are going to build.</p>
<p>6) As you see we have a button that when clicked must launch the <strong>Footballers</strong> window.This is the code to achieve that.</p>
<p><pre class="brush: csharp;">
 private void footballersWindowButton_Click(object sender, RoutedEventArgs e)
{
var fooballers = new Footballers();
fooballers.Show();

}

</pre></p>
<p>7) We have also added an &#8220;About&#8221; button. That will launch an <em>About</em> form. We know that Windows Forms have such functionality and we will utilise it. Add a new item to your application, an <strong>About Box</strong> (Add &#8211;&gt; New Item &#8211;&gt;Windows Forms &#8211;&gt;About Box).Name it <strong>AboutForm</strong>.References are added automatically to the application and the Windows Forms designer pops up showing the &#8220;AboutForm&#8221; form.</p>
<p>8) When you select the <strong>AboutForm</strong> (Windows Form) you will see in the <em>Toolbox</em> area the Windows Forms controls.When you select the .xaml file in the <em>Toolbox </em>the WPF controls will appear.</p>
<p>9) I need to add login functionality to my application. I will use an existing Windows Forms (Login Form) that I have already created. I will add an existing item (a <strong>LoginForm.cs</strong>)  file to my application.</p>
<p>10) In the <strong>MainWindow.xaml</strong> we will add the the code required to launch the <strong>Login form</strong> and the <strong>About form</strong>.The code follows.</p>
<p><pre class="brush: csharp;">
private void loginButton_Click(object sender, RoutedEventArgs e)
{
var login = new LoginForm();
login.Show();
}

private void aboutButton_Click(object sender, RoutedEventArgs e)
{
var about = new AboutForm();
about.Show();
}

</pre></p>
<p>11) Run your application and click the relevant buttons to launch the windows.</p>
<p>12) As you see it is pretty easy to add Window Forms to a <strong>WPF</strong> application. Maybe they use a different graphical subsystem to render but it is very easy to launch window forms from a WPF application. Now I would like to show you how easy it is to share information between the various forms of the application. I want to store the login name in a variable and show it in the <strong>MainWindow</strong>. Add a class file to your application. Name it <strong>General.cs. </strong>This is the code for the static class<strong>. </strong>Basically we define a string (LoginName).<strong><br />
</strong></p>
<p><pre class="brush: csharp;">
public static class General
{
public static string LoginName = string.Empty;

}
</pre></p>
<p>13) Now we will add some code in the <strong>LoginForm.cs</strong> that will store the username the user enters in the form.This is the code</p>
<p><pre class="brush: csharp;">
private void OK_Click(object sender, EventArgs e)
{

General.LoginName = UsernameTextBox.Text;
this.Close();

}
</pre></p>
<p>14) The next step is to change the code in the <strong>MainWindow.xaml.cs</strong> so that when the</p>
<p><pre class="brush: csharp;">

private void loginButton_Click(object sender, RoutedEventArgs e)
{
var login = new LoginForm();

if (login.ShowDialog() == System.Windows.Forms.DialogResult.OK)
MessageBox.Show(&quot;Welcome &quot; + General.LoginName);
}
</pre></p>
<p>15) Run your application and click the <strong>Log in</strong> button. Add a new username and a password and click &#8220;OK&#8221;. You will see the Message box popping up with the name you entered in the login form.With this simple example you see how easy it is to share information among the two forms that are part of different window technologies.</p>
<p>16) Now let&#8217;s add some functionality to the button&#8221;Footballers Window&#8221;.</p>
<p>We will get data from a database and display it in the <strong>Footballers.xaml</strong> window. But we will need a database first. So in my case I have created a small database with a single table.</p>
<p>This is the T-SQL code you need to execute so you can have the same data.</p>
<p><pre class="brush: sql;">

USE [master]
GO

/****** Object:  Database [football]    Script Date: 01/07/2012 15:22:13 ******/
CREATE DATABASE [football] ON  PRIMARY
( NAME = N'football', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\football.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'football_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\football_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [football] SET COMPATIBILITY_LEVEL = 100
GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [football].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO

ALTER DATABASE [football] SET ANSI_NULL_DEFAULT OFF
GO

ALTER DATABASE [football] SET ANSI_NULLS OFF
GO

ALTER DATABASE [football] SET ANSI_PADDING OFF
GO

ALTER DATABASE [football] SET ANSI_WARNINGS OFF
GO

ALTER DATABASE [football] SET ARITHABORT OFF
GO

ALTER DATABASE [football] SET AUTO_CLOSE OFF
GO

ALTER DATABASE [football] SET AUTO_CREATE_STATISTICS ON
GO

ALTER DATABASE [football] SET AUTO_SHRINK OFF
GO

ALTER DATABASE [football] SET AUTO_UPDATE_STATISTICS ON
GO

ALTER DATABASE [football] SET CURSOR_CLOSE_ON_COMMIT OFF
GO

ALTER DATABASE [football] SET CURSOR_DEFAULT  GLOBAL
GO

ALTER DATABASE [football] SET CONCAT_NULL_YIELDS_NULL OFF
GO

ALTER DATABASE [football] SET NUMERIC_ROUNDABORT OFF
GO

ALTER DATABASE [football] SET QUOTED_IDENTIFIER OFF
GO

ALTER DATABASE [football] SET RECURSIVE_TRIGGERS OFF
GO

ALTER DATABASE [football] SET  DISABLE_BROKER
GO

ALTER DATABASE [football] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO

ALTER DATABASE [football] SET DATE_CORRELATION_OPTIMIZATION OFF
GO

ALTER DATABASE [football] SET TRUSTWORTHY OFF
GO

ALTER DATABASE [football] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO

ALTER DATABASE [football] SET PARAMETERIZATION SIMPLE
GO

ALTER DATABASE [football] SET READ_COMMITTED_SNAPSHOT OFF
GO

ALTER DATABASE [football] SET HONOR_BROKER_PRIORITY OFF
GO

ALTER DATABASE [football] SET  READ_WRITE
GO

ALTER DATABASE [football] SET RECOVERY FULL
GO

ALTER DATABASE [football] SET  MULTI_USER
GO

ALTER DATABASE [football] SET PAGE_VERIFY CHECKSUM
GO

ALTER DATABASE [football] SET DB_CHAINING OFF
GO

USE [football]
GO
/****** Object:  Table [dbo].[footballers]    Script Date: 01/07/2012 15:21:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[footballers](
[id] [int] IDENTITY(1,1) NOT NULL,
[firstname] [varchar](50) NOT NULL,
[lastname] [varchar](50) NOT NULL,
[isActive] [bit] NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

SET IDENTITY_INSERT [dbo].[footballers] ON
INSERT [dbo].[footballers] ([id], [firstname], [lastname], [isActive]) VALUES (1, N'Robbie', N'Fowler', 1)
INSERT [dbo].[footballers] ([id], [firstname], [lastname], [isActive]) VALUES (2, N'Steven', N'Gerrard', 1)
INSERT [dbo].[footballers] ([id], [firstname], [lastname], [isActive]) VALUES (3, N'Kenny', N'Dalglish', 0)
SET IDENTITY_INSERT [dbo].[footballers] OFF

}
</pre></p>
<p>Connect to the local instance of SQL Server and in a new query window execute the T-SQL code provided above.</p>
<p>17) In the Visual Studio go to <strong>Data&#8211;&gt;Add New Data Source</strong>&#8230;Add a new data source.In the wizard select <em>Database</em> and click <em>Next</em>. Then select <em>Dataset</em> and click <em>Next</em>.In the next step create a new connection that points to the <em>football</em> database.Press <em>OK</em>. In the wizard click <em>Next</em> and <em>Next</em> again.In the database objects window choose <em>footballers</em> table and finally <em>Finish</em>.Drag and drop the <em>Data Sources</em> window on the <em>Footballers</em> window.Please have a look at the generated code in the <em>Footballers.xaml</em> and <em>Footballers.xaml.cs</em> files.</p>
<p>In my case the code in the <em>Footballers.xaml.cs</em> is the following.</p>
<p><pre class="brush: csharp;">
private void Window_Loaded(object sender, RoutedEventArgs e)
{

WindowsFormToWPF.footballDataSet footballDataSet = ((WindowsFormToWPF.footballDataSet)(this.FindResource(&quot;footballDataSet&quot;)));
// Load data into the table footballers. You can modify this code as needed.
WindowsFormToWPF.footballDataSetTableAdapters.footballersTableAdapter
footballDataSetfootballersTableAdapter = new WindowsFormToWPF.footballDataSetTableAdapters.footballersTableAdapter();
footballDataSetfootballersTableAdapter.Fill(footballDataSet.footballers);
System.Windows.Data.CollectionViewSource footballersViewSource =
((System.Windows.Data.CollectionViewSource)(this.FindResource(&quot;footballersViewSource&quot;)));
footballersViewSource.View.MoveCurrentToFirst();
}
</pre></p>
<p>The code for the <em>Footballers.xaml</em> follows</p>
<p><pre class="brush: xml;">
&lt;Window.Resources&gt;
&lt;my:footballDataSet x:Key=&quot;footballDataSet&quot; /&gt;
&lt;CollectionViewSource x:Key=&quot;footballersViewSource&quot;
Source=&quot;{Binding Path=footballers, Source={StaticResource footballDataSet}}&quot; /&gt;
&lt;/Window.Resources&gt;
&lt;Grid DataContext=&quot;{StaticResource footballersViewSource}&quot;&gt;
&lt;DataGrid AutoGenerateColumns=&quot;False&quot; EnableRowVirtualization=&quot;True&quot; Height=&quot;134&quot;
HorizontalAlignment=&quot;Left&quot; ItemsSource=&quot;{Binding}&quot; Margin=&quot;12,21,0,0&quot; Name=&quot;footballersDataGrid&quot;
RowDetailsVisibilityMode=&quot;VisibleWhenSelected&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;222&quot;&gt;
&lt;DataGrid.Columns&gt;
&lt;DataGridTextColumn x:Name=&quot;idColumn&quot; Binding=&quot;{Binding Path=id}&quot; Header=&quot;id&quot; IsReadOnly=&quot;True&quot; Width=&quot;SizeToHeader&quot; /&gt;
&lt;DataGridTextColumn x:Name=&quot;firstnameColumn&quot; Binding=&quot;{Binding Path=firstname}&quot; Header=&quot;firstname&quot; Width=&quot;SizeToHeader&quot; /&gt;
&lt;DataGridTextColumn x:Name=&quot;lastnameColumn&quot; Binding=&quot;{Binding Path=lastname}&quot; Header=&quot;lastname&quot; Width=&quot;SizeToHeader&quot; /&gt;
&lt;DataGridCheckBoxColumn x:Name=&quot;isActiveColumn&quot; Binding=&quot;{Binding Path=isActive}&quot; Header=&quot;is Active&quot; Width=&quot;SizeToHeader&quot; /&gt;
&lt;/DataGrid.Columns&gt;
&lt;/DataGrid&gt;
&lt;/Grid&gt;
</pre></p>
<p>18) Run your application and click on the &#8220;Footballers window&#8221; button to see the new window populated with data from the dataset.</p>
<p>19) Now we need to add some functionality to the fourth button &#8220;Footballers form&#8221;. Add another form (Windows Form) to your application.Name it <em>FootballersForm.cs</em></p>
<p>Bring the form on the designer.From the <em>Data Sources</em> window, click <em>Details</em> from the drop-down and then drag and drop it on the <em>FootballersForm</em> window.Have a look at the code in the <em>FootballersForm.cs</em> file. Now we need to add some code to launch this Windows Form window from the MainWindow.xaml file.</p>
<p>This is the code for the <em>footballersFormButton_Click</em> event handling routine.</p>
<p><pre class="brush: csharp;">
private void footballersFormButton_Click(object sender, RoutedEventArgs e)
{
var FootballersForm = new FootballersForm();

FootballersForm.Show();
}
</pre></p>
<p>20) Run your application and click on all buttons to see all the windows popping up. You can see how we can incorporate Window Forms in a WPF project.</p>
<p>21) At this point I would like to mention something that every developer who will try &#8220;Interop&#8221; should know. Launch Spy++ and move it over a Windows form window. You will see so many handles available for almost any control on the form. You can check that yourself by launching <strong>Spy++</strong> and trying to find the handle for the various controls of the Windows Forms windows. You will see that you will get only one handle for the WPF windows.</p>
<p>Have a look at the pictures below to see what I mean.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/handle.jpg"><img class="aligncenter size-large wp-image-1672" title="handle" src="http://dotnetstories.files.wordpress.com/2012/01/handle.jpg?w=1024&#038;h=538" alt="" width="1024" height="538" /></a></p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/handle2.jpg"><img class="aligncenter size-large wp-image-1673" title="handle2" src="http://dotnetstories.files.wordpress.com/2012/01/handle2.jpg?w=1024&#038;h=572" alt="" width="1024" height="572" /></a></p>
<p><a href="http://dotnetstories.files.wordpress.com/2012/01/handle3.jpg"><img class="aligncenter size-large wp-image-1675" title="handle3" src="http://dotnetstories.files.wordpress.com/2012/01/handle3.jpg?w=1024&#038;h=574" alt="" width="1024" height="574" /></a></p>
<p>22) Another thing worth pointing out is how keyboard input is handled in a Windows form window that is part of a WPF application. Launch your application again. Click on the &#8220;Footballers form&#8221; window and in the window that pops up, try to use the <strong>tab</strong> key to move between the fields of the record. You will notice that you cannot do that.That is because the <strong>WPF</strong> application (host application) receives the keyboard input messages but does not know how to pass that keyboard input message to the Windows Form window. Let&#8217;s fix that. First we need to add a reference to the <strong>WindowsFormIntegration</strong> assembly.Now we will add some code to the App.xaml and App.xaml.cs files.</p>
<p>In the <strong>App.xaml</strong> file we add the Startup application event.Have a look at the code below.</p>
<p><pre class="brush: xml;">
&lt;Application x:Class=&quot;WindowsFormToWPF.App&quot;
xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
StartupUri=&quot;MainWindow.xaml&quot; Startup=&quot;Application_Startup&quot;  &gt;
</pre></p>
<p>We add the event handling routine for the event in the <strong>App.xaml.cs</strong></p>
<p><pre class="brush: csharp;">
private void Application_Startup(object sender, StartupEventArgs e)
{
WindowsFormsHost.EnableWindowsFormsInterop();
           //not necessary when running on windows vista or 7. But needed when you run on windows XP
System.Windows.Forms.Application.EnableVisualStyles();
}
}
</pre></p>
<p>As you can see I use the <strong>WindowsFormsHost</strong> class that allows us to host a <strong>Windows Forms control</strong> on a WPF application.</p>
<p>23)  Launch your application again. Click on the &#8220;Footballers form&#8221; window and in the window that pops up, try to use the <strong>tab</strong> key to move between the fields of the record. You will be successful this time.</p>
<p>24) Now we can see another example where you can add an existing WPF window to a Windows Forms application.We need to add some references and Visual studio open the WPF window in the XAML designer.We will use the <strong>ElementHost</strong> class that can be used to host a Windows Presentation Foundation (WPF) element inside a Windows Forms application.Close this project/application and create a new Windows Forms application.Now we need to add a new WPF window. We are going to use an existing one, the one we created in the previous application, <strong>Footballers.xaml</strong>. In order to add all the necessary references to the Windows  Forms application, in the Xaml designer drag and drop a label control on the Footballers.xaml.When you do that all the necessary references are added.Some of them are (Accessibility,PresentationCore, PresentationFramework).Now remove the label control.Add a button on the Windows form (main windows form-Form1.cs).In the <strong>button1_click</strong> event handling routine type</p>
<p><pre class="brush: csharp;">
private void button1_Click(object sender, EventArgs e)
{
var footballers = new Footballers();

footballers.Show();
}
</pre></p>
<p>25) Now run your application and click on the button. The WPF window will show just fine.Try to move up and down the records using the <em>up</em> and <em>down</em> arrows from the keyboard. That will not work for the same reasons I explained before. The Windows Form (main &#8211; host application) receives the input messages from the keyboard but does not know how to pass them on to the WPF window.Let&#8217;s fix that.We need to add a reference to our application. We need to add a reference to the <em>WindowsFormsIntegration</em> assembly.In the <strong>button1_click</strong> event handling routine we need to add another line of code. The complete code follows.</p>
<p><pre class="brush: csharp;">
private void button1_Click(object sender, EventArgs e)
{
var footballers = new Footballers();
            System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(footballers);
footballers.Show();
}
</pre></p>
<p>26) Now let&#8217;s run the application again. Click on the button and in the WPF window move up and down the records using the <em>up</em> and <em>down</em> arrows from the keyboard. You will be successful this time.</p>
<p>27) We can also add a Windows Forms built-in or user control to a WPF window and vice versa.I will demonstrate that with additional examples.</p>
<p>28) I will be showing your first how to add a Windows Forms control in a WPF window.In order to do that I will be using the <strong>WindowsFormsHost</strong> class in the <strong>System.Windows.Forms.Integration</strong> namespace.</p>
<p>29) Create a new WPF application and choose a suitable name for it. Choose C# as the development language. Add references to the <strong>System.Windows.Forms</strong> and <strong>WindowsFormIntegration</strong> assemblies.I will be adding in XAML the assembly reference for Window Forms and <strong>mscorlib</strong> assemblies.</p>
<pre> xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:sys="clr-namespace:System;assembly=mscorlib"</pre>
<p>30) Now in the XAML I will be adding a <strong>MaskedTextBox</strong> control that does not exist in the WPF ecosystem.This is the code in the <strong>MainWindow.xaml</strong></p>
<p><pre class="brush: xml;">
&lt;WindowsFormsHost&gt;

   &lt;wf:MaskedTextBox x:Name=&quot;maskedTextBox&quot; Mask=&quot;(999)-0000000&quot; ValidatingType=&quot;{x:Type sys:Int32}&quot; &gt;&lt;/wf:MaskedTextBox&gt;

  &lt;/WindowsFormsHost&gt;
</pre></p>
<p>Run your application and you will see the masked textbox appearing with no problems at all.</p>
<p>31) Finally I am going to provide an example on how to use WPF controls in WinForms Apps.Obviously we need to add references to the needed assemblies.We are going to use the <strong>ElementHost</strong> control. Add a new folder in your application, a WPF user control.Name it <em>FrameWorkControl.xaml</em>.</p>
<p>32) Αdd a reference to the <strong>System.Xaml</strong> assembly.</p>
<p>33) The code for the <em>FrameWorkControl.xaml</em> follows. I am basically having a ListBox control with some TextBlock elements inside a stackpanel.</p>
<p><pre class="brush: xml;">
    &lt;Grid&gt;   &lt;ListBox Margin=&quot;5&quot; Grid.Row=&quot;1&quot; Grid.Column=&quot;0&quot;
Name=&quot;DotNetListBox&quot;
SelectionChanged=&quot;DotNetListBox_SelectionChanged&quot;&gt;
&lt;StackPanel Margin=&quot;0,0,0,5&quot; Orientation=&quot;Horizontal&quot;&gt;
&lt;Label Content=&quot;ASP.Net&quot; Padding=&quot;10&quot; Margin=&quot;10&quot; FontFamily=&quot;Batang&quot; FontSize=&quot;16&quot;&gt;&lt;/Label&gt;
&lt;TextBlock MaxWidth=&quot;500&quot; Margin=&quot;10,0,0,0&quot; TextWrapping=&quot;Wrap&quot; Tag=&quot;ASP.Net&quot;
Text=&quot;ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is an entirely new
technology for server-side scripting&quot; Width=&quot;265&quot; Height=&quot;66&quot;&gt;&lt;/TextBlock&gt;
&lt;/StackPanel&gt;
&lt;StackPanel Margin=&quot;0,0,0,5&quot; Orientation=&quot;Horizontal&quot;&gt;
&lt;Label Content=&quot;WPF&quot; Padding=&quot;10&quot; Margin=&quot;10&quot; FontFamily=&quot;Batang&quot; FontSize=&quot;16&quot;&gt;&lt;/Label&gt;
&lt;TextBlock MaxWidth=&quot;500&quot; Margin=&quot;10,0,0,0&quot; TextWrapping=&quot;Wrap&quot; Tag=&quot;WPF&quot;
Text=&quot;Windows Presentation Foundation, WPF, provides a unified framework for building applications and
high-fidelity experiences in Windows that blend application UI, documents, and media content&quot; Width=&quot;300&quot; Height=&quot;94&quot;&gt;&lt;/TextBlock&gt;
&lt;/StackPanel&gt;
&lt;/ListBox&gt;
&lt;/Grid&gt;

</pre></p>
<p>34) For the <em>DotNetListBox_SelectionChanged </em>event handling routine type.</p>
<p><pre class="brush: csharp;">
public string SelectedTechnology { get; set; }

        private void DotNetListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        TextBlock dotnetText = ((StackPanel)DotNetListBox.SelectedValue).Children.OfType&lt;TextBlock&gt;().First();
        this.SelectedTechnology = dotnetText.Tag.ToString();
        }
    }
}
</pre></p>
<p>35) Drag and drop an <strong>ElementHost</strong> control.Click the smarttag icon and in the &#8220;Selected Hosted Content:&#8221; select the <strong>FrameWork</strong> control.Now our user control is inside (hosted) inside the Windows Forms application.Resize appropriately.</p>
<p>36) Now add a button in the main form. In the click event handling routine type</p>
<p><pre class="brush: csharp;">
private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(string.Format( &quot;You selected {0}&quot;,((FrameWorkControl)elementHost1.Child).SelectedTechnology));
        }
</pre></p>
<p>Run your application. Select you favourite technology and click the button. Your favourite technology will pop up.</p>
<p>I understand that this is a very long post but hopefully you will find it very interesting.</p>
<p>Leave a comment with your email if you need the source code.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/wpf/'>WPF</a>, <a href='https://dotnetstories.wordpress.com/category/xaml/'>XAML</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/interoperabilitywindows-forms/'>Interoperability;Windows Forms;</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1658/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1658&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2012/01/09/windows-forms-and-wpf-interoperability/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/handle.jpg?w=1024" medium="image">
			<media:title type="html">handle</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/handle2.jpg?w=1024" medium="image">
			<media:title type="html">handle2</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2012/01/handle3.jpg?w=1024" medium="image">
			<media:title type="html">handle3</media:title>
		</media:content>
	</item>
		<item>
		<title>Using WCF Services in Silverlight 4.0 applications</title>
		<link>https://dotnetstories.wordpress.com/2011/11/21/using-wcf-services-in-silverlight-4-0-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/21/using-wcf-services-in-silverlight-4-0-applications/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 22:25:06 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight 4]]></category>
		<category><![CDATA[Silverlight-enabled WCF Service]]></category>
		<category><![CDATA[WCF Service]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1636</guid>
		<description><![CDATA[In this post I would like to present in detail how we can consume WCF services from a Silverlight 4 application.I strongly suggest that you have a look in this post of mine where I talk about using web services .asmx in our silverlight applications.I do advise against using .asmx web services.WCF is strongly recommended by Microsoft and is the distributed technology that MS supports and will continue to support.In many cases you will see a difference in performance.WCF is significantly faster.Have a look in this very useful article in MSDN where it compares performance of WCF distributed systems with other existing distributed technologies. <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1636&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to present in detail how we can consume WCF services from a Silverlight 4 application.I strongly suggest that you have a look in this <a href="http://dotnetstories.wordpress.com/2011/11/20/using-asp-net-web-services-in-silverlight-4-applications/" target="_blank">post </a>of mine where I talk about using <strong>web services &#8211; .asmx services</strong> and how we consme them in our Silverlight applications.I do advise against using <strong>.asmx</strong> web services in Silverlight application.WCF is strongly recommended by Microsoft and is the distributed technology that MS supports and will continue to support and enhance.In many cases you will see a difference in performance.WCF is significantly faster.Have a look in this very useful <a href="http://msdn.microsoft.com/en-us/library/bb310550.aspx" target="_blank">article</a> in MSDN where it compares performance of WCF distributed systems with other existing distributed technologies.</p>
<p>All the tools you need to get you started with Silverlight ( and to follow this example) can be found <a href="http://www.silverlight.net/getting-started" target="_blank">here</a>. Make sure you download and install everything. You will need Visual Studio 2010 or Visual Web Developer Express edition with Microsoft Silverlight 4 Tools for Visual Studio 2010.</p>
<p>I have <strong>Visual Studio 2010 Ultimate</strong> edition installed in my machine and that is I am going to use.</p>
<p>1) Launch Visual Studio and create a new project a <strong>Silverlight</strong> application.Give it an appropriate name.I have named it<strong> SilverlightWCFService</strong>. Make sure you click the option where you host the Silverlight application in a new web site.The Silverlight version should be <strong>4</strong>.I will use <strong>C#</strong> as the development language.</p>
<p>2) I am not going to look into <strong>WCF</strong> in detail. I can only say a few things. Microsoft with .Net 3.0 Framework, introduced WCF. WCF is Microsoft&#8217;s choice to design/build Service Oriented Architecture applications. In this example the silverlght client will use a WCF data service to work with the data.Add a new item to your Web hosting project.Select the project and right click on it. Choose <strong>Add new item</strong> and from the available templates choose <strong>Silverlight-enabled WCF Service</strong>.I have named it <strong>ProductsByCategory.svc</strong>.Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/silverlight-enabled-wcf-service1.jpg"><img class="aligncenter size-large wp-image-1642" title="silverlight-enabled-wcf-service" src="http://dotnetstories.files.wordpress.com/2011/11/silverlight-enabled-wcf-service1.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>This will build us a service that is correctly configured for Silverlight.Do not choose the <strong>WCF Service</strong> template.As I have said earlier, Microsoft suggests that WCF is the best way of writing services when a Silvelight application is involved.So Microsoft has provided us with a template that is specifically configured for Silverlight.Typically built-in WCF Services do not work out of the box for Silverlight.You cannot have any kind of bindings with Silverlight.You cannot have any type of <strong>ws*</strong>.Binding should be set to <strong>BasicHttpBinding</strong>.</p>
<p>3) Obviously we need to add a data source, a database. I will use the <strong>Northwind</strong> database.If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a>. I assume that you have access to a version of <strong>SQL Server</strong>.If you do not, you can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>.</p>
<p>4)  I assume that you probably have some experience on working with <strong>Entity Framework</strong>.With EF we can create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.<strong>EF</strong> addresses the problem of <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch" target="_blank">Object-relational impedance mismatch</a>. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.</p>
<p>We will need to add an <strong>ADO.Net Entity Data mode</strong>l to our project.</p>
<p>In order to see how I am going to accomplish that, have a look in this <a href="http://weblogs.asp.net/dotnetstories/archive/2011/02/19/building-a-simple-asp-net-application-using-the-entity-data-model.aspx" target="_blank">post </a>(this is my other blog).You can follow steps 5-9.Ι am going to adopt the <strong>database first</strong> approach.The only difference is that you should pick <strong>Northwind</strong> database instead of <strong>AdventureWorksLT</strong>.In the model we only need the <strong>Categories,Suppliers,Products</strong> tables.So pick only those tables and close the <strong>Entity Data Model</strong> wizard.My final model in the <strong>Entity Designer</strong> looks something like this</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/entity-designer.jpg"><img class="aligncenter size-large wp-image-1638" title="entity designer" src="http://dotnetstories.files.wordpress.com/2011/11/entity-designer.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>5) Now we are ready to write a method in our service class that gets the <strong>Products By Category</strong>.Have a look at the <strong>ProductsByCategory.svc.cs file</strong>.The Silverlight code will call the WCF service to request the data from the database.This is the code I wrote for the WCF Service.You have to mark the method you wrote with &#8220;[OperationContract] &#8221; .</p>
<p><pre class="brush: csharp;">
public class ProductsByCategory
{
[OperationContract]
public List&lt;Product&gt; GetProductsByCategory(string categoryname)
{
var ctx = new NorthwindEntities();

var query = from product in ctx.Products
where product.Category.CategoryName == categoryname
select product;
return query.ToList();

}

// Add more operations here and mark them with [OperationContract]
}
</pre></p>
<p>6) Now that we have our WCF service ready we can add a <strong>Service Reference</strong> from the Silverlight application.Select the Silverlight project and right click on it. Choose <strong>Add Service Reference</strong>.Click <strong>Discover</strong> to find available services. You will find the available service and then select it.You will see all the methods available in it.I choose to have a new namespace “MyServices”.Finally click <strong>OK</strong>.Have a look at the picture below. It will also show you the steps Ι followed.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/servicereference.jpg"><img class="aligncenter size-large wp-image-1643" title="servicereference" src="http://dotnetstories.files.wordpress.com/2011/11/servicereference.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>This whole process generates the necessary proxy and data contract classes that are necessary to talk to the web service.Our Silverlight application knows all about the WCF service up to this point.I would urge you to have a look in the <strong>Reference.cs</strong> file in the Silvelight project. You can find this file if you choose &#8220;Show All files&#8221; from the<strong> Solution Explorer</strong>. Have a look at the picture below to see where it is located.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/reference.jpg"><img class="aligncenter size-large wp-image-1645" title="reference" src="http://dotnetstories.files.wordpress.com/2011/11/reference.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>7) Now we have to design our user interface and also write the necessary code for the <strong>data binding</strong>. We have to open the<strong> MainPage.xaml</strong> file and type the following.</p>
<p><pre class="brush: xml;">
&lt;Grid Background=&quot;Cyan&quot;&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;1*&quot; /&gt;
&lt;ColumnDefinition Width=&quot;3*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;ListBox x:Name=&quot;ProductList&quot;
Margin=&quot;12 12 12 12 &quot;
DisplayMemberPath=&quot;ProductName&quot; /&gt;
&lt;Border BorderBrush=&quot;#D92B2B&quot;
Background=&quot;Gray&quot;
BorderThickness=&quot;3&quot;
Padding=&quot;10&quot;
Margin=&quot;10 10&quot;
Grid.Column=&quot;1&quot;&gt;

&lt;StackPanel DataContext=&quot;{Binding SelectedItem, ElementName=ProductList}&quot; Background=&quot;#FF47CE52&quot;&gt;
&lt;TextBlock&gt;Product Name&lt;/TextBlock&gt;
&lt;TextBox Text=&quot;{Binding ProductName, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}&quot; /&gt;
&lt;TextBlock&gt;Unit Price&lt;/TextBlock&gt;
&lt;TextBox Text=&quot;{Binding UnitPrice, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}&quot; /&gt;
&lt;TextBlock&gt;Discontinued&lt;/TextBlock&gt;
&lt;TextBox Text=&quot;{Binding Discontinued, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}&quot; /&gt;

&lt;/StackPanel&gt;
&lt;/Border&gt;
&lt;/Grid&gt;
</pre></p>
<p>I have a <strong>ListBox</strong> control and displays the names of the <strong>Product</strong>s.In a seperate <strong>StackPane</strong>l element I have <strong>3 textblock</strong> and <strong>3 textbox</strong> elements.Inside the textbox elements I am going to bind data fetched from the WCF service.More specifically I am interested in the <strong>ProductName,UnitPrice,Discontinued</strong> properties/fields. I am not going to go into details as far as data binding is concerned. We have the <strong>FrameworkElement</strong> (StackPanel) that we want to link it to the datasource.The <strong>DataContext</strong> property sets the data context for that element.If you want to learn more  about the issue click <a href="http://www.silverlight.net/learn/data-networking/binding/silverlight-data-binding">here</a> .</p>
<p>8) Now we need to write the code in the <strong>MainPage.xaml.cs</strong> file.We have to populate the <strong>ProductList</strong> element with data.We are going to write some code in the <strong>MainPage_Loaded</strong> event handling routine.</p>
<p><pre class="brush: csharp;">
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();

Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{

var clnt = new ProductsByCategoryClient();

clnt.GetProductsByCategoryCompleted += (t, r) =&gt;
{

if (!r.Cancelled &amp;&amp; r.Error == null)
{

ProductList.ItemsSource = r.Result;

}

else
{
MessageBox.Show(&quot;There is no data&quot;);
}
};

clnt.GetProductsByCategoryAsync(&quot;Refreshments&quot;);

}

}
</pre></p>
<p>We must instantiate an instance of the client before we can use the service ( <strong>var clnt = new ProductsByCategoryClient();</strong> ).</p>
<p>We have two members for the <strong>GetProductsByCategory</strong> operation. We have the asynchronous method and the completed event.I am handling the completed event first. I am going to use a lambda expression. First I check that the operation has not been cancelled.Then I bind the results to the <strong>ProductList</strong> element.</p>
<p>Finally I hard code the category, I execute the call  in which the products I am interested to bring into the silverlight client  belong (<strong> clnt.GetProductsByCategoryAsync(“Refreshments”);</strong>  ).</p>
<p>Build and Run your application and see all the products appearing in the silverlight client fetched from the WCF service.</p>
<p>That is all folks. Stay tuned because I am going to post more examples on Silverlight 4.</p>
<p>Email me if you need the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/silverlight/'>Silverlight</a>, <a href='https://dotnetstories.wordpress.com/category/silverlight-4/'>Silverlight 4</a>, <a href='https://dotnetstories.wordpress.com/category/silverlight-enabled-wcf-service/'>Silverlight-enabled WCF Service</a>, <a href='https://dotnetstories.wordpress.com/category/wcf-service/'>WCF Service</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/silverlight-enabled-wcf-service/'>Silverlight-enabled WCF Service</a>, <a href='https://dotnetstories.wordpress.com/tag/wcf-service/'>WCF Service</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1636/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1636&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/21/using-wcf-services-in-silverlight-4-0-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/silverlight-enabled-wcf-service1.jpg?w=1024" medium="image">
			<media:title type="html">silverlight-enabled-wcf-service</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/entity-designer.jpg?w=1024" medium="image">
			<media:title type="html">entity designer</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/servicereference.jpg?w=1024" medium="image">
			<media:title type="html">servicereference</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/reference.jpg?w=1024" medium="image">
			<media:title type="html">reference</media:title>
		</media:content>
	</item>
		<item>
		<title>Using ASP.Net web services in Silverlight 4 applications</title>
		<link>https://dotnetstories.wordpress.com/2011/11/20/using-asp-net-web-services-in-silverlight-4-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/20/using-asp-net-web-services-in-silverlight-4-applications/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 16:47:01 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight 4]]></category>
		<category><![CDATA[Silverlight 4.0]]></category>
		<category><![CDATA[web services]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1623</guid>
		<description><![CDATA[In this post I would like to present in detail how we can consume .asmx web services from a Silverlight 4 application. Silverlight supports and "recognises" web services in a similar way that ASP.Net applications can "talk" to web services.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1623&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to present in detail how we can consume .asmx web services from a Silverlight 4 application. Silverlight supports and &#8220;recognises&#8221; web services in a similar way that ASP.Net applications can &#8220;talk&#8221; to web services. One might say that .asmx web services are considered by Microsoft legacy software. I will not disagree with that. Sometimes we do not have the luxury (time or budget) to create the services from scratch. It is very difficult to convince your boss or client to create a WCF service that does something when the functionality already exists in a web service (.asmx). So if now, I have the chance to write a whole Silverlight application from scratch I would not use .<strong>asmx</strong> web services, I would use WCF. But as I said before we have to use and maintain legacy code.</p>
<p>All the tools you need to get you started with Silverlight ( and to follow this example) can be found <a href="http://www.silverlight.net/getting-started" target="_blank">here</a>. Make sure you download and install everything. You will need Visual Studio 2010 or Visual Web Developer Express edition with Microsoft Silverlight 4 Tools for Visual Studio 2010.</p>
<p>I have <strong>Visual Studio 2010 Ultimate</strong> edition installed in my machine and that is I am going to use.</p>
<p>1) Launch Visual Studio and create a new project a <strong>Silverlight</strong> application.Give it an appropriate name.I have named it <strong>SilverlightWebService</strong>. Make sure you click the option where you host the Silverlight application in a new web site.The Silverlight version should be 4.I will use C# as the development language.</p>
<p>2) Add a new web service to the asp.net hosting project <strong>(SilverlightWebService</strong>.<strong>Web)</strong>. I have named it <strong>CategoryProducts.asmx. </strong>If you notice in the <strong>.asmx.cs  </strong>file that inherits from the <strong>WebService</strong> class there are web methods that can be executed over the web.<strong><br />
</strong></p>
<p>3) Obviously we need to add a data source, a database. I will use the <strong>Northwind</strong> database.If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>4) We will need an <strong>ADO.Net Entity Data mode</strong>l to our project. In order to see how I am going to accomplish that, have a look in this <a href="http://weblogs.asp.net/dotnetstories/archive/2011/02/19/building-a-simple-asp-net-application-using-the-entity-data-model.aspx" target="_blank">post </a>(this is my other blog).You can follow steps 5-9. The only difference is that you should pick <strong>Northwind</strong> database instead of <strong>AdventureWorksLT</strong>.In the model we only need the <strong>Categories,Suppliers,Products</strong> tables.My model in the <strong>Entity Designer</strong> looks something like this</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/entity-designer1.jpg"><img class="aligncenter size-large wp-image-1639" title="entity designer1" src="http://dotnetstories.files.wordpress.com/2011/11/entity-designer1.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>5) So let&#8217;s write a method in our service class that gets the <strong>Products By Category</strong>.</p>
<p><pre class="brush: csharp;">
[WebMethod]
public List&lt;Product&gt; GetProductsByCategory(string categoryname)
{
var ctx = new NorthwindEntities();

var query = from product in ctx.Products
where product.Category.CategoryName == categoryname
select product;
return query.ToList();

}
</pre></p>
<p>This is a very easy to follow code.I am creating a method that returns a List of Product entities that takes as an input parameter the category that the product belongs.I am just building a simple Linq to Entities query.</p>
<p>Make sure you test the web service and that it functions correctly.</p>
<p>6) Now we need to add a reference from our silverlight application to the web service.Select the Silverlight project and right click on it. Choose <strong>Add Service Reference</strong>.Click Discover to find available services. You will find the available service and then select it.You will see all the methods available in it.I choose to have a new namespace &#8220;MyServices&#8221;.Finally click <strong>OK</strong>. This whole process generates the necessary proxy classes that are necessary to talk to the web service.</p>
<p>In my case it looks like the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/service.jpg"><img class="aligncenter size-large wp-image-1627" title="service" src="http://dotnetstories.files.wordpress.com/2011/11/service.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Have a look at the files being generated.You can have a look at the <strong>Reference.cs</strong> file.You should see that some classes are generated and the interfaces they support.</p>
<p>7) Now we have to design our user interface. We have to open the<strong> MainPage.xaml</strong> file and type the following.</p>
<p><pre class="brush: xml;">
&lt;Grid
Background=&quot;Cyan&quot;&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;1*&quot; /&gt;
&lt;ColumnDefinition Width=&quot;3*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;ListBox x:Name=&quot;ProductList&quot;
Margin=&quot;12 12 12 12 &quot;
DisplayMemberPath=&quot;ProductName&quot; /&gt;
&lt;Border BorderBrush=&quot;#D92B2B&quot;
Background=&quot;Gray&quot;
BorderThickness=&quot;3&quot;
Padding=&quot;10&quot;
Margin=&quot;10 10&quot;
Grid.Column=&quot;1&quot;&gt;

&lt;StackPanel DataContext=&quot;{Binding SelectedItem, ElementName=ProductList}&quot; Background=&quot;#FF47CE52&quot;&gt;
&lt;TextBlock&gt;Product Name&lt;/TextBlock&gt;
&lt;TextBox Text=&quot;{Binding ProductName, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}&quot; /&gt;
&lt;TextBlock&gt;Unit Price&lt;/TextBlock&gt;
&lt;TextBox Text=&quot;{Binding UnitPrice, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}&quot; /&gt;
&lt;TextBlock&gt;Discontinued&lt;/TextBlock&gt;
&lt;TextBox Text=&quot;{Binding Discontinued, Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}&quot; /&gt;

&lt;/StackPanel&gt;
&lt;/Border&gt;
&lt;/Grid&gt;
</pre></p>
<p>I have a <strong>ListBox</strong> control and displays the names of the Products.In a seperate <strong>StackPane</strong>l element I have <strong>3 textblock</strong> and 3 <strong>textbox</strong> elements.Inside the textbox elements I am going to bind data.More specifically I am interested in the ProductName,UnitPrice,Discontinued properties/fields.</p>
<p>I am not going to go into details as far as Data binding is concerned. We have the <strong>FrameworkElement (StackPanel)</strong> that we want to link it to the datasource.The <strong>DataContext</strong> property sets the data context for that element.</p>
<p>If you want to learn more  about the issue click <a href="http://www.silverlight.net/learn/data-networking/binding/silverlight-data-binding">here</a> .</p>
<p>8) Now we need to write the code in the <strong>MainPage.xaml.cs</strong> file.We have to populate the <strong>ProductList</strong> element with data.We are going to write some code in the <strong>MainPage_Loaded</strong> event handling routine.</p>
<p><pre class="brush: csharp;">

public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();

Loaded +=new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender , RoutedEventArgs e)
{

var clnt = new GategoryProductsSoapClient();

clnt.GetProductsByCategoryCompleted += (t, r) =&gt;
{

if (!r.Cancelled &amp;&amp; r.Error == null)
{

var result = r.Result;
ProductList.ItemsSource = result;

}

else
{
MessageBox.Show(&quot;There is no data&quot;);
}
};

clnt.GetProductsByCategoryAsync(&quot;Refreshments&quot;);

}

}
</pre></p>
<p>We instaniate the web service proxy before we can use the service (<strong> var clnt = new GategoryProductsSoapClient();</strong> ).</p>
<p>The web service calls in Silverlight are asynchronous.We have two members for the <strong>GetProductsByCategory</strong> operation. We have the asynchronous method and the completed event.I am handling the completed event first. I am going to use a lambda expression. First I check that the operation has not been cancelled.Then I bind the results to the <strong>ProductList</strong> element.</p>
<p>Finally I hard code the category,  I execute the call  in which the products I am interested to bring into the silverlight client  belong ( <strong>clnt.GetProductsByCategoryAsync(&#8220;Refreshments&#8221;);</strong> ).</p>
<p>Build and Run your application and see all the products appearing in the silverlight client from the web service.</p>
<p>That is all folks. Stay tuned because I am going to post more examples on Silverlight 4.</p>
<p>Email me if you need the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/silverlight/'>Silverlight</a>, <a href='https://dotnetstories.wordpress.com/category/silverlight-4/'>Silverlight 4</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/silverlight/'>Silverlight</a>, <a href='https://dotnetstories.wordpress.com/tag/silverlight-4-0/'>Silverlight 4.0</a>, <a href='https://dotnetstories.wordpress.com/tag/web-services/'>web services</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1623/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1623/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1623/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1623/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1623/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1623/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1623/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1623/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1623&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/20/using-asp-net-web-services-in-silverlight-4-applications/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/entity-designer1.jpg?w=1024" medium="image">
			<media:title type="html">entity designer1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/service.jpg?w=1024" medium="image">
			<media:title type="html">service</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Common Table Expressions in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/11/19/using-common-table-expressions-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/19/using-common-table-expressions-in-sql-server/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 23:38:32 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[anchor member]]></category>
		<category><![CDATA[common table expressions]]></category>
		<category><![CDATA[CTE]]></category>
		<category><![CDATA[recursive CTEs]]></category>
		<category><![CDATA[recursive member]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1612</guid>
		<description><![CDATA[In this post I would like to talk about Common Table Expressions or CTE .  I know there are samples of how to use CTE in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.CTEs were introduced in SQL Server 2005. You can think of them as temporary views.They last only for the duration of the execution of the query<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1612&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about <strong>Common Table Expressions or CTE</strong> .  I know there are samples of how to use <strong>CTE </strong>in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.<strong>CTEs</strong> were introduced in SQL Server 2005. You can think of them as temporary views.They last only for the duration of the execution of the query.You can think of <strong>CTEs</strong> as an alternative to using subqueries,derived tables and temporary tables.They are similar to derived tables but you can reference them multiple times in the same query.So a <strong>CTE</strong> is really a named expression and their structure is defined by the query that follows the first <strong>CTE</strong> statement.We can reference them in SELECT,INSERT,UPDATE,DELETE statements.One other advantage is that with <strong>CTEs</strong> you can simplify our queries to make them more readable and maintainable.</p>
<p>We will need an instance of SQL Server running in our machine.You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>.I will use SQL Server 2008 R2 Express edition.</p>
<p>Let&#8217;s have a look at some <strong>CTEs</strong> examples.As we go through these examples you will get familiar with <strong>CTEs</strong> syntax.The syntax of a <strong>CTE</strong> is not very difficult to understand</p>
<p>We have the <strong>WITH</strong> keyword and then the <strong>CTE</strong> name follows.Then we have the column list which is optional.The query appears inside the parentheses after the <strong>AS</strong> keyword.</p>
<p>I will use the<em>AdventureWorksLt</em> which you can download from this <a href="http://www.codeplex.com/MSFTDBProdSamples/Wiki/View.aspx?title=AWLTDocs" target="_blank">site</a> .</p>
<p>1) Launch SSMS and connect to the instance of SQL Server you have available.In an new query window type the following T-SQL statements.</p>
<p><pre class="brush: sql;">

WITH ListPriceOver500ForProductsPerCategory (ProductNumber, Name, ListPrice) AS
(
SELECT
p.ProductNumber AS productNumber,
c.Name AS categoryName,
p.ListPrice
FROM SalesLT.ProductCategory c
INNER JOIN SalesLT.Product p ON
c.ProductCategoryID = p.ProductCategoryID
WHERE p.ListPrice &gt; 500.0
)

SELECT name AS categoryName, MAX(ListPrice)
FROM ListPriceOver500ForProductsPerCategory
GROUP BY Name

</pre></p>
<p>Execute the code above and see the results. In this example I create a <strong>CTE</strong> where I get the productnumber,category name and list price for all the products where the listprice is over 500. Then I can refer to this <strong>CTE</strong> in another SELECT query and find the maximum listprice per category where obviously I get back the category names and prices of the products where the list price is greater than 500, since that was defined in the <strong>CTE</strong>.</p>
<p>2) Now let&#8217;s take a look at recursive <strong>CTEs</strong>.That means that <strong>CTEs</strong> can reference themselves to produce the desired results.There are two parts in recursive <strong>CTEs</strong>. We have the <strong>base part</strong> where it is described what to do when computing the result no longer requires another recursive call.The second part is known as the <strong>recursive step</strong>.In this step it is required to invoke the recursive call again in order to reach the base part/stage.To put it simply the <strong>CTE</strong> is built and then the results from that <strong>CTE</strong> are called recursively in a UNION statement that returns subsets of data until all the data is returned. By that we have the chance to create data in a hierarchical fashion.</p>
<p>In a recursive <strong>CTE</strong> is consisted from a minimum of two queries. The nonrecursive query is called anchor member. The recursive member is the recursive query.  Those two queries are separated by a UNION ALL statement. Anchor members are invoked only once. Recursive members are invoked repeatedly until the query returns no rows.</p>
<p>In an new query window type the following T-SQL statements.</p>
<p><pre class="brush: sql;">
USE tempdb
GO

CREATE TABLE FootballInfo(FootballRelatedPosition_Name nvarchar(50),Football_ID INT PRIMARY KEY,
ReportsToManager INT)

INSERT INTO FootballInfo VALUES('FA',1,  NULL)
INSERT INTO FootballInfo VALUES('Kenny Dalglish',2,  1)
INSERT INTO FootballInfo VALUES('Steven Gerrard',3,  2)
INSERT INTO FootballInfo VALUES('Harry Redknapp',4,  1)
INSERT INTO FootballInfo VALUES('Gareth Bayle',5,  4)
INSERT INTO FootballInfo VALUES('Alex Ferguson',6,  1)
INSERT INTO FootballInfo VALUES('Dirk Kuyt',7,  2)
INSERT INTO FootballInfo VALUES('Aaron Lennon',8,  4)
INSERT INTO FootballInfo VALUES('Pepe Reina',9,  2)
INSERT INTO FootballInfo VALUES('Luka Modrić',10,  4)
INSERT INTO FootballInfo VALUES('Rio Ferdinand',11,  6)
INSERT INTO FootballInfo VALUES('Wayne Rooney',12,  6)

WITH FindwhoReportsToWhom(FootballRelatedPosition_Name,Football_ID,  ReportsToManager)
AS
(SELECT FootballRelatedPosition_Name, Football_ID, ReportsToManager
FROM FootballInfo WHERE Football_ID = 1
UNION ALL
SELECT f.FootballRelatedPosition_Name, f.Football_ID, f.ReportsToManager
FROM FootballInfo f  INNER JOIN
FindwhoReportsToWhom fwr ON fwr.Football_ID = f.ReportsToManager
)

SELECT fwrs.FootballRelatedPosition_Name AS Footballer, fr.FootballRelatedPosition_Name AS 'Manager or FA'
FROM FindwhoReportsToWhom fwrs INNER JOIN FootballInfo fr
ON fwrs.ReportsToManager = fr.Football_ID

</pre></p>
<p>In the first T-SQL statements we create a table with football related data.Each football person/authority has an <strong>ID</strong>, <strong>a name</strong> and another field(<strong>ReportsToManager</strong>) that self-references back to the ID field<strong></strong>.Then I insert some values into the table. We want to write a query that returns all the football people and who they report to.In this example I will look for <strong>Football_ID=1</strong>.I write the<strong> CTE</strong> and the recursion starts at <strong>Football_ID=1</strong> which is the anchor member.It picks up every record that reports to <strong>Football_ID=1</strong> using the recursive member(SELECT statement after UNION ALL).Then we have subsequent recursions that gives us back all the football people and who they report to.The recursion stops when there are no results to show anymore. Be careful on how you design your<strong> CTE</strong>, so there is not an infinite loop.</p>
<p>Execute the code and see the results for yourself.</p>
<p>If you have followed everything correctly you should see something similar to the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/cte1.jpg"><img class="aligncenter size-large wp-image-1619" title="cte1" src="http://dotnetstories.files.wordpress.com/2011/11/cte1.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/anchor-member/'>anchor member</a>, <a href='https://dotnetstories.wordpress.com/tag/common-table-expressions/'>common table expressions</a>, <a href='https://dotnetstories.wordpress.com/tag/cte/'>CTE</a>, <a href='https://dotnetstories.wordpress.com/tag/recursive-ctes/'>recursive CTEs</a>, <a href='https://dotnetstories.wordpress.com/tag/recursive-member/'>recursive member</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1612/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1612/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1612/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1612&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/19/using-common-table-expressions-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/cte1.jpg?w=1024" medium="image">
			<media:title type="html">cte1</media:title>
		</media:content>
	</item>
		<item>
		<title>Using large data types in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/11/17/using-large-data-types-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/17/using-large-data-types-in-sql-server/#comments</comments>
		<pubDate>Thu, 17 Nov 2011 13:05:34 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[large data types]]></category>
		<category><![CDATA[nvarchar(max)]]></category>
		<category><![CDATA[varbinary(max)]]></category>
		<category><![CDATA[varchar(max)]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1607</guid>
		<description><![CDATA[In this post I would like to talk about the large value data types and how we can use them to store large amounts of data. We can store up to 2^31 bytes of character, binary, and Unicode data. I know there are samples of how to use large value data types in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1607&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about the large value data types and how we can use them to store large amounts of data. We can store up to 2^31 bytes of character, binary, and Unicode data. I know there are samples of how to use <strong>large value data types </strong>in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p>So T-SQL supports large character and binary data types.These types are <strong>varchar(max)</strong>,<strong>nvarchar(max)</strong> and <strong>varbinary(max)</strong>.They have no 8000 byte limitation and <strong>text</strong>,<strong>ntext</strong> and <strong>image</strong>  data types are deprecated and you should not use it anymore. Actually there is no need to use them anymore.Bear in mind that you cannot use text,ntext,image data types as the data type of a local variable. If you attempt to do so you will receive an error from SQL Server ,&#8221;The text,ntext and image data types are invalid for local variables&#8221;.So that is another big limitation and you should avoid using these system data types.In some future version of SQL Server they will go away.</p>
<p>We will need an instance of SQL Server running in our machine.You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>.I will use SQL Server 2008 R2 Express edition.</p>
<p>1)  Launch SSMS and connect to the SQL Server instance.Start a new query window and type (copy-paste) the following</p>
<p><pre class="brush: sql;">

CREATE DATABASE LargeDataTypes

GO

USE LargeDataTypes

GO

DECLARE @myvar TEXT

SET @myvar = 'SQL Server is the best RDMBS'

SELECT @myvar

</pre></p>
<p>Execute the code above. This will not work.</p>
<p>2) In a new query window type the following</p>
<p><pre class="brush: sql;">

USE LargeDataTypes

GO

DECLARE @myvar VARCHAR(max)

SET @myvar = 'SQL Server is the best RDMBS'

SELECT @myvar

</pre></p>
<p>Execute the code above. This will work just fine.</p>
<p>3) In this example we will store a huge number of bytes in a variable of type <strong>varchar(max)</strong>. In a new query window type</p>
<p><pre class="brush: sql;">

USE LargeDataTypes

GO

DECLARE @myvar VARCHAR(max)

SET @myvar = REPLICATE(CAST('SQL Server 2012 will provide Mission Critical
Confidence with greater uptime blazing-fast performance and enhanced
security features for mission critical workloads' AS VARCHAR(max)),65000)

SELECT @myvar

SELECT LEN(@myvar)

</pre></p>
<p>In this little example I replicate the string in quotes (&#8216; &#8216;) 65000 times.Then I store it in a local variable of data type varchar(max) . Execute the code above and you will see that it works perfectly well.So we test beyond doubt that there is no 8000 bytes limitation.</p>
<p>4) In this final example I will show you how to store a large document. I have found <a href="http://msdn.microsoft.com/en-us/library/dd672789%28v=sql.100%29.aspx" target="_blank">this</a> technical document with title &#8220;Troubleshooting Performance Problems in SQL Server 2008&#8243; very useful.Download it and save it in a folder. It is 561kbytes in  size and we will store it in a variable of type <strong>varbinary(max)</strong></p>
<p>In a new query window type</p>
<p><pre class="brush: sql;">

USE LargeDataTypes

GO

DECLARE @myvar VARBINARY(max)

SET @myvar = (SELECT * FROM OPENROWSET(BULK 'C:\Users\fofo\Downloads\TShootPerfProbs2008.docx',SINGLE_BLOB) AS document)

SELECT @myvar

</pre></p>
<p>Execute the code above.This code will work just fine.The results will be the binary representation of what is inside the .docx file.</p>
<p>5) In this final example we will store the large .docx in a table.In a new query window type</p>
<p><pre class="brush: sql;">

USE LargeDataTypes

GO

CREATE TABLE largedocs(id INT PRIMARY KEY IDENTITY, mydoc VARBINARY(max))

INSERT INTO largedocs VALUES
((SELECT * FROM OPENROWSET(BULK 'C:\Users\fofo\Downloads\TShootPerfProbs2008.docx',SINGLE_BLOB) AS document))

SELECT * FROM largedocs
</pre></p>
<p>Execute the code above. The .docx will be stored in the column with data type varbinary(max)</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/large-data-types/'>large data types</a>, <a href='https://dotnetstories.wordpress.com/tag/nvarcharmax/'>nvarchar(max)</a>, <a href='https://dotnetstories.wordpress.com/tag/varbinarymax/'>varbinary(max)</a>, <a href='https://dotnetstories.wordpress.com/tag/varcharmax/'>varchar(max)</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1607/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1607/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1607/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1607/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1607/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1607/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1607/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1607/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1607&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/17/using-large-data-types-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Using HierarchyID system data type in SQL Server 2008</title>
		<link>https://dotnetstories.wordpress.com/2011/11/15/using-hierarchyid-system-data-type-in-sql-server-2008/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/15/using-hierarchyid-system-data-type-in-sql-server-2008/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 17:44:23 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[ancestor]]></category>
		<category><![CDATA[descendant]]></category>
		<category><![CDATA[hierarchies]]></category>
		<category><![CDATA[HierarchyID]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1594</guid>
		<description><![CDATA[In this post I would like to talk about the new system data type HierarchyID which was introduced in SQL Server 2008. I know there are samples of how to use HierarchyID in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.It is used for storing hierarchical data.The most common scenario is that we want to store the data (relations and positions) of an organisational chart.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1594&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about the new system data type <strong>HierarchyID</strong> which was introduced in SQL Server 2008. I know there are samples of how to <strong>use HierarchyID </strong>in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.It is used for storing hierarchical data.The most common scenario is that we want to store the data (relations and positions) of an organisational chart.Basically we want to store the relationship between employers and their managers.In order for you to better understand of what I am trying to do in this example, have a look at the picture below.It shows an organisational chart with the relationships between the various employees.This is the kind of data we can store in a database using the <strong>hierarchyID</strong> data type.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/hierarchy.jpg"><img class="aligncenter size-full wp-image-1595" title="hierarchy" src="http://dotnetstories.files.wordpress.com/2011/11/hierarchy.jpg?w=460&#038;h=274" alt="" width="460" height="274" /></a>Let me explain the relationships in the chart above. Nick is the <strong>CEO</strong>. Jane,Mary and John report to Nick and are <strong>General Managers</strong>.Kate is the <strong>Sales Manager</strong> and reports to John.George and Diane are <strong>Marketing Managers</strong> and report to Jane. Frank is the <strong>Internet and</strong> <strong>Social Media Marketing Manager</strong> and report s to George. Gregory is the <strong>Marketing and Research</strong> coordinator and reports to Diane.</p>
<p>We will need an instance of SQL Server running in our machine.You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>.I will use SQL Server 2008 R2 Express edition.</p>
<p>1) We will begin with this example. Launch SSMS and connect to the SQL Server instance.Start a new query window and type (copy-paste) the following</p>
<p><pre class="brush: sql;">

CREATE DATABASE Hierarchy
GO

USE Hierarchy
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Hierarchies]') AND type in (N'U'))
DROP TABLE [dbo].[Hierarchies]

CREATE TABLE Hierarchies
(
[HierarchyID] hierarchyid PRIMARY KEY CLUSTERED,
EmployeeID int UNIQUE NOT NULL,
EmployeeName varchar(20) NOT NULL,
Title varchar(20) NULL
) ;
GO

SELECT HierarchyID.ToString(), HierarchyID, EmployeeID, EmployeeName, Title
FROM Hierarchies

</pre></p>
<p>Execute the code above.We create a database and then we create a table. In that table one of the fields is a field of type <strong>HierarchyID</strong>.In that table we will store the data as it was explained previously in the example(chart).</p>
<p>2) Now let&#8217;s insert the data in the <strong>Hierarchies</strong> table.We will insert the CEO (Nick) first. In the same query window type the following.</p>
<p><pre class="brush: sql;">

INSERT INTO Hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (hierarchyid::GetRoot(), 1,'Nick','CEO')

SELECT [HierarchyID].ToString(), [HierarchyID], EmployeeID, EmployeeName, Title
FROM Hierarchies

</pre></p>
<p>Execute the code above. You will see that Nick was inserted as CEO in the rool level.I used the <strong>GetRoot()</strong> method to do that.</p>
<p>3) Now we need to insert a child node. We will insert the descendants of root node. In our case they are Jane,Mary,John who are the <strong>General Managers</strong> and report to Nick.</p>
<p><pre class="brush: sql;">

DECLARE @GenMgr hierarchyid
SELECT @GenMgr = [HierarchyID]FROM Hierarchies WHERE EmployeeID = 1
INSERT INTO Hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@GenMgr.GetDescendant(NULL, NULL), 2, 'Jane', 'General Manager') ;

SELECT [HierarchyID].ToString(), [HierarchyID], EmployeeID, EmployeeName, Title
FROM Hierarchies

</pre></p>
<p>Execute the code above.You will see that <strong>Jane</strong> was inserted as a child node to the Root node <strong>Nick</strong>.As you see I use the <strong>GetDescendant()</strong> method to achieve that.</p>
<p>4) Now I will add the other 2 <strong>General Managers Mary and John</strong>.In the same query window type</p>
<p><pre class="brush: sql;">

--Insert Child (Mary)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'Nick'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 3, 'Mary', 'General Manager') ;

Go

--Insert Child (John)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'Nick'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 4, 'John', 'General Manager') ;

SELECT [HierarchyID].ToString(), [HierarchyID], EmployeeID, EmployeeName, Title
FROM Hierarchies

</pre></p>
<p>Execute the code above and you will see that the child nodes (John and Mary) are inserted as immediate childs of the root node <strong>Nick</strong>. Have a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/descendants.jpg"><img class="aligncenter size-large wp-image-1601" title="descendants" src="http://dotnetstories.files.wordpress.com/2011/11/descendants.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>We use the <strong>GetDescendant()</strong> method to achieve that.It returns the child node of a given parent node.We also use the <strong>GetAncestor()</strong> method which returns the ancestor of a given child node.</p>
<p>5) Now I will use insert <strong>George</strong> and <strong>Diane</strong> as <strong>Marketing Managers</strong> that report to <strong>Jane</strong>.In the same query window type</p>
<p><pre class="brush: sql;">

--Insert Child (George)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'Jane'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 5, 'George', 'Marketing Manager') ;

GO
--Insert Child (Diane)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'Jane'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies  ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 6, 'Diane', 'Marketing Manager') ;

SELECT [HierarchyID].ToString(), [HierarchyID], EmployeeID, EmployeeName, Title
FROM Hierarchies

</pre></p>
<p>Execute the code above and you will see <strong>George and Diane</strong> inserted as descendants of the parent node <strong>Jane</strong>.</p>
<p>7) Now I will insert into the <strong>Hierarchies</strong> table <strong>Kate</strong> who is the <strong>Sales Manager</strong> who reports to John.</p>
<p>In the same query window type</p>
<p><pre class="brush: sql;">

--Insert Child (Kate)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'John'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 7, 'Kate', 'Sales Manager') ;

SELECT [HierarchyID].ToString(), [HierarchyID], EmployeeID, EmployeeName, Title
FROM Hierarchies

</pre></p>
<p>Execute the code above and <strong>Kate</strong> will be inserted as a child node to the parent node <strong>John</strong>.</p>
<p>8) Now I will insert into the <strong>Hierarchies</strong> table <strong>Frank</strong> who is <strong>Internet and</strong> <strong>Social Media Marketing Manager</strong> and reports to George.I will also add <strong>Gregory</strong> who is the <strong>Marketing and Research</strong> <strong>coordinator</strong> and reports to Diane.</p>
<p><pre class="brush: sql;">

--Insert Child (Frank)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'George'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 8, 'Frank', 'Internet and Social Media Marketing Manager') ;

GO

--Insert Child (Gregory)
DECLARE @Mgr hierarchyid
DECLARE @LastEmp hierarchyid

SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE employeename = 'Diane'
SELECT @LastEmp = Max([HierarchyID].ToString()) FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

INSERT INTO hierarchies ([HierarchyID], EmployeeID, EmployeeName, Title)
VALUES (@Mgr.GetDescendant(@LastEmp, NULL), 9, 'Gregory ', 'Marketing and Research') ;

SELECT HID.ToString(), HID, EmployeeID, EmployeeName, Title
FROM employee

</pre></p>
<p>Execute the code above and <strong>Frank</strong> will be inserted as a child node to the parent node <strong>George</strong>.Also <strong>Gregory</strong> will be inserted as a child node to the parent node <strong>Diane.</strong><br />
Now we have inserted all the data into the table. By all data I mean we have now the information regarding the employees and their relationships.</p>
<p>9) Finally I will show you how to get the <strong>direct</strong> <strong>descendants</strong> of <strong>Jane</strong> and to find the <strong>Ancenstor</strong> of <strong>Jane</strong>. In a new query window type</p>
<p><pre class="brush: sql;">

--To Find all direct descendants of Jane
DECLARE @Mgr hierarchyid
SELECT @Mgr = [HierarchyID] FROM hierarchies WHERE EmployeeName = 'Jane'
SELECT [HierarchyID].ToString(), * FROM hierarchies WHERE [HierarchyID].GetAncestor(1) = @Mgr

go

--To Find the Ancenstor of Jane
DECLARE @emp hierarchyid
SELECT @emp = [HierarchyID] FROM hierarchies WHERE EmployeeName = 'Jane'
SELECT * FROM hierarchies WHERE @emp.GetAncestor(1) = [HierarchyID]

</pre></p>
<p>Execute the code above and you will get the results.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/ancestor/'>ancestor</a>, <a href='https://dotnetstories.wordpress.com/tag/descendant/'>descendant</a>, <a href='https://dotnetstories.wordpress.com/tag/hierarchies/'>hierarchies</a>, <a href='https://dotnetstories.wordpress.com/tag/hierarchyid/'>HierarchyID</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1594/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1594&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/15/using-hierarchyid-system-data-type-in-sql-server-2008/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/hierarchy.jpg" medium="image">
			<media:title type="html">hierarchy</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/descendants.jpg?w=1024" medium="image">
			<media:title type="html">descendants</media:title>
		</media:content>
	</item>
		<item>
		<title>Looking into exceptions in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/11/12/looking-into-exceptions-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/12/looking-into-exceptions-in-sql-server/#comments</comments>
		<pubDate>Sat, 12 Nov 2011 00:30:15 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[try catch]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1579</guid>
		<description><![CDATA[In this post I would like to talk about exceptions in SQL Server. Well, let me make a general statement. All humans make mistakes.That includes application developers,database developers e.t.c.

So all developers must be familiar with the various exception mechanisms and tools that each language has. Everyone who has worked with Visual Basic has used the "ON  ERROR GOTO" statement and all .NET languages have exception handling techniques e.g Try Catch statements-blocks.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1579&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about exceptions in SQL Server. I know there are samples of how to <strong>handle exception in SQL Server </strong> in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p>Well, let me make a general statement. All humans make mistakes.That includes application developers,database developers e.t.c.</p>
<p>So all developers must be familiar with the various exception mechanisms and tools that each language has. Everyone who has worked with Visual Basic has used the &#8220;<strong>ON  ERROR GOTO</strong>&#8221; statement and all .NET languages have exception handling techniques e.g <strong>Try Catch</strong> statements-blocks.</p>
<p>Since SQL Server 2005 we have support for <strong>TRY&#8230;CATCH</strong> statements. That makes it much easier and less verbose to handle exceptions in SQL Server. .Net developers find it much easier to use <strong>Try Catch</strong> statements in SQL Server and in general it is a much readable (cleaner syntax) format to handle exceptions.</p>
<p>I am sure that most of you are familiar with <strong>Try Catch</strong> statements but before I go on with the actual examples I will explain it. Inside the <strong>TRY</strong> block all the instructions that might cause an exception are included. <strong></strong>When an exception occurs from one of the statements that are inside in the <strong>TRY</strong> block, the control is handed to the <strong>CATCH</strong> block, where the exception can be handled (by printing a message to the user, log the error e.t.c)</p>
<p>In previous versions SQL Server had various options to handle errors and exceptions. We had the <strong>@@error</strong> global variable.If the <strong>@@error</strong> value was zero we had no error.If it was not zero we should firstly find the value of the global variable and understand what kind of error it was.</p>
<p>Let&#8217;s have a look at all these exception handling techniques with some examples.We will need an instance of SQL Server running in our machine.You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>.I will use SQL Server 2008 R2 Express edition.</p>
<p>1) In this first example, I will show you what happens when we do not use exception handling mechanisms in T-SQL. Launch SSMS and connect to the instance of SQL Server you have available.</p>
<p>In a new query window type the following T-SQL statements.</p>
<p><pre class="brush: sql;">

USE TEMPDB
GO

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');

--execute this after you have finished with the example
drop table dbo.football

</pre></p>
<p>Execute the code.As you will notice, there is a primary key violation. Since there is not an exception handling mechanism SQL Server has little choice but to send me back (to the calling (client) application) the very detailed error which follows.</p>
<p>&#8220;<strong>Msg 2627, Level 14, State 1, Line 4</strong><br />
<strong>Violation of PRIMARY KEY constraint &#8216;PK__Football__123AE7B907020F21&#8242;. Cannot insert duplicate key in object &#8216;dbo.Football&#8217;. The duplicate key value is (1).</strong><br />
<strong>The statement has been terminated.</strong>&#8220;</p>
<p>As you can understand the client cannot do anything about that. He will be confused and angry. A malicious user can even get valuable information about our database,system and that is not something we want.You will still notice that the 2 of the 3 possible rows are inserted into the table despite the primary key violation</p>
<p>2) We can rewrite the previous query using TRY CATCH statements. In this example we will not do something fancy. I would like to demonstrate the exception functions and how <strong>Τry Catch</strong> works as well.Type in a new query window the following</p>
<p><pre class="brush: sql;">

USE tempdb

go

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

BEGIN TRY
INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');
END TRY
BEGIN CATCH

SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;

END CATCH
GO
--execute this after you have finished with the example
drop table dbo.football
</pre></p>
<p>Execute the code above. You will notice that now instead of 2 rows inserted in the table, there is only one inserted. This happens because after lines 18-19 fail, the execution of the code (flow) is handed to the line 24 (Catch statement) and that means that lines 21 and 22 are never executed.Inside the <strong>Catch</strong> statement I am not doing anything special. I just use the built-in exception functions to print out the error number, the error severity,the error state, the error line and the error message.Those exception functions are almost self explanatory and you can find their full explanation at BOL.</p>
<p>3)Let&#8217;s try our next example. In order to follow this example it would be great if you understand the basics of transactions. I have another post on this subject.Click <a href="http://dotnetstories.wordpress.com/2011/11/09/a-thorough-look-into-transactions-in-sql-server/" target="_blank">here</a> if you want to have a look.</p>
<p>Τype the following T-SQL statements in a new query window. In this example I have placed the <strong>Insert</strong> statements inside a transaction.</p>
<p><pre class="brush: sql;">

USE tempdb

go

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

BEGIN TRANSACTION
INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');
COMMIT TRANSACTION

SELECT * FROM DBO.FOOTBALL
--execute this after you have finished with the example
drop table dbo.football
</pre></p>
<p>When you execute the code above, you will get the same error (primary key violation) but stilll 2 rows will be inserted in the table.You will be consfused by this behaviour.We have certain kind of errors that are considered not to be <em>fatal</em>.So in this case we have the error taking place but then the code proceeds to the next statements and executes them successfully. Some people do not like this behaviour and we can most certainly influence this behaviour.In this next example I will set the <strong>XACT_ABORT</strong> property to <strong>ON</strong>. The default value is <strong>OFF</strong>. By setting this property at the connection level to <strong>ON</strong> we are adopting a new strategy which says that &#8220;if an error takes place in a transaction or an exception is thrown, the whole batch is aborted.The whole transaction is rolled back&#8221;. In a new query window type the following T-SQL statements</p>
<p><pre class="brush: sql;">

USE tempdb

go

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

SET XACT_ABORT ON

BEGIN TRANSACTION
INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');
COMMIT TRANSACTION

SELECT * FROM DBO.FOOTBALL
--execute this after you have finished with the example
drop table dbo.football

</pre></p>
<p>Execute the code above. When you run the <strong>Select</strong> statement you will see that no rows were inserted in the table.</p>
<p>4) Let&#8217;s move on with our next example. I will follow the previous example and I will show you a way to handle exceptions before SQL Server 2005 and <strong>Try Catch</strong> statements were available.In a new query window type the following T-SQL statements.</p>
<p><pre class="brush: sql;">

USE tempdb

go

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

SET XACT_ABORT OFF

DECLARE @myerror int

BEGIN TRANSACTION

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

SET @myerror=@@ERROR
IF (@myerror!=0)GOTO Errorhandler

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

SET @myerror=@@ERROR
IF (@myerror!=0)GOTO Errorhandler

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');

SET @myerror=@@ERROR
IF (@myerror!=0)GOTO Errorhandler

COMMIT TRANSACTION

GOTO NEXT
Errorhandler:
RAISERROR ('we have an error',17,21);
IF @@TRANCOUNT &gt; 0 ROLLBACK TRANSACTION NEXT:

SELECT * FROM DBO.FOOTBALL

--execute this after you have finished with the example
drop table dbo.football

</pre></p>
<p>Execute the code above. In this case nothing will be inserted in the table.You will get the same primary key violation along with our custom message.</p>
<p>We check after every INSERT statement to see if there is an error.We do that by checking the value we get back from the <strong>@@error</strong> global variable. If there is an error (error!=0) we pass the control to the <strong>Errorhandler</strong> block . If there is no error (error=0) we proceed to the next line.If there is no error the transaction is commited.If there is an error we do raise a custom error  by using the <a href="http://msdn.microsoft.com/en-us/library/ms178592.aspx" target="_blank"><strong>raiserror</strong> function</a>.Then we check to see if there are any active transactions and rollback those transactions.Obviously this is a very verbose piece of <strong>T-SQL</strong> code. We have to check for errors after each INSERT statement.We will rewrite the code above using <strong>Try Catch</strong> statements.</p>
<p>5) In a new query window type the following T-SQL statements.</p>
<p><pre class="brush: sql;">

USE tempdb

go

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

BEGIN TRY
BEGIN TRANSACTION

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');

COMMIT TRANSACTION
END TRY

BEGIN CATCH
RAISERROR ('we have an error',17,21);
IF @@TRANCOUNT &gt; 0
ROLLBACK TRANSACTION
END CATCH

SELECT * FROM DBO.FOOTBALL

--execute this after you have finished with the example
drop table dbo.football

</pre></p>
<p>Execute the code above. In this case nothing will be inserted in the table.You will not get the primary key violation message this time.By that I mean that the message that SQL Server would send back to the client is never sent because only the messages in the <strong>Catch</strong> block will be printed out to the client,just the custom message we raise with the <strong>raiserror</strong> function.Have a good look at the code and see how much cleaner syntax we have used. Surely it rings a bell with the .Net developers.</p>
<p>6) This is the last example I would like to show you. I will show you how to use exceptions in a batch where we have various <strong>INSERT</strong> statements and there is a trigger also applied to the table.</p>
<p>Type the code below in a new query window. When  I say type, I mean copy paste the code. In every snippet of code I provide, you can use the icons in the upper right-hand corner to copy the code.</p>
<p><pre class="brush: sql;">

USE tempdb

go

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

--create a trigger that does not allow to enter teams with ID = 4
CREATE TRIGGER TeamID4 ON dbo.football
FOR INSERT
AS
BEGIN
BEGIN TRANSACTION
DECLARE @teamid4 INT
SELECT @teamid4 = COUNT(*) FROM INSERTED WHERE TeamID=4
IF @teamid4 !=0
ROLLBACK TRANSACTION
END

--insert some values that will make the trigger fire

BEGIN TRANSACTION

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (4,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');

COMMIT TRANSACTION

--no values will be inserted
SELECT * FROM DBO.FOOTBALL

--use old school exception handling techniques to get the exception
-- the custom error we want to print out will not get printed to the client

BEGIN TRANSACTION

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (4,'ManUtd','Alex Ferguson','Nemanja Vidić');

IF (@@error !=0) PRINT 'an error has occured'

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');
IF (@@error !=0) PRINT 'an error has occured'

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');
IF (@@error !=0) PRINT 'an error has occured'

COMMIT TRANSACTION

--we will use try catch statements this time and the error is printed to client

BEGIN TRY
BEGIN TRANSACTION

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Everton','David Moyes','Phil Neville');

COMMIT TRANSACTION
END TRY

BEGIN CATCH
RAISERROR ('we have an error',17,21);
IF @@TRANCOUNT &gt; 0
ROLLBACK TRANSACTION
END CATCH

--no values will be inserted in the table
SELECT * FROM DBO.FOOTBALL

--drop the trigger

DROP TRIGGER TeamID4

--execute this after you have finished with the example

drop table dbo.football

</pre></p>
<p>We need to execute the code step by step.First execute the lines 01-24. We create in the <strong>tempdb</strong> database a table (football) and then we create a trigger that does not allow to enter in the table rows where the <strong>TeamID equals 4</strong>.Then execute the code in lines 28-39. The trigger will fire and then we will get an error message like this &#8220;<strong>Msg 3609, Level 16, State 1, Line 3</strong><br />
<strong>The transaction ended in the trigger. The batch has been aborted.</strong>&#8220;If you execute line 42, you will see that naturally no rows were inserted.The trigger fired when the exception took place and rolled back the whole transaction.</p>
<p>Execute the code in lines <strong>47 to 64</strong>. This time we use the <strong>@@error</strong> global variable to check for exceptions.But we will not get our custom error message printed out to the client.When the code executes line <strong>50</strong> then the exception happens and the trigger fires. Nothing after that line is executed. The body of the trigger rollbacks the whole transaction and no lines after<strong> 50</strong> are executed.</p>
<p>Now execute lines <strong>69 to 89</strong> . We basically execute the same code but now we use <strong>try catch</strong> statements.Still there are no rows inserted in the table.But this time we get our custom error to get printed to the client.In my case is &#8220;<strong>Msg 50000, Level 17, State 21, Line 18 we have an error</strong>&#8220;.</p>
<p>So by that you can see that in certain cases we have much more power on how to handle exceptions using <strong>try catch</strong> statements rather than the <strong>@@error</strong> global function.The trigger rollback the transaction but still because of how <strong>try catch</strong> statements work we handle the exception the way we want.</p>
<p>Then we need to drop the trigger and drop the table.</p>
<p>Hopefully you understand how important is to use <strong>Try Catch</strong> blocks in your T-SQL code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/exceptions/'>exceptions</a>, <a href='https://dotnetstories.wordpress.com/tag/try-catch/'>try catch</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1579/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1579/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1579/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1579/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1579/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1579/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1579/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1579/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1579&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/12/looking-into-exceptions-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>A thorough look into transactions in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/11/09/a-thorough-look-into-transactions-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/09/a-thorough-look-into-transactions-in-sql-server/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 16:35:21 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[aspects of transactions]]></category>
		<category><![CDATA[blocking]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[deadlocking]]></category>
		<category><![CDATA[lock modes]]></category>
		<category><![CDATA[locking]]></category>
		<category><![CDATA[trace flags]]></category>
		<category><![CDATA[transactions]]></category>
		<category><![CDATA[types of transactions]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1548</guid>
		<description><![CDATA[In this post I would like to look into transactions in SQL Server. A transaction is a group of tasks that perform as a single unit of work.In database terms all parts of the transaction must be saved in tha database or must be abandoned.It is a great feature in the relational world since through transactions we make sure the database is never in an inconsistent state.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1548&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to look into transactions in SQL Server. A transaction is a group of tasks that perform as a single unit of work.In database terms all parts of the transaction must be saved in the database or must be abandoned.It is a great feature in the relational world since through transactions we make sure the database is never in an inconsistent state.We will need an instance of SQL Server to do our examples.In case you do not have an instance of <strong>Enterprise edition or Developer edition  of SQL Server 2008 / R2</strong>, you can download it from <a href="http://msdn.microsoft.com/en-us/evalcenter/ff459612.aspx" target="_blank">here</a> . This is a trial version. Developer edition has the same features as the Enterprise edition but has different licensing requirements.It is not <a href="http://blog.sqlauthority.com/2008/12/23/sql-server-2008-download-copy-of-developer-edition-for-free-is-myth/" target="_blank">free</a> as many people believe.</p>
<p>We need a database as well. I will use the <strong>Northwind</strong> database.</p>
<p>If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>All transactions must possess the ACID properties. They must be atomic, consistent,isolated and durable.<strong>Atomic</strong> means that a transaction has to work as a unit.That means that the transaction should fully commit or abandon when it completes.Let&#8217;s have a look at an example where we can see what atomicity means in SQL Server.Execute the code below.</p>
<p>1) Launch SSMS and connect to the local instance of SQL Server.</p>
<p><pre class="brush: sql;">

USE tempdb
IF (SELECT  OBJECT_ID('dbo.nikostable')) IS NOT NULL
DROP TABLE dbo.nikostable
GO
CREATE TABLE dbo.nikostable (ID INT CONSTRAINT check_ID CHECK (ID = 1),
NAME NVARCHAR(50) NOT NULL)
GO
INSERT  INTO dbo.nikostable
VALUES (1,'nikos'),(2,'kostas'),(3,'Mary')
GO
SELECT  * FROM    dbo.nikostable
--this is the final step...make sure you do not execute this line until you have
-- completed the previous steps.
DROP TABLE dbo.nikostable
</pre></p>
<p>When you run the code above (including the last <strong>SELECT</strong> statement) you will notice that <span style="text-decoration:underline;">no rows</span> are inserted in the table. I have placed a constraint in the table. Even if I have rows that have values different than &#8220;1&#8243; none of them is inserted in the table.An error is raised when we try to insert rows with ID (2,3). None of these rows will be inserted as they are considered to be a unit of work(atomic) and everything is rolled back.</p>
<p>2) If we write the previous T-SQL statements in a different way, we would get different results.Execute the code below.</p>
<p><pre class="brush: sql;">
USE tempdb
IF (SELECT  OBJECT_ID('dbo.nikostable')) IS NOT NULL
DROP TABLE dbo.nikostable
GO
CREATE TABLE dbo.nikostable(ID INT CONSTRAINT check_ID CHECK (ID = 1),NAME NVARCHAR(50) NOT NULL)
GO
BEGIN TRANSACTION
INSERT  INTO dbo.nikostable
VALUES (1,'nikos')
INSERT  INTO dbo.nikostable VALUES (2,'kostas')
COMMIT TRANSACTION
SELECT  * FROM    dbo.nikostable
DROP TABLE dbo.nikostable
</pre></p>
<p>When you will run the statements above you will see that the first INSERT statement will succeed and the second one will fail.Each statement inside the transaction is atomic. That means each one will act independently of each other.Someone could find this behaviour weird but this is the default behaviour.</p>
<p>3) We could influence this behaviour ( if one statement fails within a transaction all of them fail) by setting the <strong>XACT_ABORT ON</strong>.Εxecute the code below.No rows will be inserted in the table this time. The <strong>XACT_ABORT OFF</strong> is the default option.</p>
<p><pre class="brush: sql;">
USE tempdb
IF (SELECT  OBJECT_ID('dbo.nikostable')) IS NOT NULL
DROP TABLE dbo.nikostable
GO
CREATE TABLE dbo.nikostable
(ID INT CONSTRAINT check_ID CHECK (ID = 1),NAME NVARCHAR(50) NOT NULL)
GO
SET XACT_ABORT ON
GO
BEGIN TRANSACTION
INSERT  INTO dbo.nikostable
VALUES (1,'nikos')
INSERT  INTO dbo.nikostable
VALUES (2,'kostas')
COMMIT TRANSACTION
GO
SELECT  * FROM    dbo.nikostable
SET XACT_ABORT OFF
GO
DROP TABLE dbo.nikostable
</pre></p>
<p><strong>Consistent</strong> means that the transaction must leave all data in a consistent state after the transaction completes.<strong>Isolated</strong> means that all transactions must be independent of the data operations of all other concurrent transactions.<strong>Durable</strong> means that all effects on data are permanent when the transaction fails even if the system fails.SQL Server provides various facilities that ensure that all ACID aspects of a transaction are honoured. We have transaction management systems,locking and logging mechanisms.People believe that SQL Server supports one type of transaction. This is wrong. We have <strong>explicit transactions</strong>,which means that we are responsible for starting(BEGIN TRANSACTION),commiting (COMMIT TRANSACTION) or rollback a transaction (ROLLBACK TRANSACTION).We also have <strong>autocommit</strong> transactions.This is the default mode. This means that all transactions are automatically committed when complete or automatically rolled back when an error occurs.Finally we have <strong>implicit</strong> transactions. In this mode SQL Server starts a new transaction whenever one is committed or rolled back.We have to commit or rollback the transaction.All transactions are managed by SQL Server at the connection level.All statements on that connection belong to the active transaction. Obviously the transactions use resources and while they operate they have locks applied on them.When we commit or rollback a transaction, when the transaction finishes locks and resources used by the transaction are freed.Locks are one way of protecting data.Basically it prevents certain operations on a locked resource (e.g table). The lock is held as long as the transaction is active.For example when we have explicit transactions, locks are held until a COMMIT or ROLLBACK statement.In read-only operations, SQL Server uses shared locks that are quickly released.SQL Server uses <strong>dynamic locking</strong> to find the most cost effective locking strategy/mode for any given operation in the particular resource.Let&#8217;s look into locking,blocking and deadlocking with more details.</p>
<p>What we want is to have highly concurrent SQL Server 2008 R2 applications.In a perfect scenario every SQL query should be able to execute concurrently without any blocking by other queries.What happens in real life is that queries block each other.SQL Server uses <strong>lock manager</strong> to control concurrent access to the database resources. Without the lock manager the data would be in an inconsistent state.So <strong>locking</strong> determines what type of a lock would be placed on a transaction when it wants to access a piece of data-resource.When two sessions (connections are identified by sessions) try to access a common database resource in conflicting ways then the <strong>lock manager</strong> makes the second session waits until the first session completes its task.<strong>Blocking</strong> occurs when a connection/transaction needs to access data and has to wait for another transaction&#8217;s lock to clear.<strong>Deadlocking</strong> is when two or more connections/sessions/transactions have a deadly embrace.Each transaction is waiting on the other for a lock to clear.That is a very bad situation to find ourselves in. That is why we should keep transactions as short as possible.We should try to not require user input and to access the least amount of data.</p>
<p>There are many ways we can get information about the locks and lock types. We have  <strong>Activity Monitor</strong> and <strong>SQL Server Profiler</strong>.I am sure you are familiar with both these tools. SQL Server Profiler has a locks event category and we can get much information about locks.There is also the <strong>sys.dm_tran_locks</strong> dynamic management view.You can also use <strong>sp_lock</strong> and <strong>sp_who</strong>(<strong>sp_who2</strong>) system stored procedures.</p>
<p>Αnother important issue when it comes to transactions,connections,sessions is the <strong>isolation level</strong>.Τhe isolation level defines how much a transaction has to be isolated from other transactions.It determines the possible side effects from uncommitted changes.The default isolation level is <strong>READ COMMITTED</strong>.If you want to learn more about isolation levels have a look <a href="http://msdn.microsoft.com/en-us/library/ms173763.aspx" target="_blank">here</a>.</p>
<p>Let&#8217;s have a look at a locking example.We will simulate a locking situation</p>
<p>5) In a new query window (first-1st) type the following and execute the code</p>
<p><pre class="brush: sql;">

USE Northwind
GO
BEGIN TRANSACTION
UPDATE dbo.Categories
SET CategoryName = 'Fishfood'
WHERE CategoryName = 'Seafood';

</pre></p>
<p>In a new query window (second-2nd) type the following and execute the code</p>
<p><pre class="brush: sql;">

USE Northwind
SELECT CategoryName FROM dbo.Categories;

</pre></p>
<p>Now I will use the <strong>Activity Monitor</strong> to collect information about the locking that takes place.Select in the Object Explorer window the instance of the SQL Server and right-click and choose <strong>Activity Monitor</strong>.</p>
<p>Ηave a look at the picture below.Note the SPID 54.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/activitymonitor-lock.jpg"><img class="aligncenter size-large wp-image-1553" title="activitymonitor-lock" src="http://dotnetstories.files.wordpress.com/2011/11/activitymonitor-lock.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>In order to resolve the locking issue we can type ( in the first query window)</p>
<p><pre class="brush: sql;">

ROLLBACK TRANSACTION

</pre></p>
<p>6) Now I will show you how to get the same information using <strong>SQL Server Profiler</strong>.We will need to use an event. We need to identify long-running blocked processes.In this case we will <strong>Blocked Process Repor</strong>t event.This event is turned off by default. I know this might sound strange to you but this is the case.</p>
<p>We need to write T-SQL statements to enable the <strong>Blocked Process Repor</strong>t event.Execute the code below.</p>
<p><pre class="brush: sql;">
SP_CONFIGURE'show advanced options',1 ;
GO
RECONFIGURE
GO
SP_CONFIGURE'blocked process threshold',5 ;
GO
RECONFIGURE
GO
</pre></p>
<p>Launch SQL Server Profiler, connect ( most likely Windows Authentication ) to the instance of SQL Server.From the available templates use <strong>TSQL_Locks</strong>.In the <strong>Event Selection tab</strong> deselect all the events but the <strong>Blocked Process Repor</strong>t event. Give your trace a name e.g Locking_Info. Then hit the <strong>Run</strong> button.</p>
<p>We will have to simulate the same locking example as before.</p>
<p>So first you write in a new query window the <strong>1st</strong> T-SQL statement (see previous example) and then in a new query window the <strong>2nd</strong> T-SQL statement.</p>
<p>Wait for 30 seconds and have a look at the results in the Profiler. Have a look at the picture below to see what I got when I run the same trace in the Profiler.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/blockedreportevent.jpg"><img class="aligncenter size-large wp-image-1554" title="blockedreportevent" src="http://dotnetstories.files.wordpress.com/2011/11/blockedreportevent.jpg?w=1024&#038;h=557" alt="" width="1024" height="557" /></a></p>
<p>Run this statement in the 1st query window to resolve the blocking issue.</p>
<p><pre class="brush: sql;">

ROLLBACK TRANSACTION

</pre></p>
<p>Stop the trace in the profiler and exit the profiler.</p>
<p>7) Now we will use the same example as before and get locking information using the <strong>sp_who2</strong> system stored procedure.</p>
<p>We will have to simulate the same locking example as before.</p>
<p>So first you write in a new query window the <strong>1st</strong> T-SQL statement (see previous example) and then in a new query window the <strong>2nd</strong> T-SQL statement.</p>
<p>In a third query window type</p>
<p><pre class="brush: sql;">

sp_who2 54

</pre></p>
<p>I did not choose 54 was the SPID of the 2nd statement ( SELECT CategoryName FROM dbo.Categories;). So in your case you should choose a different SPID.</p>
<p>Have a look at the picture below to see what kind of results I get by running the <strong>sp_who2</strong> stored procedure.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/sp_who2.jpg"><img class="aligncenter size-large wp-image-1555" title="sp_who2" src="http://dotnetstories.files.wordpress.com/2011/11/sp_who2.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Now if you wonder why the second transaction(the SELECT statement) was blocked, this is because the first transaction had placed a lock on the resource ( table Categories ) with the <strong>lock mode</strong> of <strong>X</strong> (exclusive lock).If you want to see what kind of locks(lock type,lock mode) take place on what resource you can use <strong>sp_lock</strong> system stored procedure e.g <strong>sp_lock 57</strong> in a new query window.</p>
<p>When we execute a query ,SQL Server determines the database resources that need to be accessed and then the lock manager grants database locks to the process.So the query is executed after acquiring the required locks.During the query execution the locks do not remain the same. By that I mean that the lock manager escalates the locks to various <strong>lock levels</strong>. This is known as <strong>lock escalation</strong>.Obviously we , the developers, we could not be in charge of such a complex process.The lock manager takes charge of that.All that takes place during the course of the transaction. We have various lock levels.We have row locks, these locks are maintained at a row level.We have page level locks, these locks are maintained at page level. SQL Server lock manager can escalate from row,page level locks to table level locks. When this happens all lower level locks are released.We also have lock modes. The lock manager grants locks on resource types by mode.We have <strong>Sch-S</strong> lock mode which prevents transactions from altering the schema of a resource while it is in use. We have <strong>S-shared</strong> lock mode which is compatible with all other lock modes except exclusive locks <strong>X</strong>-<strong>mode</strong>.<strong>X-mode</strong> is granted to resources that is being dropped/created or modified.I will use a new example and the <strong>sp_lock</strong> stored procedure.It will be something similar like the previous example.</p>
<p>In a new query window type (in my example this is session 53)</p>
<p><pre class="brush: sql;">

USE Northwind
GO
BEGIN TRANSACTION
UPDATE dbo.Categories
SET CategoryName = 'Refreshments'
WHERE CategoryName = 'Drinks';

</pre></p>
<p>Execute the query.</p>
<p>In an new query window type(in my example this is session 58)</p>
<p><pre class="brush: sql;">

USE Northwind
go
SELECT CategoryName FROM dbo.Categories;

</pre></p>
<p>Execute the query above.This is going to be a blocked query.</p>
<p>In a new query window type</p>
<p><pre class="brush: sql;">

EXEC sp_lock 53
EXEC sp_lock 58

</pre></p>
<p>When you execute the query above you will get results similar to these. Note the <strong>Mode</strong> and <strong>Type</strong> columns.You can notice the lock escalation as the query is executed and the lock modes granted.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/sp_lock.jpg"><img class="aligncenter size-large wp-image-1561" title="sp_lock" src="http://dotnetstories.files.wordpress.com/2011/11/sp_lock.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>8) Now that we have seen some examples about locking and blocking , I would like to look into <strong>deadlocks</strong>.</p>
<p>I have explained previously what a dealock is and one more simpler explanation is that we have locks on resources that are held for too long.Two seperare processes/transactions hold locks on resources that each other needs.So this is a deadlock. Nothing can happen. This situation could go on forever.But one of the transactions is forced by SQL Server to &#8220;die&#8221;.SQL Server selects a <strong>victim</strong> and kills the process/transaction.It usually kills the one that is least expensive to roll back.We can also have some control over the process to be chosen to be the victim by setting the deadlock priority by typing  &#8220;SET DEADLOCK_PRIORITY LOW&#8221;.This option makes SQL Server to choose that session to be the victim when a deadlock occurs.  When we have a deadlock situation an error with the code <strong>1205</strong> is generated.Τhere are many ways to find information about deadlocks. We have two trace flags that help us analyse deadlocks.These flags are <strong>1222</strong> and <strong>1204</strong>.We can turn them on by typing</p>
<p><pre class="brush: sql;">

DBCC TRACEON (1222,-1)
DBCC TRACEON (1204,-1)
</pre></p>
<p>The deadlock information is stored in the error log.</p>
<p>When you use lower isolation levels helps to avoid transactions.Another thing to avoid is recursive and nested triggers.</p>
<p>I will show you an example on deadlocks. I will simulate a deadlock situation and I will use <strong>SQL Server Profiler</strong> to catch the deadlock information.</p>
<p>Before we move on with our T-SQL statements, we need to launch <strong>SQL Server Profiler</strong>.From the <strong>SSMS</strong> environment type go to Tools-&gt; SQL Server Profiler.</p>
<p>Launch SQL Server Profiler, connect ( most likely Windows Authentication ) to the local instance of SQL Server.From the available templates use <strong>TSQL_Locks</strong>.In the <strong>Event Selection tab</strong> do not deselect any event. Give your trace a name e.g <strong>DeadLocking_Info</strong>. Then hit the <strong>Run</strong> button.</p>
<p>In a new query window , execute this first statement.</p>
<p><pre class="brush: sql;">

USE Northwind
GO
--open a query window (1) and run these commands
begin tran
update products set CategoryID = 7

</pre></p>
<p>In a new query window , execute this second statement.</p>
<p><pre class="brush: sql;">

use Northwind
GO
--go to query window (2) and run this command

begin tran
UPDATE Suppliers set CompanyName = 'Mycompany'
update products set CategoryID = 12

</pre></p>
<p>Go back to the first query window, and execute this third statement.</p>
<p><pre class="brush: sql;">

-- go back to query window (1) and run this command

update Suppliers set CompanyName = 'TheCompany'

</pre></p>
<p>Now we have a deadlock situation. Switch to your Profiler. Pause the trace and look for the  <strong>Deadlock events</strong>.</p>
<p>You will see something similar with the picture below.You can see the Deadlock graph event and the graph with all the processes involved in the deadlock and the deadlock victim.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/11/deadlock.jpg"><img class="aligncenter size-large wp-image-1558" title="deadlock" src="http://dotnetstories.files.wordpress.com/2011/11/deadlock.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Go  to the first query window, and execute this  statement to undo all changes</p>
<p><pre class="brush: sql;">

ROLLBACK

</pre></p>
<p>Go  to the second query window, and execute this  statement to undo all changes.</p>
<p><pre class="brush: sql;">

ROLLBACK

</pre></p>
<p>I hope you realise how bad deadlocks is for the performance of our system.</p>
<p>I know this was a very long post and we talked about many things like transactions,aspects of transactions,types of transactions,concurrency,locking,blocking,deadlocking,lock modes e.t.c.</p>
<p>Hope it helps.</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/aspects-of-transactions/'>aspects of transactions</a>, <a href='https://dotnetstories.wordpress.com/tag/blocking/'>blocking</a>, <a href='https://dotnetstories.wordpress.com/tag/concurrency/'>concurrency</a>, <a href='https://dotnetstories.wordpress.com/tag/deadlocking/'>deadlocking</a>, <a href='https://dotnetstories.wordpress.com/tag/lock-modes/'>lock modes</a>, <a href='https://dotnetstories.wordpress.com/tag/locking/'>locking</a>, <a href='https://dotnetstories.wordpress.com/tag/trace-flags/'>trace flags</a>, <a href='https://dotnetstories.wordpress.com/tag/transactions/'>transactions</a>, <a href='https://dotnetstories.wordpress.com/tag/types-of-transactions/'>types of transactions</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1548/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1548&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/09/a-thorough-look-into-transactions-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/activitymonitor-lock.jpg?w=1024" medium="image">
			<media:title type="html">activitymonitor-lock</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/blockedreportevent.jpg?w=1024" medium="image">
			<media:title type="html">blockedreportevent</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/sp_who2.jpg?w=1024" medium="image">
			<media:title type="html">sp_who2</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/sp_lock.jpg?w=1024" medium="image">
			<media:title type="html">sp_lock</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/11/deadlock.jpg?w=1024" medium="image">
			<media:title type="html">deadlock</media:title>
		</media:content>
	</item>
		<item>
		<title>Looking into Resource Governor in SQL Server 2008</title>
		<link>https://dotnetstories.wordpress.com/2011/11/05/looking-into-resource-governor-in-sql-server-2008/</link>
		<comments>https://dotnetstories.wordpress.com/2011/11/05/looking-into-resource-governor-in-sql-server-2008/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 16:38:32 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[Classification function]]></category>
		<category><![CDATA[Resource Governor]]></category>
		<category><![CDATA[Resource pool]]></category>
		<category><![CDATA[Workload group]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1539</guid>
		<description><![CDATA[In this post I would like to talk about a new feature in SQL Server 2008, Resource Governor and what this new feature offers us in terms of performance and good use of resources.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1539&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about a new feature in SQL Server 2008, <strong>Resource Governor </strong>and what this new feature offers us in terms of performance and good use of resources.<strong><br />
</strong></p>
<p>I know there are samples of how to use <strong></strong><strong>Resource Governor</strong> in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p>Before we move on I would like to note that this is an Enterprise Feature only. In case you do not have an instance of <strong>Enterprise edition or Developer edition  of SQL Server 2008 / R2</strong>, you can download it from <a href="http://msdn.microsoft.com/en-us/evalcenter/ff459612.aspx" target="_blank">here</a> . This is a trial version. Developer edition has the same features as the Enterprise edition but has different licensing requirements.It is not <a href="http://blog.sqlauthority.com/2008/12/23/sql-server-2008-download-copy-of-developer-edition-for-free-is-myth/" target="_blank">free</a> as many people believe. <strong>Resource Governor</strong> works with the database engine and not with <strong>Integration</strong>,<strong>Reporting</strong>,<strong>Analysis</strong> services.</p>
<p>In many cases we have a situation where we have a database, an OLTP system that has heavy workloads.At the same time we have some senior managers that run reports on the same database which makes things even worse when it comes to performance of the OLTP system.Sometimes people find some compromise. The DBAs of such a system tell the senior managers or sales executives to run their long-running reports at times where there is no heavy workload , e.g at late afternoon. Obviously this is not a good solution.It is not a technical solution.With <strong>Resource Governor</strong> we can control resources (CPU and memory) and assign them to a particular workload.For example we can say that 90% of available resources can be allocated/assigned to OLTP workloads and 10% to be allocated to long-running reports.Well, with that configuration we will impact the performance of the long-running queries but will not affect the OLTP production system.</p>
<p>So we have the typical ( not correct ) configuration where we have the OLTP system(e-shop,ERP) and a third party reporting application that accesses directlyour database.We do not want to have this sort of OLAP reporting blocking the OLTP activity.We want to limit the CPU and memory resources for the reporting application to 10% of what the server has available.Obviously we need some sort of way to divide the various workloads and allocate them memory and CPU. We will do that by using the classification function.The classification function is used by the <strong>Resource Governor</strong> to determine which connection(application) is made to the database. Basically it tells the Resource Governor which application (OLTP application or Reporting application) is connecting to the database.Then the connection is directed to a particular <strong>workload group</strong>.The workload group has connections that are defined by the classification function . In our case we need to create 2 workload groups.Now that we have seperated the connections from each application we need to allocate resources to these connections.We will do that by creating resource pools. A <strong>resource pool</strong> represents the physical resources of a server.We need to create 2 resource pools in our scenario.We will use these resource pools to allocate the minimum and maximum resources (CPU &amp; Memory) that will be allocated to the 2 applications accessing our database.One resource pool is associated with the (OLTP) workload group and the other one is associated to the reporting workload group.</p>
<p>Let’s move on with our hands on example.</p>
<p>1) Launch SSMS and connect to the local instance of SQL Server.We will create the resource pools first.Execute the code below.</p>
<p><pre class="brush: sql;">
USE MASTER
GO

CREATE RESOURCE POOL OLTPApplicationpool
WITH
(
MAX_CPU_PERCENT=100,
MAX_MEMORY_PERCENT=100,
MIN_CPU_PERCENT=90,
MIN_MEMORY_PERCENT=90
);
GO

CREATE RESOURCE POOL ReportingApplicationpool
WITH
(
MAX_CPU_PERCENT=10,
MAX_MEMORY_PERCENT=10,
MIN_CPU_PERCENT=0,
MIN_MEMORY_PERCENT=0
);
GO
</pre></p>
<p>By running the code above we say that the OLTP application (through the resource pool) will use up to the 100% of the available CPU and memory resources.At the same time I specify that the OLTP application will use minimum of 90% of the total CPU and resources available.</p>
<p>2) Then we need to create the workload groups. We also need to associate the workload groups to the resource pools.Execute the code below.</p>
<p><pre class="brush: sql;">

CREATE WORKLOAD GROUP workgroupOLTP
USING OLTPApplicationpool
GO

CREATE WORKLOAD GROUP WorkgroupReports
USING ReportingApplicationpool
GO

</pre></p>
<p>3) Now we need to create the classification function that will determine which connections will go to which workload group.Execute the code below to create the classification function.</p>
<p><pre class="brush: sql;">

CREATE FUNCTION classificationOLTPReports() RETURNS SYSNAME
WITH SCHEMABINDING
AS
BEGIN
DECLARE @group_Name  AS SYSNAME
IF (APP_NAME() = 'ABCReports')
SET @group_Name = 'WorkgroupReports'
ELSE
SET @group_Name = 'workgroupOLTP'
RETURN @group_Name
END
GO

</pre></p>
<p>4) Now we need to enable the <strong>Resource Governor</strong>.We will register the classification function first with the <strong>Resource Governor</strong>.Execute the code below.</p>
<p><pre class="brush: sql;">

ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION= dbo.classificationOLTPReports);
GO

-- Start/Enable Resource Governor
ALTER RESOURCE GOVERNOR RECONFIGURE;
GO;
</pre></p>
<p>I am sure you can appreciate now the benefits of <strong>Resource Governor</strong>.Use <strong>Resource Governor</strong> to make the impact of long-running reports to your heavily accessed database minimal.It is a very good reason to upgrade to SQL Server 2008.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/classification-function/'>Classification function</a>, <a href='https://dotnetstories.wordpress.com/tag/resource-governor/'>Resource Governor</a>, <a href='https://dotnetstories.wordpress.com/tag/resource-pool/'>Resource pool</a>, <a href='https://dotnetstories.wordpress.com/tag/workload-group/'>Workload group</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1539/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1539/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1539/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1539/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1539/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1539/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1539/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1539/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1539&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/11/05/looking-into-resource-governor-in-sql-server-2008/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Looking into Transparent Data Encryption</title>
		<link>https://dotnetstories.wordpress.com/2011/10/30/looking-into-transparent-data-encryption/</link>
		<comments>https://dotnetstories.wordpress.com/2011/10/30/looking-into-transparent-data-encryption/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 22:13:53 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[cell level encryption]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[key]]></category>
		<category><![CDATA[TDE]]></category>
		<category><![CDATA[Transparent Data Encryption]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1528</guid>
		<description><![CDATA[In this post I would like to look into Transparent Data Encryption (TDE) works in SQL Server 2008.I would like to stress that this is an SQL Server 2008/R2 Entreprise/Developer editions feature only.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1528&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to look into <strong>Transparent Data Encryption (TDE)</strong> works in SQL Server 2008.I would like to stress that this is an SQL Server 2008/R2 Entreprise/Developer edition feature only.</p>
<p>I know there are samples of how to use <strong>Transparent Data Encryption</strong> in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p><strong>Transparent Data Encryption</strong> does real time encryption/decryption of data and log files.Real time means that encryption happens as the data flows from memory to the disk and decryption happens when data is read from disk to memory.Obviously we do need more CPU resources to implement <strong>TDE</strong>.However if your SQL Server instance experiences CPU bottlenecks then you should not use it or use it with caution.</p>
<p>So the encryption happens at the file level. It encrypts all the data in the database.By that I mean that besides .mdf, .ldf files tempdb,backups and snapshots are also encrypted. <strong>TDE</strong> encrypts and decrypts each <strong>8K page</strong>.</p>
<p>There is no proramming required.It is very easy to set up <strong>TDE</strong> in a database and <strong>TDE</strong> is transparent to the application.We cannot use <strong>TDE</strong> with databases that have <strong>FILESTREAM</strong> data. When we have <strong>TDE</strong> turned on we cannot have on this database turned backup compression as well.So we cannot have backup compression and encryption on the same database.Obviously you cannot restore an encrypted backup to different SQL Server instance.If any database in the server instance uses <strong>TDE</strong> then the <strong>tempdb</strong> is encrypted as well.By that I mean that even if a specific database that does not use the <strong>tempdb</strong> at all, has <strong>TDE turned on, </strong>the  <strong>tempdb</strong> will still be encrypted.</p>
<p>In SQL Server 2005 we had another form of encryption that was called cell-level encryption. It provides encryption at the cell level or column level(I will provide an example later on).In previous versions of SQL Server e.g SQL Server 2000 we had to write code in our application where all the <strong>encryption/decryption</strong> occurred.Obviously with this option we could achieve the <strong>granularity</strong> that we miss with <strong>TDE</strong> but using cell level encryption still left much of the data unencrypted while it requires changes to the underlying database schema. Finally I would like to dissolve a myth regarding <strong>TDE</strong> and restricting access to a spesific database data. <strong>TDE</strong> is not a way to restrict data access through the database engine. If the application has permissions on a database that is encrypted then it will be able to access the data.<strong>TDE</strong> is not a substitution for securing the SQL Server instance or securing sensitive data in a database.We still need to implement security at any level.</p>
<p>Now let&#8217;s have a closer look on how <strong>TDE</strong> works.</p>
<p>We need to create a master key which will use to protect the certificate. All master keys are encrypted in the <strong>master</strong> database.</p>
<p>You also require to create a certificate to access the physical files.We should not ship the certificate with the encrypted database files.This certificate will protect the database encryption key. This certificate is also stored in the <strong>master</strong> database.Then we need to create the database encryption key. This is the key that will encrypt the data. Finally we need to turn <strong>TDE</strong> on.</p>
<p>In case you do not have an instance of <strong>Enterprise edition or Developer edition  of SQL Server 2008 / R2</strong>, you can download it from <a href="http://msdn.microsoft.com/en-us/evalcenter/ff459612.aspx" target="_blank">here</a> . This is a trial version.</p>
<p>We need a database as well. I will use the <strong>Northwind</strong> database.</p>
<p>If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>Let&#8217;s move on with our hands on example</p>
<p>1) Launch SSMS and connect to the local instance of SQL Server.First I will create a copy of the <strong>Northwind</strong> database.I do not want to work with the original I will use back and restore T-SQL commands.Execute the code below to perform the backup</p>
<p><pre class="brush: sql;">
USE master
GO

BACKUP DATABASE [Northwind]
TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\Northwind.bak'
WITH NOFORMAT, NOINIT,  NAME = N'Northwind-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

</pre></p>
<p>Now execute the code below to perform the restore operation.</p>
<p><pre class="brush: sql;">
USE master
GO
RESTORE DATABASE [NorthwindCopy]
FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\Northwind.bak' WITH
FILE = 1,  MOVE N'Northwind' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\NorthwindCopy.mdf',
MOVE N'Northwind_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\NorthwindCopy_1.ldf',  NOUNLOAD,  STATS = 10
GO

</pre></p>
<p>2) Now let&#8217;s create the master key in <strong>master</strong> database to use with <strong>TDE</strong>.Execute the code below.</p>
<p><pre class="brush: sql;">
USE master
GO

CREATE MASTER KEY ENCRYPTION BY PASSWORD = '!@#$%^&amp;*()'
GO

</pre></p>
<p>3) Now we need to create the certificate used to protect the database encryption key.Execute the code below.</p>
<p><pre class="brush: sql;">
USE master
GO

CREATE CERTIFICATE NorthwindCopyCertification WITH SUBJECT
= 'Certificate to implement TDE on NorthwindCopy'
GO

</pre></p>
<p>4) Now we need to backup the certificate.If the certificate becomes corrupted then we can use the backup copy of the certificate.Exeute the code below.</p>
<p><pre class="brush: sql;">
USE master
GO

BACKUP CERTIFICATE NorthwindCopyCertification
TO FILE = 'C:\Data\NorthwindCopyCertification'
WITH PRIVATE KEY ( FILE = 'C:\Data\NorthwindCopyCertificationPrivateKey' ,
ENCRYPTION BY PASSWORD = '!@#$%^&amp;' );
GO
</pre></p>
<p>5) We can check to see if there are any databases encrypted in this instance of SQL Server.Execute the code below. In my case when I execute the code I get no results.</p>
<p><pre class="brush: sql;">
USE master
GO

SELECT DB_NAME(database_id) AS DatabaseName,
key_algorithm AS [Algorithm],
key_length AS KeyLength,encryption_state

FROM sys.dm_database_encryption_keys
GO
</pre></p>
<p>6) Now we need to create the database encryption key for <strong>TDE</strong>.This is analogous to database master key for data encryption.</p>
<p><pre class="brush: sql;">
USE NorthwindCopy
GO

CREATE DATABASE ENCRYPTION KEY
WITH ALGORITHM = TRIPLE_DES_3KEY
ENCRYPTION BY SERVER CERTIFICATE NorthwindCopyCertification
GO
</pre></p>
<p>7) Now we need to turn <strong>TDE</strong> on.This will take some time. That depends on the hardware level and size of the database.Then we check again to see if the database is encrypted. Execute the code below.</p>
<p><pre class="brush: sql;">
USE NorthwindCopy
GO

ALTER DATABASE NorthwindCopy SET ENCRYPTION ON
GO

SELECT DB_NAME(database_id) AS DatabaseName,
key_algorithm AS [Algorithm],
key_length AS KeyLength,encryption_state

FROM sys.dm_database_encryption_keys
GO
</pre></p>
<p>After executing this code I see that <strong>tempdb</strong> and <strong>NorthwindCopy</strong>are both encrypted. That was to be expected.</p>
<p>Have a look at the picture below.<strong>Encryption_state</strong> 3 means that the database is encrypted.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/tde.jpg"><img class="aligncenter size-large wp-image-1532" title="tde" src="http://dotnetstories.files.wordpress.com/2011/10/tde.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>8) Now we can run a SQL statement to see if we can select data from the database.Execute the code below and you will see the results.There will be no difference.The encryption applies to the files.</p>
<p><pre class="brush: sql;">
USE NorthwindCopy
GO

SELECT [CategoryID]
,[CategoryName]
,[Description]
,[Picture]
FROM [NorthwindCopy].[dbo].[Categories]

</pre></p>
<p>If you need to turn TDE off you can run the following T-SQL statement.It will take some time for SQL Server to decrypt the data.</p>
<p><pre class="brush: sql;">

ALTER DATABASE NorthwindCopy SET ENCRYPTION OFF
GO

</pre></p>
<p>If you try to restore the encrypted database to another instance it will fail.</p>
<p>Now let me show you an example where I can use <strong>Cell level Encryption</strong>. The first thing we can say about cell level encryption is that it is more granular than <strong>TDE</strong>.Data is decrypted only when used. It requires changes to the schema and applications. Bear in mind that you cannot search,sort data and indexes are of no use.You can use cell level encryption in SQL Server 2005 and later.</p>
<p>Use cell encryption when performance is not an issue and for small amounts of data.If the threat is the theft of database files then you should use <strong>TDE</strong></p>
<p>9)Let me provide you with a simple example of cell level encryption.I will create a new database. I will create a new table and insert some records in it.</p>
<p><pre class="brush: sql;">

CREATE DATABASE footballdata

USE footballdata
go

CREATE TABLE [dbo].[footballers](
[id] [int] PRIMARY KEY IDENTITY(1,1),
[firstname] [varchar](50) NOT NULL,
[lastname] [varchar](50) NOT NULL,
[isActive] [bit] NULL
)

GO

INSERT INTO Footballers(firstname,lastname,isActive)

VALUES ('Steven','Gerrard',1);

INSERT INTO Footballers(firstname,lastname,isActive)

VALUES ('John','Terry',1);

INSERT INTO Footballers(firstname,lastname,isActive)

VALUES ('Kenny','Dalglish',0);

SELECT * FROM footballers
go

</pre></p>
<p>10) Now we need to follow more or less the same process as with TDE.I create the master key, the encryption certificate and the symmetric key.Execute the code below and note the comments.</p>
<p><pre class="brush: sql;">

--Create Database Master Key
USE footballdata
GO
CREATE MASTER KEY ENCRYPTION
BY PASSWORD = '!@#$%^&amp;'
GO

-- Create Encryption Certificate
USE footballdata
GO
CREATE CERTIFICATE EncryptfootballdataCert
WITH SUBJECT = 'Encrypt footballdata'
GO

--Create Symmetric Key
USE footballdata
GO
CREATE SYMMETRIC KEY footballdataKey
WITH ALGORITHM = TRIPLE_DES ENCRYPTION
BY CERTIFICATE EncryptfootballdataCert
GO

</pre></p>
<p>11) Let&#8217;s say we want to encrypt the third column-lastname. The next step is to add a column of type varbinary to the table which will store the encrypted values from the second column.Execute the code below.</p>
<p><pre class="brush: sql;">

USE footballdata
GO
ALTER TABLE footballers
ADD Encryptlastname VARBINARY(256)
GO

</pre></p>
<p>12) Now we need to update the column with the encrypted data created by key and certificate. I use the <strong>ENCRYPTBYKEY</strong> function. Execute the code below.</p>
<p><pre class="brush: sql;">

USE footballdata
GO

OPEN SYMMETRIC KEY footballdataKey DECRYPTION
BY CERTIFICATE EncryptfootballdataCert
UPDATE footballers
SET Encryptlastname = ENCRYPTBYKEY(KEY_GUID('footballdataKey'),lastname)
GO
--now we drop the third column from the table

ALTER TABLE footballers
DROP COLUMN lastname

--select the data from the table and see the encrypted data.
SELECT * FROM footballers

</pre></p>
<p>Now we have encrypted the column (lastname) successfully.</p>
<p>13) Now we can decrypt the data of the column (lastname) if we want and are authorised to do so.I use the <strong>DECRYPTBYKEY</strong> function. Execute the code below and see the decrypted results.</p>
<p><pre class="brush: sql;">

USE footballdata
GO
OPEN SYMMETRIC KEY footballdataKey DECRYPTION
BY CERTIFICATE EncryptfootballdataCert
SELECT CONVERT(VARCHAR(50),DECRYPTBYKEY(Encryptlastname))
FROM footballers
GO

</pre></p>
<p>That is all for now.You can drop the database (footballdata) if you want.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/cell-level-encryption/'>cell level encryption</a>, <a href='https://dotnetstories.wordpress.com/tag/certificate/'>certificate</a>, <a href='https://dotnetstories.wordpress.com/tag/encryption/'>encryption</a>, <a href='https://dotnetstories.wordpress.com/tag/key/'>key</a>, <a href='https://dotnetstories.wordpress.com/tag/tde/'>TDE</a>, <a href='https://dotnetstories.wordpress.com/tag/transparent-data-encryption/'>Transparent Data Encryption</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1528/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1528/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1528/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1528/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1528/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1528/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1528/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1528&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/10/30/looking-into-transparent-data-encryption/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/tde.jpg?w=1024" medium="image">
			<media:title type="html">tde</media:title>
		</media:content>
	</item>
		<item>
		<title>Looking into Security in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/10/17/looking-into-security-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/10/17/looking-into-security-in-sql-server/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 23:55:56 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Authentication mode]]></category>
		<category><![CDATA[Authorisation]]></category>
		<category><![CDATA[Denial of Service]]></category>
		<category><![CDATA[Elevation of Privilege]]></category>
		<category><![CDATA[Information disclosure]]></category>
		<category><![CDATA[Mixed Mode]]></category>
		<category><![CDATA[principal]]></category>
		<category><![CDATA[Privilege]]></category>
		<category><![CDATA[Repudiation]]></category>
		<category><![CDATA[securable]]></category>
		<category><![CDATA[Spoofing identity]]></category>
		<category><![CDATA[Tampering]]></category>
		<category><![CDATA[Windows Authentication Mode]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1477</guid>
		<description><![CDATA[In this post I would like to talk about Security in SQL Server. This is a very big topic and you should embrace yourselves for a very long post.

I know there are samples of how to use secure data in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.

Many people have found useful my style of posting. They feel they can follow the steps and master the technology.

At the beginning I will give a short introduction about the various security threats that our systems face and then look into aspects of Security in SQL Server .Then I will provide many examples on how to secure data in SQL Server.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1477&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about <strong>Security in SQL Server</strong>. This is a very big topic and you should embrace yourselves for a very long post.</p>
<p>I know there are samples of how to use secure data in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p>Many people have found useful my style of posting. They feel they can follow the steps and master the technology/topic.</p>
<p>At the beginning I will give a short introduction about the various security threats that our systems face and then look into aspects of<strong> Security in SQL Server</strong> .Then I will provide many examples on how to secure data in SQL Server.</p>
<p>Let&#8217;s have a look at the main security threats that systems face nowadays. Obviously we can not analyse any of them too much.</p>
<p><strong>Spoofing identity</strong>, means using <strong>valid user&#8217;s credentials</strong> so that an attacker can impersonate that user.</p>
<p><strong>Tampering</strong>  is the deliberate destruction of data.</p>
<p><strong>Repudiation</strong> basically means that something that happened in our system was not properly logged or tracked leaving our system open to exploitation.</p>
<p><strong>Information disclosure</strong> means that that we accidentally hand to our &#8220;enemies&#8221; valuable information about a system. Sometimes even HTTP Headers can reveal a lot of information to a malicious user.</p>
<p><strong>Denial of Service</strong> is a term used to describe attacks that attempt to lower application availability and reliability.</p>
<p><strong>Elevation of Privilege</strong> is a threat that occurs when the malicious user gets privileged access to a system or data.</p>
<p>As I said before these terms above are used to generally describe security threats in many software systems including RDBMS.</p>
<p>There are different kind of threats to SQL Server that DBAs and developers must be aware of.Unfortunately we do not live in a world where other people <strong>respect</strong> our systems and data.All these malicious people and programs have the potential to harm/steal our sensitive data.</p>
<p>They should not have access to our sensitive data.Imagine the situation where a former empoyee in your company leaves the company , not in the best terms, and has access to your SQL Server through the <strong>SA</strong> account, or any other account.We should protect the data from people like that.</p>
<p>But I have also found that we should protect our data from our <span style="text-decoration:underline;">less malicious users</span>, people who work in our company but have not the skills or the knowledge to protect the data. Sometimes it happens that a user has more &#8220;authorisation&#8221; than he should have, on a database or a table and accidentally deletes them.Ηaving said all that,  data must be <strong>protected</strong> but at the same time data must be <strong>available</strong> to the users.</p>
<p>It is quite obvious that the so-called &#8220;hackers&#8221; or malicious users, want to get their hands on ou system and compromise them. Delete data or interfere with our data in a catastrophic way.</p>
<p>As I said earlier do not underestimate the power that the &#8220;accidental&#8221; user has over the data . So make sure he does not have &#8220;rights&#8221; to access sensitive data(more on that later)..</p>
<p>Before I move on and explain how to set up logins,create users and roles I would like to tell you a few things that help <strong>secure</strong> SQL Server.</p>
<p>Some things are really simple and very easy to do.Make sure you have downloaded and installed all the <strong>latest service packs</strong> for the SQL Server version you have, running in your machine.Needless to say that you must install all <strong>patches and updates</strong> regarding Windows OS.  You should install a very good <strong>antivirus</strong> program and have set up a <strong>firewall</strong> program configured properly.</p>
<p>Install only the components that you really need. When installing the e.g Enterprise edition of <strong>SQL Server 2008 R2</strong> you see that there are many components that you could install.If you do not need to install <strong>SQL Server Analysis Services</strong>, <strong>SQL Server Integration Services</strong>,<strong>SQL Reporting Services</strong> then do not.Try (if this is an option for you) not to install <strong>SQL Server Reporting Services</strong> on the same server as the database engine.IIS and web services bring a lot of vulnerabilities to SQL Server.You can also disable SQL Server services that you are not going to use.Disable the<strong> VSS writer service</strong> and the <strong>SQL Server Browser</strong>.</p>
<p>You should also disable the network protocols that aren&#8217;t required.You could,for example, disable <strong>Named Pipes</strong> and enable TCP/IP. You could do all these using the <strong>SQL Server Configuration Manager</strong>.</p>
<p>Have a look at the picture below. You will see that TCP/IP is enabled but configured to a different port than the default port(1433).This is also a thing you should keep in mind and apply it to your SQL Server instances. Use a different TCP/IP port than the default one.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/sqlserverconfiguration.jpg"><img class="aligncenter size-large wp-image-1479" title="sqlserverconfiguration" src="http://dotnetstories.files.wordpress.com/2011/10/sqlserverconfiguration.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>We could break down security in two major <em>components</em>.</p>
<p><strong>Authentication</strong>: In simple words that means who should be able to access the data.</p>
<p><strong>Authorisation</strong>: In simple words that means who activities, people/entities can perform on the data when they are authenticated.</p>
<p>Before we move on, we should define some basic terms that are very important when we talk about security in SQL Server.</p>
<p>The <strong>principal</strong> access data. It should be authenticated by SQL Server which basically means that the principal should &#8220;prove&#8221; that it is , whom it claims to be.</p>
<p><strong>Principal</strong> is a user a group or an application granted permission to access <strong>securables</strong>.So what is a securable? <strong>Securable</strong> is an object to which access privileges are granted.</p>
<p><strong>Privilege</strong> is an action that a principal is allowed to perform an a securable.</p>
<p>Let&#8217;s look into principals in more detail. We have <strong>Window Principals</strong> that are windows user accounts or groups that are authenticated using Windows security.</p>
<p>We have <strong>SQL Server Principals</strong> are server logins or groups that are authenticated using SQL Server security.</p>
<p>We also have <strong>Database Principals</strong> that are database users,database roles (user defined roles or database fixed roles) and application roles.</p>
<p>Another very important thing you should know when configuring SQL Server to be as secure as possible is <strong>Authentication modes</strong>.</p>
<p>When installing SQL Server (at a certain step) you will be asked to specify the authentication mode and administrators for the Database Engine.</p>
<p>For all those of you, who have not installed SQL Server you will have to believe me that at a certain time during the installation process you will have to make this decision. Then again, I strongly believe that anyone working on a daily basis with SQL Server should install the product at least once.</p>
<p>We have two authentication modes.<strong>Windows Authentication</strong> <strong>Mode</strong> and<strong> Mixed Mode</strong>.<strong>Windows Authentication</strong> basically means that a user must log in to a windows domain or a windows local account first before logging into an SQL Server system.Basically a security token is created by Windows when someone logs in and this is passed to SQL Server that &#8220;validates&#8221; the account  name and password based on that token. In a sentence the user logged in the SQL Server is checked and identified by Windows.</p>
<p>SQL Server validates the account name and password using the Windows principal token in the operating system.</p>
<p><strong>Windows Authentication</strong> disables SQL Server Authentication.I have been asked if you can disable <strong>Windows Authentication</strong> and the short answer to that is <strong>NO</strong>.</p>
<p>When possible (Microsoft recommends it) use <strong>Windows Authentication</strong> only since it is inherently more secure.For example when using Active Directory you can use <strong>Group Policies</strong> which means we can enforce certain policies like &#8220;enforce users to use strong passwords&#8221; .Another very useful policy is the &#8220;Account Lockout&#8221; which locks accounts when too many failed login attempts occur.</p>
<p>We also have <strong>Mixed Authentication Mode</strong> which basically means <strong>Windows Authentication</strong> &amp; <strong>SQL Server Authentication</strong>.</p>
<p>With <strong>SQL Server Authentication</strong> mode SQL Server manages a seperate set of users and groups to give permissions to.SQL Server logins are not based on Windows accounts,usernames and passwords are created by SQL Server and also stored there.</p>
<p>If you choose to have <strong>SQL Server Authentication </strong>you would have to keep credentials for your windows domain and SQL Server.When using the <strong>SQL Server Authentication</strong> make sure you create a long <strong>sa</strong> password and hide it.</p>
<p>In any case you need to have this authentication mode enabled especially if you need to provide access to your users outside the organisation.SQL Server Authentication does not require a domain controller.</p>
<p>In order to change the Authentication mode, you should open SSMS and then through Object Explorer you select the instance of SQL Server , right-click on it and then choose <strong>Properties</strong> and then select <strong>Security</strong> tab.</p>
<p>Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/security-authentication1.jpg"><img class="aligncenter size-large wp-image-1488" title="security-authentication1" src="http://dotnetstories.files.wordpress.com/2011/10/security-authentication1.jpg?w=1024&#038;h=582" alt="" width="1024" height="582" /></a></p>
<p>The change will take effect when SQL Server is restarted.</p>
<p>Another (less secure) way to have the same effect is using the following T-SQL code.</p>
<p><pre class="brush: sql;">

USE master
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2

--Windows Authentication mode
USE master
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 1
</pre></p>
<p>Let&#8217;s move on to more hands-on examples. I think we have covered a lot of issues regarding Security in SQL Server.</p>
<p>We need an instance of SQL Server running in our machine. I have<strong> SQL Server 2008 R2 Developer</strong> edition installed in my machine.</p>
<p>In case you do not have an instance of <strong>Enterprise edition or Developer edition  of SQL Server 2008 / R2</strong>, you can download it from <a href="http://msdn.microsoft.com/en-us/evalcenter/ff459612.aspx" target="_blank">here</a> . This is a trial version.</p>
<p>1) Launch SQL Server Management Studio and connect to the local instance of SQL Server 2008/R2 Enterprise or Developer edition.</p>
<p>We need a database as well. I will use the <strong>Northwind</strong> database. If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>2)Let&#8217;s find all the server principals on this server/machine.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT * FROM sys.server_principals
</pre></p>
<p>Run the query and see the results.In my case I see the following</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/server-principals.jpg"><img class="aligncenter size-large wp-image-1491" title="server-principals" src="http://dotnetstories.files.wordpress.com/2011/10/server-principals.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>You can see the various server principals, the sid, the type of login and if it is enabled or disabled.</p>
<p>3) Now le&#8217;ts see how to create a windows login. We need to create a windows user first. <strong>Right-click</strong> on Computer icon on the desktop and then select <strong>Manage</strong>, expand <strong>Local Users and Groups</strong> and then create <strong>New User</strong>.I create a windows user named &#8220;nikolaosk&#8221;. Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/windowsuser.jpg"><img class="aligncenter size-full wp-image-1492" title="windowsuser" src="http://dotnetstories.files.wordpress.com/2011/10/windowsuser.jpg?w=460&#038;h=328" alt="" width="460" height="328" /></a></p>
<p>We need to write some T-SQL code to create a windows login from the windows user.</p>
<p><pre class="brush: sql;">

CREATE LOGIN [fofo-pc\nikolaosk] FROM WINDOWS
SELECT * FROM sys.server_principals
</pre></p>
<p>Run the query and see the results.You will see the new windows login created.</p>
<p>4) Now we will see how to create an SQL Server Login.</p>
<p><pre class="brush: sql;">

CREATE LOGIN SqlLogin WITH PASSWORD='!@#$%^&amp;1a'
SELECT * FROM sys.server_principals
</pre></p>
<p>Run the query and see the results.You will see the new SQL Login created.</p>
<p>5) Now let&#8217;s have a look on database principals. We need to create a user based on a login that we created previously on the server.</p>
<p><pre class="brush: sql;">

CREATE USER [fofo-pc\nikolaosk]
SELECT * FROM Northwind.sys.database_principals
</pre></p>
<p>Run the query and see the results.You will see the new user created. Have a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/database-user.jpg"><img class="aligncenter size-large wp-image-1493" title="database-user" src="http://dotnetstories.files.wordpress.com/2011/10/database-user.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>6) Now let&#8217;s have a look on the <strong>sids</strong> for the user and login &#8216;fofo-pc\nikolaosk&#8217;</p>
<p><pre class="brush: sql;">

SELECT sid FROM Northwind.sys.database_principals WHERE name ='fofo-pc\nikolaosk'

--0x01050000000000051500000020C72D8DC8F347F7A0A346D31F040000

SELECT sid FROM sys.server_principals WHERE name ='fofo-pc\nikolaosk'

--0x01050000000000051500000020C72D8DC8F347F7A0A346D31F040000
</pre></p>
<p>Run the query and see the results. You will see that the sids are the same. I am sure you can see now how the user and the login is linked.</p>
<p>7) Now let&#8217;s create another user based on that windows login.But this time we will use an alias-different name and not the previous name [fofo-pc\nikolaosk]</p>
<p><pre class="brush: sql;">

USE Northwing
GO

DROP USER [fofo-pc\nikolaosk]

CREATE USER nikolaosk FROM login [fofo-pc\nikolaosk]

SELECT * FROM Northwind.sys.database_principals

</pre></p>
<p>Run the query and see the results.Now you have your new database user.</p>
<p>8) Now let&#8217;s create another user for the <strong>Northwind</strong> database that is not based on a login. You can also do that.Then I just delete this user.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE USER withoutlogin WITHOUT LOGIN
go

DROP USER withoutlogin
go

</pre></p>
<p>Run the query and see the results.</p>
<p>9) Now let&#8217;s create a user defined database role. It is another entry <strong>sys.database_principals</strong></p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE ROLE myrole
SELECT * FROM Northwind.sys.database_principals

</pre></p>
<p>Run the query and see the results.Now you have a new role.</p>
<p>Now that we know how to create server and database principals,let&#8217;s see how to authorise those principals to actually use SQL Server.</p>
<p>You must understand that Authorisation in SQL Server is a very fine-grained process. That means I can say for example</p>
<ul>
<li>Nikos (a windows login principal) can do anything on the server.</li>
<li>Nikos (a windows login principal) can do anything on a database.</li>
<li>Nikos (a windows login principal) can use &#8220;SELECT&#8221; statements on 5 tables in the database.</li>
<li>Nikos (a windows login principal) can use &#8220;SELECT&#8221; statement on only one table of the database.</li>
</ul>
<p>So a <strong>permission</strong> is applied on <strong>object</strong> to a <strong>Principal</strong>.</p>
<p>10) Now that we will create a new windows user (as in step 3) and then create a login from that user. Then we will create a database user based on that login.So we create a windows user called &#8220;jane&#8221;.</p>
<p>Run the code below to create a login and a user based on that login.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE LOGIN [fofo-pc\jane] FROM WINDOWS

CREATE USER jane FROM login [fofo-pc\jane]

</pre></p>
<p>If you want to use Windows Authentication in the Microsoft SQL Server Management Studio to connect to a Microsoft SQL Server in an other domain or with an other username (&#8220;jane&#8221; in this case), you can use the RUN AS command in Windows. Just open a command prompt window and type:</p>
<p><strong>runas  /user:jane &#8220;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe&#8221;</strong></p>
<p>You will be prompted for the password.After you type the password, a new SSMS instance will launch as user &#8220;jane&#8221;. Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/ssms-jan.jpg"><img class="aligncenter size-large wp-image-1499" title="ssms-jan" src="http://dotnetstories.files.wordpress.com/2011/10/ssms-jan.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>11) In the new query window (you are always logged in as Jane) try to do something in the <strong>Northwind</strong> database, like select from a table or a view. Try to create a new database. You will fail.That is because the user-jane is authenticated but has no permissions / not authorised to do anything.If you want to check out what you can do as a user connected to an SQL Server instance (at the server level) type the following.</p>
<p><pre class="brush: sql;">

SELECT * FROM sys.fn_my_permissions(NULL,'server')

</pre></p>
<div style="margin-top:0;margin-bottom:0;margin-left:.48in;text-indent:-.35in;text-align:left;direction:ltr;unicode-bidi:embed;">In my case when I execute the T-sql command above I get the following:</div>
<div style="margin-top:0;margin-bottom:0;margin-left:.48in;text-indent:-.35in;text-align:left;direction:ltr;unicode-bidi:embed;"><strong>entity_name </strong>  <strong> subentity_name </strong>   <strong>permission_name</strong></div>
<div style="margin-top:0;margin-bottom:0;margin-left:.48in;text-indent:-.35in;text-align:left;direction:ltr;unicode-bidi:embed;"> server                                                                      CONNECT SQL</div>
<div style="margin-top:0;margin-bottom:0;margin-left:.48in;text-indent:-.35in;text-align:left;direction:ltr;unicode-bidi:embed;"> server                                                                    VIEW ANY DATABASE</div>
<p>As it was expected, the only &#8220;permission&#8221; I have as user <strong>jane</strong> is basically to connect to SQL Server and view the databases.</p>
<p>12) Now let&#8217;s move back to the SSMS (the one instance that I run as admin) and let&#8217;s give user &#8220;jane&#8221; some permissions.This is how I do it. I use the &#8220;GRANT&#8221; T-SQL statement.</p>
<p><pre class="brush: sql;">

GRANT CONTROL SERVER TO [fofo-pc\jane]

</pre></p>
<p>In a command prompt type again</p>
<p><strong>runas  /user:jane &#8220;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe&#8221; </strong></p>
<p>Then type the password.<strong><br />
</strong></p>
<p>In the new<strong></strong> SSMS application (running as jane), in a new query  window type again</p>
<p><pre class="brush: sql;">

SELECT * FROM sys.fn_my_permissions(NULL,'server')

</pre></p>
<p>When you execute the query you will get similar results like the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/fn_my_permissions.jpg"><img class="aligncenter size-large wp-image-1504" title="fn_my_permissions" src="http://dotnetstories.files.wordpress.com/2011/10/fn_my_permissions.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>So we can see that we can have a simple windows user/jane that is not a member of the Windows Admin Group, but at the same time is &#8220;almost&#8221; a server admin in the SQL Server instance.</p>
<p>13) Managing permissions on individual principals can be difficult and not practical.<strong>Windows</strong> <strong>group/database role</strong> is a principal.It is much easier to manage users in group roles.However a user can belong to one or more roles. Those roles can have different permissions set on the user.Sometimes these permissionsa can be conflicting.Try to avoid that.</p>
<p>Now le&#8217;ts see how to create a windows user ( as in step 3). We need to create a windows user first. <strong>Right-click</strong> on Computer icon on the desktop and then select <strong>Manage</strong>, expand <strong>Local Users and Groups</strong> and then create <strong>New User</strong>. Create 2 new users, <strong>Aidan</strong> and <strong>Ale</strong>.Create the logins and users.</p>
<p><pre class="brush: sql;">
USE Northwind
go

CREATE LOGIN [fofo-pc\Ale] FROM WINDOWS

CREATE USER Ale FROM LOGIN [fofo-pc\Ale]

CREATE LOGIN [fofo-pc\Aidan] FROM WINDOWS

CREATE USER Aidan FROM LOGIN [fofo-pc\Aidan]

</pre></p>
<p>Le&#8217;ts see how to create a windows group. We need to create a windows user first. <strong>Right-click</strong> on Computer icon on the desktop and then select <strong>Manage</strong>, expand <strong>Local Users and Groups</strong> and then click on <strong>Groups</strong>. Create a new <strong>Group</strong> and name it <strong>ITPeople</strong>. Add the users <strong>Aidan</strong> and <strong>Ale</strong> as members of that group.</p>
<p>Now let&#8217;s create a login for the windows group(we are logged in as sysadmin).After that we will create a user for that login.Execute the following query.</p>
<p><pre class="brush: sql;">
USE Northwind
go

CREATE LOGIN [fofo-pc\ITPeople] FROM WINDOWS

CREATE USER ITPeople FROM LOGIN [fofo-pc\ITPeople]

SELECT * FROM sys.database_principals

</pre></p>
<p>Now we want to grant <strong>SELECT</strong> permissions on the table <strong>Categories</strong> of the <strong>Northwind</strong>database, to everyone who is a member of ITPeople principal. That means Ale and Aidan since they are members of that principal can also use &#8220;Select&#8221; statements.</p>
<p><pre class="brush: sql;">
USE Northwind
go

GRANT SELECT ON OBJECT::dbo.Categories TO ITPeople

</pre></p>
<p>Now let&#8217;s find out if they indeed have the &#8220;Select&#8221; permission on the Categories table.</p>
<p><pre class="brush: sql;">
USE Northwind
go

SETUSER 'Aidan'

SELECT * FROM dbo.Categories

SETUSER

SETUSER 'Ale'

SELECT * FROM dbo.Categories
SETUSER

</pre></p>
<p>Run the query above and you will see that you will succeed. I use the <strong>SETUSER</strong>  statement which allows a member of the <strong>sysadmin</strong> fixed server role or <strong>db_owner</strong> fixed database role to impersonate another user.</p>
<p>14) Now let&#8217;s create a database role.This is the same as window groups more or less. That means that we have a database role. We give permissions to that role and then all the users/members of that role inherit those permission.In the following T-SQL statements, I create a role, I add <strong>Ale</strong> and <strong>Aidan</strong> on this role and grant on this role permissions to do &#8220;Insert&#8221; statements on the <strong>Categories</strong> table.</p>
<p><pre class="brush: sql;">

USE Northwind
go

CREATE ROLE myrole

sp_addrolemember 'myrole','Ale'

sp_addrolemember 'myrole','Aidan'

GRANT INSERT ON OBJECT::dbo.Categories TO myrole

</pre></p>
<p>Execute the query above and see the results.</p>
<p>Now let&#8217;s find out if the users <strong>Ale</strong> and <strong>Aidan</strong> of the <strong>myrole</strong> group can indeed perform <strong>INSERT</strong> statements on the <strong>Categories</strong> table.</p>
<p><pre class="brush: sql;">

USE Northwind
go

SETUSER 'Ale'

INSERT INTO dbo.Categories
( CategoryName ,
Description ,
Picture
)
VALUES  ( N'Myfood' , -- CategoryName - nvarchar(15)
NULL , -- Description - ntext
NULL  -- Picture - image
)

SETUSER

SETUSER 'Aidan'

INSERT INTO dbo.Categories
( CategoryName ,
Description ,
Picture
)
VALUES  ( N'Mynicefood' , -- CategoryName - nvarchar(15)
NULL , -- Description - ntext
NULL  -- Picture - image
)

SETUSER

</pre></p>
<p>If you run the statements above you will succeed. That means <strong>Ale</strong> and <strong>Aidan</strong> are members of this role (myrole) and they have <strong>INSERT</strong> permissions on <strong>Categories</strong> table. They are also members of the ITPeople (windows group) and they have <strong>SELECT</strong> permissions on <strong>Categories</strong> table.</p>
<p>15) Let&#8217;s move on with our security examples and see how we can use <strong>Schemas</strong> in our security context. Schemas is a set of database objects and it the third element when naming fully a database object e.g <strong>MyServer.MyDB.MySchema.MyTable</strong>.A schema is a container of objects in a database and it is similar to a <strong>namespace in c#</strong><br />
Every object (table,view) belongs to only one schema. Have a look here for more information on <a href="http://en.wikipedia.org/wiki/Database_schema" target="_blank">schemas</a>.</p>
<p>Let&#8217;s create a schema and its relevant objects.Execute the code below to create the schema and the two tables.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE SCHEMA football

CREATE TABLE footballer
(
id INT PRIMARY KEY,
NAME VARCHAR(50),
AGE INT

)

CREATE TABLE FootballTeam
(
fid INT PRIMARY KEY,
NAME VARCHAR(50),
DATEFOUNDED DATE
)

</pre></p>
<p>Now le&#8217;ts create 2 more windows users (as in step 3).  <strong>Right-click</strong> on Computer icon on the desktop and then select <strong>Manage</strong>, expand <strong>Local Users and Groups</strong> and then create <strong>New User</strong>. Create 2 new users, <strong>Michael</strong> and <strong>Steven</strong>.Create the logins and users.</p>
<p><pre class="brush: sql;">

USE Northwind
go

CREATE LOGIN [fofo-pc\Michael] FROM WINDOWS

CREATE USER Michael FROM LOGIN [fofo-pc\Michael]

CREATE LOGIN [fofo-pc\Steven] FROM WINDOWS

CREATE USER Steven FROM LOGIN [fofo-pc\Steven]

</pre></p>
<p>Now, let&#8217;s assume that we want the user <strong>Steven</strong> to have <strong>SELECT</strong> permissions on the schema.I am sure you are beginning to realise what schemas offer us when it comes to security. Imagine that we have 20 tables in a database. Imagine that we wanted to grant <strong>SELECT</strong> permissions on 18 of them to a particular principal. We had to do it sepereately (different T-SQL statements) for each table.By using schemas, we could grant <strong>SELECT</strong> on the schema (all 20 tables belong to one schema) to the user and then <strong>DENY SELECT</strong> for those 2 tables for the user.</p>
<p>In my case I can grant <strong>SELECT</strong> permissions on the schema (football) for that particular principal(Steven).</p>
<p>Execute the code below(lines 1-9 first). You will see that  I grant the permissions for the schema to the user (line1)  and then impersonate that user(line 3).</p>
<p>Then I check that indeed I am the user <strong>Steven</strong> (line 5).</p>
<p>Then I use the <strong>SELECT</strong> statement on both tables of the schema (lines 7 &amp; 9)</p>
<p>That will succeed.</p>
<p>Now execute lines (13 to 25). In line 13 I revert to the use <strong>dbo</strong>. Then I impersonate the user <strong>Michael</strong> (line 17) and then I I use the <strong>SELECT</strong> statement on both tables of the schema (lines 22 and 25).</p>
<p>That will fail, since <strong>Michael</strong> has no permissions on the schema.</p>
<p><pre class="brush: sql;">

GRANT SELECT ON SCHEMA::football TO Steven

EXECUTE AS USER = 'Steven'

SELECT USER

SELECT * FROM football.footballer

SELECT * FROM football.FootballTeam

-- this will revert to the dbo user

REVERT

SELECT USER

EXECUTE AS USER ='Michael'

--check indeed that I am user Michael
SELECT USER

--this will fail
SELECT * FROM football.footballer

SELECT * FROM football.FootballTeam

</pre></p>
<p>16) Let&#8217;s see some examples on security and fixed server roles/database roles. A <strong>role</strong> has permissions for particular kind of tasks. Principal assumes of role they are assigned to. There are several fixed server roles that each one has permissions to perform server related tasks.Later on we will look into database roles. Please note that we cannot create server roles but we can create user defined database roles.</p>
<p>Execute the code below.You will see what the fixed server roles are and what kind of permissions are attached to the &#8220;serveradmin&#8221; and &#8220;dbcreator&#8221; fixed server roles.</p>
<p><pre class="brush: sql;">

sp_HELPSRVROLE

SP_SRVROLEPERMISSION 'serveradmin'

SP_SRVROLEPERMISSION 'dbcreator'

</pre></p>
<p>We can add a login to a fixed server role.We had two logins created previously.Let&#8217;s add <strong>Michael</strong> to the <strong>sysadmin</strong> fixed server role.</p>
<p><pre class="brush: sql;">

--find out what are the principals that are members of the sysadmin role.
sp_helpsrvrolemember 'sysadmin'

--Add Michael to the sysadmin role

sp_addsrvrolemember 'fofo-pc\Michael','sysadmin'

</pre></p>
<p>Let&#8217;s test that <strong>Michael</strong> is indeed added to the <strong>sysadmin</strong> fixed server role.</p>
<p>In a command prompt type</p>
<p><strong>runas  /user:michael &#8220;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe&#8221; </strong></p>
<p>Then type the password. That will launch a new instance of the SSMS window. In the new query window, type</p>
<p><pre class="brush: sql;">

SELECT * FROM sys.fn_my_permissions(NULL,'server')

</pre></p>
<p>You will see beyond doubt that Michael is a member of the <strong>sysadmin</strong> role.Close SSMS ( the one logged in as Michael) and switch back to the other instance of SSMS running.<strong></strong></p>
<p>Now, you may want to drop <strong>Michael</strong> from the <strong>sysadmin</strong> role.Execute the code below.</p>
<p><pre class="brush: sql;">

sp_dropsrvrolemember 'fofo-pc\Michael','sysadmin'

</pre></p>
<p>17) We will look into fixed database roles and user defined database roles. Now we want to add <strong>Michael</strong> to a fixed database role. Please note that <strong>Michael</strong> is also a user in the database Northwind, and not just a login. <strong></strong></p>
<p>We find out first what the fixed database roles are. Then we find out that <strong>Michael</strong> does not have <strong>SELECT</strong> permissions on any table of the database.</p>
<p>We add <strong>Michael</strong> to the fixed role of <strong>db_datareader </strong>and try again to select data from the tables of the database. This time we are successful.Members of the <em>db_datareader</em> fixed database role can run a <strong>SELECT</strong> statement against any table or view in the database.</p>
<p>Execute the code below.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT * FROM Northwind.sys.database_principals

-- what the db fixed roles are

sp_helpdbfixedrole

--impersonate the user Michael

EXECUTE AS USER ='Michael'

SELECT USER

--this will fail

SELECT * FROM dbo.Categories

--this will fail

SELECT * FROM dbo.Shippers

--revert back to sysadmin so I can add Michael to the db_datareader role
REVERT

--add Michael to the db_datareader role

sp_addrolemember 'db_datareader','Michael'

--impersonate the user Michael

EXECUTE AS USER ='Michael'

SELECT USER

--this will succeed

SELECT * FROM dbo.Categories

--this will succeed

SELECT * FROM dbo.Shippers

--this will succeed
SELECT * FROM football.footballer

</pre></p>
<p>Now we want to restrict user <strong>Michael  </strong>from selecting (tables &amp; views) belonging to the <strong>football</strong> schema in the <strong>Northwind</strong> database.Execute the code below.</p>
<p><pre class="brush: sql;">

--this will fail

DENY SELECT ON SCHEMA::football TO db_datareader

</pre></p>
<p>This will fail. We cannot deny permissions from a fixed database server role. What we can do is deny permissions on the schema to the particular user.Execute the code below.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

DENY SELECT ON SCHEMA::football TO Michael

EXECUTE AS USER ='Michael'

SELECT USER

--this will now fail
SELECT * FROM football.footballer

</pre></p>
<p>Finally we will drop <strong>Michael</strong> from the fixed database role <strong>db_datareader.</strong>Execute the code below.<strong><br />
</strong></p>
<p><pre class="brush: sql;">

USE Northwind

go

sp_droprolemember 'db_datareader','Michael'

EXECUTE AS USER ='Michael'

SELECT USER

--this will fail

SELECT * FROM dbo.Categories

--this will fail

SELECT * FROM dbo.Shippers

--this will fail
SELECT * FROM football.footballer

</pre></p>
<p>Now <strong>Michael</strong> does not have any SELECT permissions on the tables/views of the <strong>Northwind</strong> database.</p>
<p>18) Now we will add  a new user  to a user defined database role. <strong>Right-click</strong> on Computer icon on the desktop and then select <strong>Manage</strong>, expand <strong>Local Users and Groups</strong> and then create <strong>New User</strong>. Create ne new users, <strong>Meryl</strong><strong></strong>.Create the login and user.Execute the code below.</p>
<p><pre class="brush: sql;">

USE Northwind
go

CREATE LOGIN [fofo-pc\Meryl] FROM WINDOWS

CREATE USER Meryl FROM LOGIN [fofo-pc\Meryl]

</pre></p>
<p>Obviously we could assign <strong>SELECT</strong> permissions to the schema <strong>football</strong>  to user <strong>Meryl</strong> ( as we did in another example previously) but this time we want to do it through a user defined database role.Execute the code below.I create a role and assign to it <strong>SELECT</strong> permissions on the <strong>football</strong> schema.Execute the code below. I check to see that <strong>Meryl</strong> does not have <strong>SELECT</strong> permissions on the schema.Then I create a role and give permissions to that role. Then I add <strong>Meryl</strong> to that role. <strong>Meryl</strong> assumes the permissions of that role.Then I run the <strong>SELECT</strong> statements again against the two tables that belong to the <strong>football</strong> schema.</p>
<p><pre class="brush: sql;">

USE Northwind
go

EXECUTE AS USER ='Meryl'

SELECT USER

--this will fail

SELECT * FROM football.footballer

--this will fail

SELECT * FROM football.footballteam

--revert to dbo

REVERT

--create role

CREATE ROLE football_reader

--grant permissions on role
GRANT SELECT ON SCHEMA::football TO football_reader

--add user to the role
sp_addrolemember 'football_reader','Meryl'

EXECUTE AS USER ='Meryl'

SELECT USER

--this will succeed

SELECT * FROM football.footballer

--this will succeed

SELECT * FROM football.footballteam

</pre></p>
<p>19)Ιn this example I would like to talk a bit about conflicting permissions.What happens when a user is in a role (like <strong>Meryl</strong> above) that has <strong>SELECT</strong> rights on the schema <strong>football</strong> and at the same time is a  member of another role that has no <strong>SELECT</strong> rights on that schema? We have a conflict. We will execute the code below and we will find out.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE ROLE no_football_reader

--deny permissions on role

DENY SELECT ON SCHEMA::football TO no_football_reader

--add user to the role
sp_addrolemember 'no_football_reader','Meryl'

EXECUTE AS USER ='Meryl'

SELECT USER

--this will fail

SELECT * FROM football.footballer

--this will fail

SELECT * FROM football.footballteam

</pre></p>
<p>As you will find out when you execute the code, the user <strong>Meryl</strong> cannot perform <strong>SELECT</strong> statements on the schema <strong>football</strong>.So <strong>DENY</strong> overwrites\takes precedence over the <strong>GRANT</strong> statement.</p>
<p>In all these samples I have adopted the T-SQL approach. You could do all the above with the GUI of SSMS.</p>
<p>Remember your system is as secure as your weakest component.Also keep in mind that threats are broad and varied.<br />
I do not want to say that everyone is your enemy but sometimes it helps to think pessimistically.<br />
That is all folks.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/authentication/'>Authentication</a>, <a href='https://dotnetstories.wordpress.com/tag/authentication-mode/'>Authentication mode</a>, <a href='https://dotnetstories.wordpress.com/tag/authorisation/'>Authorisation</a>, <a href='https://dotnetstories.wordpress.com/tag/denial-of-service/'>Denial of Service</a>, <a href='https://dotnetstories.wordpress.com/tag/elevation-of-privilege/'>Elevation of Privilege</a>, <a href='https://dotnetstories.wordpress.com/tag/information-disclosure/'>Information disclosure</a>, <a href='https://dotnetstories.wordpress.com/tag/mixed-mode/'>Mixed Mode</a>, <a href='https://dotnetstories.wordpress.com/tag/principal/'>principal</a>, <a href='https://dotnetstories.wordpress.com/tag/privilege/'>Privilege</a>, <a href='https://dotnetstories.wordpress.com/tag/repudiation/'>Repudiation</a>, <a href='https://dotnetstories.wordpress.com/tag/securable/'>securable</a>, <a href='https://dotnetstories.wordpress.com/tag/spoofing-identity/'>Spoofing identity</a>, <a href='https://dotnetstories.wordpress.com/tag/tampering/'>Tampering</a>, <a href='https://dotnetstories.wordpress.com/tag/windows-authentication-mode/'>Windows Authentication Mode</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1477/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1477&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/10/17/looking-into-security-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/sqlserverconfiguration.jpg?w=1024" medium="image">
			<media:title type="html">sqlserverconfiguration</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/security-authentication1.jpg?w=1024" medium="image">
			<media:title type="html">security-authentication1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/server-principals.jpg?w=1024" medium="image">
			<media:title type="html">server-principals</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/windowsuser.jpg" medium="image">
			<media:title type="html">windowsuser</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/database-user.jpg?w=1024" medium="image">
			<media:title type="html">database-user</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/ssms-jan.jpg?w=1024" medium="image">
			<media:title type="html">ssms-jan</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/fn_my_permissions.jpg?w=1024" medium="image">
			<media:title type="html">fn_my_permissions</media:title>
		</media:content>
	</item>
		<item>
		<title>Performing Auditing in SQL Server environments</title>
		<link>https://dotnetstories.wordpress.com/2011/10/13/performing-auditing-in-sql-server-environments/</link>
		<comments>https://dotnetstories.wordpress.com/2011/10/13/performing-auditing-in-sql-server-environments/#comments</comments>
		<pubDate>Thu, 13 Oct 2011 01:42:54 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[Database Audit Specification]]></category>
		<category><![CDATA[Server Audit Specification]]></category>
		<category><![CDATA[SQL Server Audit]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1416</guid>
		<description><![CDATA[In this post I would like to talk about SQL Server Audit. This new way of auditing was introduced with SQL Server 2008.This feature is supported in SQL Server 2008 Enterprise edition.Auditing is simply the process of monitoring and tracking changes to the SQL Server system.All the DBAs need to implement auditing at some point to satisfy business requirements. There is something called  "SQL Server Extended Events" engine.The extended events engine allows any process to define and raise events and consumers to receive events.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1416&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about <strong>SQL Server Audit</strong>. This new way of auditing was introduced with <strong>SQL Server 2008</strong>.This feature is supported in<strong> SQL Server 2008 Enterprise</strong> <strong>edition</strong>.Auditing is simply the process of monitoring and tracking changes to the SQL Server system.All the DBAs need to implement auditing at some point to satisfy business requirements. There is something called  &#8220;<strong>SQL Server Extended Events</strong>&#8221; engine.The extended events engine allows any process to define and raise events and consumers to receive events.This engine is in the heart of <strong>SQL Server Audits</strong>.</p>
<p>Some of the advantages of <strong>SQL Server Audit</strong> over the other auditing techniques available to us(I am going to mention some of them later on) are the fact that you can perform audits at the server and database levels.We can define audits for different activities at the same time and capture activity generated from a variety of SQL Statements like select,insert,update,delete,execute.As with so many activities in SQL Server you can set up and administer SQL Server Audit using SSMS.</p>
<p>There are some limitations as well when using SQL Server Audit.As with anything in SQL Server everything takes up resources.If you decide to have a very detailed auditing then more resources are used. So one thing to keep in mind is not to use <strong>SQL Server Audit</strong> in servers where there are heavy workloads and are experiencing bottlenecks. Or if you are adamant about using them then use them carefully.One other thing to keep in mind is that SQL Server Audit is instance based.So you will have to set it up on every instance. The data is stored in the event logs or some file. If you need to have further analysis on them you should import them on some tables in a database.</p>
<p>SQL Server Audits are comprised of Audits,Server and Database Audit specifications,actions and action groups and targets.</p>
<p>There are some other alternatives that we can use in order to perform auditing to our SQL Server instance. I am going to talk about them briefly.</p>
<p>We can use C2 Audit mode.It configures SQL Server to record attempts to access statements and objects.</p>
<p>C2 audit mode can still be configured in SQL Server but is now rarely used. It has a negative performance impact through the generation of large volumes of event information.</p>
<p>When you set this option you should be prepared to run out of disk space.If this happens SQL Server will shut itself down.That is why I think it is imperative for everyone to check through jobs and alerts the remaining disk space where our databases live.You can turn on C2 Audit mode through SSMS. Just select the instance of SQL Server from the <em>Object Explorer</em> right-click and select <strong>Properties</strong>. Then choose <strong>Security</strong>.</p>
<p>Have a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/c2audit.jpg"><img class="aligncenter size-full wp-image-1417" title="c2audit" src="http://dotnetstories.files.wordpress.com/2011/10/c2audit.jpg?w=460&#038;h=412" alt="" width="460" height="412" /></a></p>
<p>We can turn C2 audit through T-SQL as well.</p>
<p><pre class="brush: sql;">

sp_configure 'show advanced options', 1 ;
GO
RECONFIGURE ;
GO
sp_configure 'c2 audit mode', 1 ;
GO
RECONFIGURE ;
GO

</pre></p>
<p>We could also use triggers for auditing.I have blogged about triggers in this <a href="http://dotnetstories.wordpress.com/2011/10/02/looking-into-triggers-in-sql-server/">post</a>. We can have DML triggers for data modification and Logon triggers for tracking logons.There are some limitations using triggers like performance issues, the ability to disable triggers e.t.c</p>
<p>One of my favourite tools in the SQL Server ecosystem is SQL Server Profiler.We can use SQL Server profiler to trace commands sent to the server.</p>
<p>The basic process in order to create an SQL Server Audit is the following:</p>
<p>We need to define a SQL Server Audit Package and define a destination for the output.</p>
<p>Then we need to define a Server Audit Specification and a Database Audit Specification.</p>
<p>Then we need to enable the Audit. Finally we need to analyse the captured audit events.We can view the audit using the <strong>Windows Event Viewer</strong>, the <strong>Log File Viewer</strong> or by using the <a href="http://msdn.microsoft.com/en-us/library/cc280765.aspx" target="_blank"><strong>fn_get_audit_file</strong></a> function.</p>
<p>A server audit specification determines which server level events shoud be included in the audit.Server audit specification are defined at the SQL Server instance level.We will use it to see who is logging in or out from our server,logins that are dropped and added to fixed server roles and backups/restores that are performed.</p>
<p>A database audit specification works like the server audit specification but at the database level.We will use it when we want to know who is selecting,inserting,updating data in a table in a database.</p>
<p>Have a look at this <a href="http://technet.microsoft.com/en-us/library/cc280663.aspx" target="_blank">link</a> for a complete list of <strong>Server-Level Audit Action Groups</strong> and  <strong>Database-Level Audit Action Groups</strong></p>
<p>Let&#8217;s see all that with a hands on example.</p>
<p>In case you do not have an instance of <strong>Enterprise edition or Developer edition  of SQL Server 2008 / R2</strong>, you can download it from <a href="http://msdn.microsoft.com/en-us/evalcenter/ff459612.aspx" target="_blank">here</a> . This is a trial version.</p>
<p>We need a database as well. I will use the <strong>Northwind</strong> database.</p>
<p>If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>1) Launch SQL Server Management Studio and connect to the local instance of SQL Server 2008/R2 Enterprise or Developer edition.</p>
<p>2) We need  to create a new audit object. Through <strong>SSMS</strong>, we open  &#8220;Security,&#8221; and you will see the &#8220;Audits&#8221; folder and then choose the &#8220;New Audit &#8221; option, as shown in the picture below.Now we need so specify the details of the <strong>Audit</strong>.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/serveraudit1.jpg"><img class="aligncenter size-large wp-image-1456" title="serveraudit1" src="http://dotnetstories.files.wordpress.com/2011/10/serveraudit1.jpg?w=1024&#038;h=577" alt="" width="1024" height="577" /></a></p>
<p>The first thing I need to do is to assign an audit name. Then I specify a  &#8220;Queue Delay&#8221; number. This is the delay expressed as an amount of time after an audit<br />
event has occurred and before it is written to the log. The default value is 1000 milliseconds.</p>
<p>Then I have the option of  &#8220;Shut down server on audit log failure&#8221;. By selecting this option and for whatever reason the audit data can&#8217;t be logged, SQL Server will not start, unless you manually start it.Then we have to choose the option where to store the audit data. I am going to choose &#8220;Application Log&#8221; and then click &#8220;OK&#8221;.</p>
<p>Then I will create the <strong>server audit specification</strong>.We have to choose from the Object Explorer , <strong>Security</strong> &#8211;&gt; <strong>Server Audit Specifications</strong> &#8211;&gt; <strong>New Server Audit Specification</strong>.Then I need to choose a name for the <strong>Server Audit</strong> and &#8220;link&#8221; it to the audit object previously created, namely &#8220;MyServerAudit&#8221;.Then I choose the <strong>Audit Actions</strong>.In this example I am interested in</p>
<ul>
<li>FAILED_LOGIN_GROUP</li>
<li>SERVER_ROLE_MEMBER_CHANGE_GROUP</li>
<li>BACKUP_RESTORE_GROUP</li>
</ul>
<p>I will not go into details because these are self-explanatory.After I do that I just click &#8220;OK&#8221; to close the window. Then I select the server audit specification I created &#8220;MyServerAuditSpecification&#8221;, I right-click on it and then enable it.</p>
<p>Have a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/serveraudit2.jpg"><img class="aligncenter size-large wp-image-1460" title="serveraudit2" src="http://dotnetstories.files.wordpress.com/2011/10/serveraudit2.jpg?w=1024&#038;h=575" alt="" width="1024" height="575" /></a></p>
<p>Now we can create an audit specification for the Northwind database.We do that by using again SSMS and the Object Explorer to open up the database to be audited. Then we open up the security folder under it. Next, right-click on &#8220;Database Audit Specifications&#8221; and select &#8220;New<br />
Database Audit Specification&#8221;.The &#8220;Create Database Audit Specification&#8221; dialog box appears.We can define a name for the audit. I named it &#8220;MyDatabaseAuditSpecification&#8221;.</p>
<p>Then we select the appropriate audit object from the Audit dropdown box. In my case is &#8220;MyServerAudit&#8221;.Then we need to define the kind of audit activity we want to capture by selecting from the &#8220;AuditAction Type&#8221; drop-down box.In the <strong>Actions list</strong> I will choose to audit (INSERT,SELECT,UPDATE) of the <strong>Categories</strong> table of the <strong>Northwind</strong> table.I will choose these actions from the <strong>Audit Action Type</strong> dropdown and then choose the <strong>Object Class</strong> (OBJECT) and then the <strong>Object Name</strong> (Categories) and the <strong>Principal Name</strong> (dbo). Then I click &#8220;OK&#8221; to close the window.Then I need to enable my audit specification.</p>
<p>Have a look at the picture below to see all the settings we need to set.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/audit.jpg"><img class="aligncenter size-large wp-image-1464" title="audit" src="http://dotnetstories.files.wordpress.com/2011/10/audit.jpg?w=1024&#038;h=572" alt="" width="1024" height="572" /></a></p>
<p>Now let&#8217;s test the audits. We will have to write some T-SQL statements.We will write some T-SQL statements to test the Server Audit specification.</p>
<p>The events I have specified in the <strong>Audit</strong> are</p>
<p>FAILED_LOGIN_GROUP &#8211; Indicates that a principal tried to log on to SQL Server and failed</p>
<p>SERVER_ROLE_MEMBER_CHANGE_GROUP &#8211; This event is raised whenever a login is added or removed from a fixed server role.</p>
<p>BACKUP_RESTORE_GROUP &#8211; This event is raised whenever a backup or restore command is issued</p>
<p><pre class="brush: sql;">
--I create the login and then try to log on to the server as the new user but intentionally typing the wrong password

CREATE LOGIN myuser WITH PASSWORD ='password'

--see what logins are members of the sysadmin role

sp_helpsrvrolemember 'sysadmin'

--add myuser login to the sysadmin fixed server role

sp_addsrvrolemember 'myuser','sysadmin'

-- drop the user to the sysadmin fixed server role

sp_dropsrvrolemember 'myuser','sysadmin'

--perform a full backup of the Northwind database
BACKUP DATABASE [Northwind] TO
DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\Northwind.bak' WITH NOFORMAT,
NOINIT,  NAME = N'Northwind-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO
</pre></p>
<p>Let&#8217;s open the &#8220;Application Log FileViewer&#8221; by selecting &#8220;Computer&#8221; icon from the desktop and right-click choose &#8220;Manage&#8221; and then choose &#8220;Event Viewer&#8221; &#8211;&gt; &#8220;Window Logs&#8221;  &#8211;&gt; Application.</p>
<p>Have a look the picture below that shows that the full backup operation audited.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/backup.jpg"><img class="aligncenter size-large wp-image-1466" title="backup" src="http://dotnetstories.files.wordpress.com/2011/10/backup.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Have a look the picture below that shows that the failed login operations audited.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/login.jpg"><img class="aligncenter size-large wp-image-1467" title="login" src="http://dotnetstories.files.wordpress.com/2011/10/login.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Have a look the picture below that shows that adding/dropping a login to a fixed server role operations were audited.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/drop.jpg"><img class="aligncenter size-large wp-image-1468" title="drop" src="http://dotnetstories.files.wordpress.com/2011/10/drop.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>Now we will move on to test the database audits.We need to write Insert,Update,Select statements for the <strong>Categories</strong> table of the <strong>Northwind</strong> database.</p>
<p><pre class="brush: sql;">
USE Northwind
go

SELECT * FROM dbo.Categories

UPDATE dbo.Categories
SET CategoryName = 'Drinks'
WHERE CategoryID=1

INSERT INTO dbo.Categories

VALUES (9,'General food','Bread,cheese,meat')
</pre></p>
<p>In this picture below the INSERT statement is audited.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/insert.jpg"><img class="aligncenter size-large wp-image-1469" title="insert" src="http://dotnetstories.files.wordpress.com/2011/10/insert.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>In this picture below the SELECT statement is audited.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/select.jpg"><img class="aligncenter size-large wp-image-1470" title="select" src="http://dotnetstories.files.wordpress.com/2011/10/select.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>In this picture below the UPDATE statement is audited.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/update.jpg"><img class="aligncenter size-large wp-image-1471" title="update" src="http://dotnetstories.files.wordpress.com/2011/10/update.jpg?w=1024&#038;h=550" alt="" width="1024" height="550" /></a></p>
<p>That is all folks!!!I hope you appreciated the power of <strong>SQL Server Audits</strong>.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/database-audit-specification/'>Database Audit Specification</a>, <a href='https://dotnetstories.wordpress.com/tag/server-audit-specification/'>Server Audit Specification</a>, <a href='https://dotnetstories.wordpress.com/tag/sql-server-audit/'>SQL Server Audit</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1416/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1416/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1416/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1416&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/10/13/performing-auditing-in-sql-server-environments/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/c2audit.jpg" medium="image">
			<media:title type="html">c2audit</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/serveraudit1.jpg?w=1024" medium="image">
			<media:title type="html">serveraudit1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/serveraudit2.jpg?w=1024" medium="image">
			<media:title type="html">serveraudit2</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/audit.jpg?w=1024" medium="image">
			<media:title type="html">audit</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/backup.jpg?w=1024" medium="image">
			<media:title type="html">backup</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/login.jpg?w=1024" medium="image">
			<media:title type="html">login</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/drop.jpg?w=1024" medium="image">
			<media:title type="html">drop</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/insert.jpg?w=1024" medium="image">
			<media:title type="html">insert</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/select.jpg?w=1024" medium="image">
			<media:title type="html">select</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/update.jpg?w=1024" medium="image">
			<media:title type="html">update</media:title>
		</media:content>
	</item>
		<item>
		<title>Data compression features in SQL Server 2008</title>
		<link>https://dotnetstories.wordpress.com/2011/10/10/data-compression-features-in-sql-server-2008/</link>
		<comments>https://dotnetstories.wordpress.com/2011/10/10/data-compression-features-in-sql-server-2008/#comments</comments>
		<pubDate>Mon, 10 Oct 2011 18:50:19 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[Backup Compression]]></category>
		<category><![CDATA[Data Compression]]></category>
		<category><![CDATA[Page-level Data compression]]></category>
		<category><![CDATA[Row-level data compression]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1422</guid>
		<description><![CDATA[In this post I would like to talk about data compression/backup compression features available to us in SQL Server 2008 and R2 editions.

I will talk about Data Compression and Backup Compression.

Data Compression is only available in Enterprise (SQL Server 2008 &#38; SQL Server 2008 R2) edition or higher, not in the standard edition for SQL Server 2008/ R2.

Backup compression was introduced in SQL Server 2008 Enterprise.Backup compression is available in the SQL Server 2008 Standard edition R2.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1422&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about data<strong> compression/backup compression</strong> features available to us in SQL Server 2008 and R2 editions.</p>
<p>I will talk about <strong>Data Compression</strong> and <strong>Backup Compression</strong>.</p>
<p><strong>Data Compression</strong> is only available in Enterprise (SQL Server 2008 &amp; SQL Server 2008 R2) edition or higher, not in the <strong>Standard edition</strong> for <strong>SQL Server 2008/ R2</strong>.</p>
<p><strong>Backup compression </strong>was introduced in <strong>SQL Server 2008 Enterprise edition.Backup compression</strong> is available in the <strong>SQL Server 2008 Standard edition R2</strong>.</p>
<p>I know there are samples of how to use data compression/backup compression in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p>Many people have found useful my style of posting. They feel they can follow the steps and master the technology.</p>
<p>We need an instance of SQL Server running in our machine. I have<strong> SQL Server 2008 R2 Developer</strong> edition installed in my machine.</p>
<p>In case you do not have an instance of Enterprise edition or Developer edition  of SQL Server 2008 R2, you can download it from <a href="http://msdn.microsoft.com/en-us/evalcenter/ff459612.aspx" target="_blank">here</a> . This is a trial version.</p>
<p>We need a database as well. I will use the <strong>Northwind</strong> database.</p>
<p>If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>One thing is definetely true, <strong>Data grows</strong>. That means the size of our databases grow.That means that the size of the backups grow.So with data compression not only we reduce the size of the physical files but we also reduce the disk I/O. We can also take compressed backups and reduce the amount of disk space our backups take.</p>
<p>We cannot apply data compression on an entire database.Data compression can only be used for these database objects:</p>
<p>• A table stored as a heap<br />
• A table stored as a clustered index<br />
• A non-clustered index<br />
• An indexed view<br />
• Partitioned tables and indexes</p>
<p>As experienced or novice DBAs we must evaluate the objects in the database that should be compressed and what type of compression we should use.</p>
<p>We have <strong>Row-level data compression</strong> which takes fixed length data types and converts them into variable length data types.Zero and null values are also ignored. By row level data compression we have more rows fitted in a single page.</p>
<p>Let&#8217;s see an example.I will use the <strong>tempdb</strong> database. We will also use the <a href="http://msdn.microsoft.com/en-us/library/ms188776.aspx" target="_blank"><strong>sp_spaceused</strong></a> system stored procedure which displays the <strong>number of rows</strong>, <strong>disk space reserved</strong>, and <strong>disk space</strong> used by a table.In this case through Row-level compression we have  two CHAR (100) data types turned into variable length data types. The characters stored are only the ones that &#8220;make up the data&#8221; , so blank characters are not stored.</p>
<p>1) Launch SQL Server Management Studio and connect to the local instance of SQL Server 2008/R2 Enterprise or Developer edition.</p>
<p>I create the table and populate it with some values and then I use the <a href="http://msdn.microsoft.com/en-us/library/ms188776.aspx" target="_blank"><strong>sp_spaceused</strong></a> system stored procedure. Execute the code up to line 15 and see the results.</p>
<p><pre class="brush: sql;">
USE tempdb
GO

CREATE TABLE MyCompressionTable (ID INT, phrase1 CHAR(100),phrase2 CHAR(100))
GO

INSERT INTO MyCompressionTable VALUES (1,
'SQL Server is the best RDBMS','I love T-SQL')

GO 15000

SELECT * FROM MyCompressionTable

EXEC sp_spaceused MyCompressionTable
GO

-- DATA_COMPRESSION = ROW
ALTER TABLE MyCompressionTable
REBUILD WITH (DATA_COMPRESSION = ROW);
GO

EXEC sp_spaceused MyCompressionTable
GO

</pre></p>
<p>Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/row_compression.jpg"><img class="aligncenter size-full wp-image-1425" title="row_compression" src="http://dotnetstories.files.wordpress.com/2011/10/row_compression.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>Now execute the lines 18-23. In those lines I apply row compression on the table and then I use the <a href="http://msdn.microsoft.com/en-us/library/ms188776.aspx" target="_blank"><strong>sp_spaceused</strong></a> system stored procedure again. Execute the code in the lines 18-23 and see the results. Notice the difference in size of the table.  Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/row_compression-1.jpg"><img class="aligncenter size-full wp-image-1426" title="row_compression-1" src="http://dotnetstories.files.wordpress.com/2011/10/row_compression-1.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>We have another form of data compression, <strong>Page-level Data</strong> <strong>compression</strong>. This is a more sophisticated,advanced form of compression which combines row-level data compression with prefix and dictionary compression algorithms. With this type of compression we have increased data compression over row level compression.</p>
<p>I won&#8217;t go into details on dictionary algorithms but their main idea is to search for repeated patterns of data in columns and then place that data in a special &#8220;place&#8221; in the page. Then obviously there is some reference from each row to this &#8220;place&#8221; in the page where the <strong>common value</strong> is stored.</p>
<p>Let&#8217;s say we have a column e.g <strong>FootballTeamName</strong> with values</p>
<p>Man United<br />
Newcastle United<br />
Westham United<br />
Leeds United</p>
<p>Then through column prefix phase the &#8220;United&#8221; common value is detected and is stored in an <em>anchor</em> record and then there is a reference to this anchor record from the column.</p>
<p>If you need to learn more about those algorithms and Data compression in general have a look at this whitepaper.</p>
<p>In this code we alter the Data compression from <strong>Row</strong> to <strong>Page</strong> level and then execute the <strong>sp_spaceused</strong> stored procedure.Execute the code and see the results.</p>
<p><pre class="brush: sql;">

ALTER TABLE TestCompression
REBUILD WITH (DATA_COMPRESSION = PAGE);
GO

EXEC sp_spaceused TestCompression
GO

</pre></p>
<p>Have a look at the picture below.You can compare the differences in the size of the table when the different forms of data compression are applied and when there was no data compression applied to the table.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/page-compression.jpg"><img class="aligncenter size-full wp-image-1429" title="page-compression" src="http://dotnetstories.files.wordpress.com/2011/10/page-compression.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>I would like to explain a few things about how Data compression works internally.I know a lot of people who are totally confused on how SQL Server handles internally data compression.  You might ask, &#8220;Do I need to know this?&#8221;.</p>
<p>Well, the answer is no really&#8230;.I mean, you do not have to know how the Iphone works internally in order to use it.</p>
<p>Having said that it is useful sometimes to dive into the inner workings of the <strong>Storage Engine</strong>, the relational engine and the <strong>SQL OS</strong>.When we compress tha data that means that the <strong>Storage Engine</strong> compresses the data and stores it.</p>
<p>When the <strong>Storage Engine</strong> passes the data back to us through <strong>Relational Engine</strong>, it has to uncompress it.Obviously we need more CPU power to do that. Well, always keep in mind that from all the subsystems that SQL Server uses CPU is the faster one.</p>
<p>By data compression the amount of I/O is reduced and that is the important thing.If we want to update a row that is stored in the disk and is compressed using row-level compression, the row must be brought to memory so the update takes place. The <strong>Storage Engine</strong> gets the compressed data from disk and brings it into memory(that means more data is stored in the buffer cache and that means less I/O).</p>
<p>Then the <strong>Relational Engine</strong> steps up. But before performing its magic (executing the Update statement) the row is uncompressed by the <strong>Storage Engine</strong>.When the updates takes place the row is handed back to the <strong>Storage Engine</strong> where it is compressed again. At some point during a CHECKPOINT operation the row is stored to the disk again always in compressed format.</p>
<p>Now let&#8217;s see how to perform data compression using SSMS. We want a database, a table and lots of data in it. I will create a database &#8220;testdata&#8221; and a table called &#8220;ThePerson&#8221;</p>
<p>There will be 20 thousand rows of data in the table. I used the <strong>SQL Data Generator</strong>  tool from <strong>Red Gate</strong>.You can download the script that creates the database and the table and populates the table from <a href="http://weblogs.asp.net/blogs/dotnetstories/testdata.zip" target="_blank">here</a>.</p>
<p>Open the script in a new query window and execute it.</p>
<p>Now that you have the database and the table ready we can use the SSMS to perform data compression. Select the table and right click on it. From the popup menu select Storage &#8212; &gt; Manage Partition. The <strong>Data Compression Wizard</strong> is shown.Click <strong>Next. </strong>Then select the compression type (select Row) and then press <strong>Calculate</strong>.This allow us to see  how much space will be saved once compression has been turned on.</p>
<p>Have a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/rowcalculate.jpg"><img class="aligncenter size-full wp-image-1434" title="rowcalculate" src="http://dotnetstories.files.wordpress.com/2011/10/rowcalculate.jpg?w=460&#038;h=383" alt="" width="460" height="383" /></a></p>
<p>Now choose from the drop-down menu under <em>Compression Type</em> the option <em>Page</em> and then press <strong>Calculate</strong>.</p>
<p>Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/pagetype-compression.jpg"><img class="aligncenter size-full wp-image-1435" title="pagetype-compression" src="http://dotnetstories.files.wordpress.com/2011/10/pagetype-compression.jpg?w=460&#038;h=383" alt="" width="460" height="383" /></a></p>
<p>I will choose to go with the &#8220;Page&#8221; compression since it offers me greater compression.So we now, have to click the <strong>Next</strong> button.I will choose to create a script and script it in a new query window.Then I click &#8220;Next&#8221; again and then the &#8220;Finish&#8221; button.I chose to save the script in a new query window so I can execute it later when there is no so much activity in the server.By that I mean since this is a heavy CPU related task, leave it until a time where you server has less workload to process.</p>
<p>Have a look at the picture below to see a snapshot of this step.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/wizzard-page.jpg"><img class="aligncenter size-full wp-image-1437" title="wizzard-page" src="http://dotnetstories.files.wordpress.com/2011/10/wizzard-page.jpg?w=460&#038;h=383" alt="" width="460" height="383" /></a></p>
<p>This is the T-SQL code that was generated in my query window</p>
<p><pre class="brush: sql;">

USE [testdata]
ALTER TABLE [dbo].[ThePerson] REBUILD PARTITION = ALL
WITH
(DATA_COMPRESSION = PAGE
)

</pre></p>
<p>We can use the <strong>sp_estimate_data_compression_savings</strong> system stored procedure to find out the estimated storage space savings. In our case we can use the following T-SQL.</p>
<p><pre class="brush: sql;">

USE testdata
GO
EXEC sp_estimate_data_compression_savings 'dbo', 'ThePerson', NULL, NULL, 'ROW' ;
GO
EXEC sp_estimate_data_compression_savings 'dbo', 'ThePerson', NULL, NULL, 'PAGE' ;
GO

</pre></p>
<p>There is another free tool, very useful, that is called SQL Server Compression Estimator (SSCE) and you can download it from <a href="http://ssce.codeplex.com/" target="_blank">here</a>.</p>
<p>This is a tool that lets you quickly and easily to determine the best compression algorithm for a database with many objects. It works for SQL Server 2008 and later.</p>
<p>After you download it and install it you can use it. I provide some snapshots on how to use it. It is very easy to use.First you connect to the instance of SQL Server.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/ssce.jpg"><img class="aligncenter size-full wp-image-1452" title="ssce" src="http://dotnetstories.files.wordpress.com/2011/10/ssce.jpg?w=460" alt=""   /></a></p>
<p>Then we need to select a database , decide the percentage of compression we would like and decide whether <strong>Index Maintenance Ratio</strong> will be calculated.</p>
<p>Then the tool will process all the tables in the database calculating the potential compression savings for each one</p>
<p>We have the buttons &#8220;Save Results&#8221; that will save the entire contents of the results window to a comma separated value (CSV) file. We have the button &#8220;Create Script&#8221; that will create a Transact-SQL script.Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/ssce1.jpg"><img class="aligncenter size-full wp-image-1453" title="ssce1" src="http://dotnetstories.files.wordpress.com/2011/10/ssce1.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>This is a very nice tool that let us quickly and easily implement data compression in a database with a large number of objects.</p>
<p>Now let&#8217;s move on to  <strong>Backup Compression</strong>.<strong>Backup compression</strong> is available in the <strong>SQL Server 2008 Standard edition R2.</strong></p>
<p>When we compress backups we<strong> save</strong> <strong>backup space and also reduce backup times</strong>.Obviously we will need more CPU resources to perform compression during a backup or decompression during a restore.One thing to keep in mind is that if we have databases that use data compression or are encrypted, backup compression will not be very efficient. Backup compression does not use row-level or page-level data compression. Backup compression happens at the time of a backup, and it uses its own compression algorithms.Let&#8217;s see an example. We will <strong>back up the Northwind</strong> database without back up compression and then we will use backup compression</p>
<ul>
<li><strong>without backup compression</strong></li>
</ul>
<p>We will select Northwind database then <strong>Tasks &#8211;&gt; Back up</strong>.</p>
<p>Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/backupnocompess1.jpg"><img class="aligncenter size-full wp-image-1442" title="backupnocompess" src="http://dotnetstories.files.wordpress.com/2011/10/backupnocompess1.jpg?w=460&#038;h=261" alt="" width="460" height="261" /></a></p>
<ul>
<li><strong>with backup compression</strong></li>
</ul>
<p>We will select Northwind database then <strong>Tasks &#8211;&gt; Back up</strong> and then<strong> Options</strong>.Choose <strong>Compress backup</strong>.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/backupcompress.jpg"><img class="aligncenter size-full wp-image-1443" title="backupcompress" src="http://dotnetstories.files.wordpress.com/2011/10/backupcompress.jpg?w=460&#038;h=265" alt="" width="460" height="265" /></a></p>
<p>We can set at the server level, the option to have <strong>backup compression</strong> on by default for every database on the server.This is the <strong>T-SQL</strong> code to achieve that.</p>
<p><pre class="brush: sql;">

EXEC sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO

-- See the current values
EXEC sp_configure

-- Turn on backup compression by default
EXEC sp_configure 'backup compression default', 1
GO
RECONFIGURE
GO
</pre></p>
<p>Now we have two backups. One compressed backup of the Northwind database and one uncompressed.</p>
<p>Have a look at the picture below to see the difference in size of the backup files when using compressed backups and when there is not a compressed backup.There is a notable difference.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/10/backupcompression.jpg"><img class="aligncenter size-full wp-image-1439" title="backupcompression" src="http://dotnetstories.files.wordpress.com/2011/10/backupcompression.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>When restoring a compressed backup it will uncompress itself automatically. We compress backups using the Enterprise Edition of SQL Server 2008 and the Standard edition of SQL Server 2008 R2 but we  can restore compressed backups to any edition of SQL Server 2008. You cannot restore a compressed SQL Server 2008 backup to any previous versions of SQL Server.</p>
<p>That is all folks!!!</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/backup-compression/'>Backup Compression</a>, <a href='https://dotnetstories.wordpress.com/tag/data-compression/'>Data Compression</a>, <a href='https://dotnetstories.wordpress.com/tag/page-level-data-compression/'>Page-level Data compression</a>, <a href='https://dotnetstories.wordpress.com/tag/row-level-data-compression/'>Row-level data compression</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1422/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1422&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/10/10/data-compression-features-in-sql-server-2008/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/row_compression.jpg" medium="image">
			<media:title type="html">row_compression</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/row_compression-1.jpg" medium="image">
			<media:title type="html">row_compression-1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/page-compression.jpg" medium="image">
			<media:title type="html">page-compression</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/rowcalculate.jpg" medium="image">
			<media:title type="html">rowcalculate</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/pagetype-compression.jpg" medium="image">
			<media:title type="html">pagetype-compression</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/wizzard-page.jpg" medium="image">
			<media:title type="html">wizzard-page</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/ssce.jpg" medium="image">
			<media:title type="html">ssce</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/ssce1.jpg" medium="image">
			<media:title type="html">ssce1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/backupnocompess1.jpg" medium="image">
			<media:title type="html">backupnocompess</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/backupcompress.jpg" medium="image">
			<media:title type="html">backupcompress</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/10/backupcompression.jpg" medium="image">
			<media:title type="html">backupcompression</media:title>
		</media:content>
	</item>
		<item>
		<title>Looking into Triggers in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/10/02/looking-into-triggers-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/10/02/looking-into-triggers-in-sql-server/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 20:55:01 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[AFTER triggers]]></category>
		<category><![CDATA[DDL triggers]]></category>
		<category><![CDATA[DML triggers]]></category>
		<category><![CDATA[INSTEAD OF triggers]]></category>
		<category><![CDATA[Logon triggers]]></category>
		<category><![CDATA[triggers]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1403</guid>
		<description><![CDATA[In this post I would like to show a few examples of how to use triggers in SQL Server. I would like to talk about the uses of triggers, the type of triggers and some misconceptions about the triggers.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1403&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to show a few examples of how to use <strong>triggers</strong> in SQL Server. I would like to talk about the uses of triggers, the type of triggers and some misconceptions about the triggers.</p>
<p>I know there are samples of how to use triggers in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.</p>
<p>Many people have found useful my style of posting. They feel they can follow the steps and master the technology.</p>
<p>Before we move on, let&#8217;s look into trigger types,uses and definitions.</p>
<p>A trigger is a mechanism that in invoked when a particular action occurs on a particular table or view. Each trigger has three general parts:</p>
<ul>
<li>a name</li>
<li>the action</li>
<li>the execution</li>
</ul>
<p>The  action of a trigger can be either a DML statement (INSERT,UPDATE,DELETE) or a DDL statement (CREATE,ALTER,DROP). So we have two types of triggers:DML and DDL triggers.There are more options when defining triggers. We have the <strong>AFTER</strong> and <strong>INSTEAD OF</strong> options.<strong>AFTER</strong> triggers fire after the triggering action occurs while <strong>INSTEAD OF</strong> triggers are executed instead of the corresponding triggering action.<strong>AFTER</strong> triggers can be created only on tables.<strong>INSTEAD OF</strong> triggers can be created on both tables and views.Triggers on Views only fire if data changes through a view.We cannot directly execute them.Triggers can be thought as procedures that run in response to changes to data. Their main purpose is to determine whether to commit or rollback tha changes. You can think of them as a variation of stored procedures. They are treated the same internally by SQL Server as far parsing,name resolution and query plan otimisation is concerned.When it comes to performance, I have one sentence for you guys &#8220;Triggers are expensive&#8221;.</p>
<p>Whenever you can use constraints or referential integrity (cascade updates and deletes) to enforce data integrity you should do that.  Constraints fire before data modification. AFTER triggers fire after data modification.Triggers should be only used to enforce complex business rules.Another useful operation triggers can perform is that they can record changes to data. They cannot create objects, they cannot modify the schema of an object(e.g add a column to a table) and cannot perform administrative tasks (e.g backups).</p>
<p>Finally, I must point out that triggers use virtual tables, <strong>inserted</strong> and <strong>deleted</strong>. INSERT statements put new rows in <strong>inserted</strong> virtual table. UPDATE statements put new values in <strong>inserted</strong> virtual table and old values in <strong>deleted </strong>virtual table. DELETE statements put affected rows in <strong>deleted</strong> virtual tables.</p>
<p>Well, you might be confused with all these options I have mentioned but do not worry I will provide you with examples and you will not have any questions,hopefully.</p>
<p>We need an instance of SQL Server running in our machine. I have<strong> SQL Server 2008 R2 Developer</strong> edition installed in my machine.You can use any edition of SQL Server you might have installed in your machine.We need a database as well. I will use the <strong>Northwind</strong> database.</p>
<p>You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>. If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>1) Launch SQL Server Management Studio and connect to the local instance of SQL Server.</p>
<p>Let&#8217;s write our first trigger.I am going to create table (Football) in Northwind database. Then I will insert some values in it. Then I will create an AFTER trigger where I will check whether the user tries to delete the row where the TeamName field equals &#8220;Liverpool&#8221;.If that happens then the transaction should be rolled back. Have a look at the T-SQL code below.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE TABLE dbo.Football
(
TeamID INT PRIMARY KEY ,
TeamName VARCHAR(50) NOT NULL ,
TeamCoach VARCHAR(50) NOT NULL ,
TeamCaptain VARCHAR(50) NOT NULL
) ;
GO

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (1,'ManUtd','Alex Ferguson','Nemanja Vidić');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (2,'Liverpool','Kenny Dalglish','Steven Gerrard');

INSERT INTO dbo.Football(TeamID,TeamName,TeamCoach,TeamCaptain)
VALUES (3,'Everton','David Moyes','Phil Neville');

-- Create the trigger
CREATE TRIGGER dbo.NoDeleteLiverpool
ON dbo.Football
FOR DELETE
AS
DECLARE @FootballValue varchar(50);
SELECT @FootballValue = TeamName FROM deleted;

IF @FootballValue = 'Liverpool'
BEGIN
PRINT 'Deleting Liverpool data is not allowed.';
ROLLBACK TRAN;
END
GO

DELETE FROM dbo.Football WHERE TeamName='Liverpool';
GO

--delete the trigger
DROP TRIGGER dbo.NoDeleteLiverpool

DROP TABLE dbo.football

</pre></p>
<p>Run the code and see the results. In the last T-SQL statement above I check if the trigger works by executing a <em>Delete</em> statement..  If you run the <em>Delete</em> statement the trigger will fire and you will receive a message like this</p>
<p>&#8220;<em>Deleting Liverpool data is not allowed.</em><br />
<em> Msg 3609, Level 16, State 1, Line 1</em><br />
<em> The transaction ended in the trigger. The batch has been aborted.</em>&#8220;</p>
<p>Finally I drop the trigger and then drop the table as well.</p>
<p>So we have created an AFTER delete trigger. Now I can create an <strong>INSTEAD OF</strong> trigger that will check if someone is trying to delete any rows from the<strong> Categories</strong> table. If that happens then the transaction must be rolled back.A message should be printed to the user as well.</p>
<p><pre class="brush: sql;">

USE Northwind
go

CREATE TRIGGER NoCategoriesDelete ON dbo.Categories
INSTEAD OF DELETE
AS
BEGIN
DECLARE @Count INT

SET @Count = @@ROWCOUNT
IF @Count = 0
RETURN

SET NOCOUNT ON

BEGIN
RAISERROR
(N'Categories cannot be deleted. They can only be marked as not current.', -- Message
10, -- Severity.
1)  -- State.

-- Rollback any active or uncommittable transactions
IF @@TRANCOUNT &gt; 0
BEGIN
ROLLBACK TRANSACTION
END
END
END

DELETE FROM dbo.Categories WHERE CategoryName='Beverages'

SELECT * FROM dbo.Categories

DROP TRIGGER NoCategoriesDelete

</pre></p>
<p>Run the query and see the results.</p>
<p>Now let&#8217;s create another trigger. This is going to be an AFTER INSERT trigger . I will use this trigger to check that <strong>only  a number of characters more than seven will be inserted</strong> in the <strong>RegionDescription</strong> column of the <strong>dbo.Region</strong> column.The code follows</p>
<p><pre class="brush: sql;">

USE Northwind
go

CREATE TRIGGER RegionLength
ON  dbo.Region
AFTER INSERT
AS
BEGIN
DECLARE @RegionDescription nvarchar(50)
SELECT @RegionDescription = RegionDescription
FROM inserted
IF len(@RegionDescription) &lt; 7
BEGIN
ROLLBACK TRANSACTION
END
END

--this will fail

INSERT INTO dbo.Region VALUES (6,'London')

--this will succeed

INSERT INTO dbo.Region VALUES (6,'South London')

--drop the trigger
DROP TRIGGER RegionLength

</pre></p>
<p>Run the query and see the results.As I said earlier you should always use <strong>CHECK</strong> constraints instead of triggers when possible.In this case, we will alter the definition of the table and we add a <strong>CHECK</strong> constraint.So we do not need the trigger anymore, that is why I deleted above.In the code below I create the <strong>CHECK</strong> constraint.</p>
<p><pre class="brush: sql;">
USE [Northwind]
GO

ALTER TABLE [dbo].[Region]  WITH NOCHECK ADD  CONSTRAINT [CK_RegionDescriptionLength] CHECK  ((len([RegionDescription])&gt;(7)))
GO

ALTER TABLE [dbo].[Region] CHECK CONSTRAINT [CK_RegionDescriptionLength]
GO

</pre></p>
<p>Let&#8217;s see some examples of DDL triggers. They were introduced in SQL Server 2005.DDL triggers are implemented as AFTER triggers.That means that the operation that fires the trigger actually takes place and then the trigger is activated and rolls back the operation if we put a ROLLBACK statement in the trigger body.In this example below, I will show you how to create a trigger that does not allow to create new tables in the Northwind database.The event I am interested is (CREATE_TABLE ). Have a look at MSDN and BOL for the DDL events that you can write triggers for.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

CREATE TRIGGER NoNewTablesAreAllowed
ON DATABASE
FOR CREATE_TABLE
AS
PRINT 'No new tables allowed!!!!!.You will soon hear from the DBA!!!';
ROLLBACK ;
GO

-- Test the trigger
-- you will get an error
CREATE TABLE dbo.MyTable
(col1 varchar(50),col2 VARCHAR(50),col3 VARCHAR(50));
GO

-- Disable the trigger.
DISABLE TRIGGER NoNewTablesAreAllowed ON DATABASE;
GO
-- Now attempt to create the table again. You will succeed

CREATE TABLE dbo.MyTable
(col1 varchar(50),col2 VARCHAR(50),col3 VARCHAR(50));
GO

DROP TRIGGER NoNewTablesAreAllowed ON DATABASE

DROP TABLE dbo.MyTable

</pre></p>
<p>Run the code and see the results.</p>
<p>Now we will create another DDL trigger. In this case we do not want to allow anyone to create a database on the server.We also want to print on the results the statement that the user typed when he attempted to  create the database (e.g CREATE DATABASE MYDB). We will use the <span style="color:#ff00ff;">EVENTDATA()</span> function that returns data only when appears in the body of a DDL or logon trigger. Basically it returns information about server and database events.The event I am interested in is (FOR CREATE_DATABASE).When the user types a &#8220;create database&#8221; statement the trigger will fire and print a message to the screen and rollback the transaction.</p>
<p><pre class="brush: sql;">

USE    master

GO

IF EXISTS (SELECT * FROM sys.server_triggers
WHERE name = 'ddl_trig_database')
DROP TRIGGER ddl_trig_database
ON ALL SERVER;
GO

CREATE TRIGGER ddl_trig_database
ON ALL SERVER
FOR CREATE_DATABASE
AS
PRINT 'You are trying to create a new database on the server .you should have checked with me first !!!'
SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
rollback
GO

--try to create a database. It will fail
CREATE DATABASE MytestDB

--drop the trigger
DROP TRIGGER ddl_trig_database
ON ALL SERVER;
GO

--this will succeed now
CREATE DATABASE MytestDB

--drop database

DROP DATABASE MytestDB

</pre></p>
<p>Run the code and see the results.</p>
<p>We can also use triggers for auditing purposes.First we need to create a table that we will store the audit data. We need to have columns that will store data like the login name, the command and the time the command was executed.Then we need to create the trigger that will populate the table with information about all database level events of the Northwind database.The event type and Transact-SQL statement are captured by using <strong>XQuery</strong> expressions against the XML data generated by<span style="color:#ff00ff;"> EVENTDATA() <span style="color:#000000;">function.Make sure you run the code below as is defined in the steps(in the comments).</span></span></p>
<p>Have a look at the code below.</p>
<p><pre class="brush: sql;">

-- STEP 1, Create DDL Audit table
USE Northwind
GO

CREATE TABLE DatabaseDDLAudit
(AuditID int IDENTITY(1,1) NOT NULL
,PostTime datetime NOT NULL
,LoginName nvarchar(128) NULL
,Command nvarchar(MAX) NULL
,EventData xml NULL)

-- STEP 2, Create DDL database trigger

CREATE TRIGGER NoDDLAllowed ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
SET NOCOUNT ON
DECLARE @data AS XML ,
@PostTime AS DATETIME ,
@HostName AS NVARCHAR(128)
DECLARE @LoginName AS NVARCHAR(128) ,
@Command AS NVARCHAR(MAX)

SET @data = EVENTDATA()

SELECT  @PostTime = CAST(@Data.value(' (/EVENT_INSTANCE/PostTime)[1] ',
'nvarchar(25) ') AS DATETIME) ,
@HostName = @Data.value(' (/EVENT_INSTANCE/HostName)[1] ',
'nvarchar(25) ') ,
@LoginName = @Data.value(' (/EVENT_INSTANCE/LoginName)[1] ',
'nvarchar(25) ') ,
@Command = @Data.value(' (/EVENT_INSTANCE/TSQLCommand)[1] ',
'nvarchar(max) ')

RAISERROR ('Modifications to this database are not allowed!', 16, 1)
ROLLBACK

INSERT DatabaseDDLAudit
(PostTime, LoginName, Command, EventData)
VALUES   (@PostTime, @LoginName, @Command, @Data)
RETURN;

SELECT * from databaseddlaudit

-- STEP 3, Test the trigger

ALTER TABLE dbo.Categories
ADD NewColumn varchar(10) NULL;

-- Step 4, View DDL Audit

SELECT * FROM DatabaseDDLAudit;
GO

--step 5

DISABLE TRIGGER NoDDLAllowed
ON DATABASE;
GO

CREATE TABLE TestTable
(Column1 int
,Column2 int);
GO

DROP table testtable

--step 6

ENABLE  TRIGGER NoDDLAllowed
ON DATABASE;

drop TRIGGER NoDDLAllowed
ON DATABASE;

drop TABLE DatabaseDDLAudit

</pre></p>
<p>We have covered a lot of things regarding triggers and you can follow all the examples in this post. They are very easy to follow.</p>
<p>Hope its helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server/'>Sql Server</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/after-triggers/'>AFTER triggers</a>, <a href='https://dotnetstories.wordpress.com/tag/ddl-triggers/'>DDL triggers</a>, <a href='https://dotnetstories.wordpress.com/tag/dml-triggers/'>DML triggers</a>, <a href='https://dotnetstories.wordpress.com/tag/instead-of-triggers/'>INSTEAD OF triggers</a>, <a href='https://dotnetstories.wordpress.com/tag/logon-triggers/'>Logon triggers</a>, <a href='https://dotnetstories.wordpress.com/tag/triggers/'>triggers</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1403/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1403/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1403/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1403&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/10/02/looking-into-triggers-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Using built-in functions in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/09/30/using-built-in-functions-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/09/30/using-built-in-functions-in-sql-server/#comments</comments>
		<pubDate>Fri, 30 Sep 2011 16:02:24 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[builtin functions]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1385</guid>
		<description><![CDATA[In this post I would like to show a few examples of built in T-SQL functions and global functions. I teach T-SQL to people from all walks of life and many of them have asked me to write a simple post with examples of the most commonly used T-SQL functions and global functions.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1385&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to show a few examples of built in T-SQL functions and global functions. I teach T-SQL to people from all walks of life and many of them have asked me to write a simple post with examples of the most commonly used T-SQL functions and global functions.</p>
<p>I know there are samples of how to use these functions in BOL,MSDN and elsewhere but I thought that it would be a good idea to give it a try with hands-on examples.We will cover around 50 built-in TSQL functions.</p>
<p>Many people have found useful my style of posting. They feel they can follow the steps and master the technology.For those of you that are familiar with MS Excel you will see similar function in SQL Server.</p>
<p>We need an instance of SQL Server running in our machine. I have SQL Server 2008 R2 Developer edition.You can use any edition of SQL Server you might have installed in your machine.We need a database as well. I will use the <strong>Northwind</strong> database.</p>
<p>You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>. If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>1) Launch SQL Server Management Studio and connect to the local instance of SQL Server.</p>
<p>I will start by showing you simple examples on how to use the AGGREGATE built-in  functions.<span style="color:#ff00ff;">COUNT()</span> function, counts the number of rows in the aggregate query. <span style="color:#ff00ff;">COUNTBIG()</span> is more or less the same as <span style="color:#ff00ff;">COUNT()</span> but returns a bigint data type. <span style="color:#ff00ff;">SUM()</span> functions adds column values and <span style="color:#ff00ff;">AVG()</span> averages column values. <span style="color:#ff00ff;">MIN()</span> and <span style="color:#ff00ff;">MAX()</span> functions return the lowest or maximum column value respectively. Let&#8217;s have a look at some examples.</p>
<p><pre class="brush: sql;">

USE Northwind
go

SELECT COUNT(*) FROM dbo.Employees

SELECT COUNT(*) AS NUMEmps,COUNT(region) AS NumRegions FROM dbo.Employees

SELECT SUM(UnitPrice) FROM dbo.[Order Details]
SELECT AVG(UnitPrice) FROM dbo.[Order Details]
SELECT MIN(UnitPrice) FROM dbo.[Order Details]
SELECT MAX(UnitPrice) FROM dbo.[Order Details]

</pre></p>
<p>I will provide you with a simple example on how to use the <span style="color:#ff00ff;">ISNUMERIC()</span> function. In this example I am checking whether the values in the <strong>PostalCode</strong> column of the<strong> Customers</strong> table are numeric or not.</p>
<p><pre class="brush: sql;">

USE Northwind
go

SELECT PostalCode,ISNUMERIC(PostalCode)
FROM dbo.customers

</pre></p>
<p>Run the query and see the results.</p>
<p>We can generate random numbers with T-SQL by using the <span style="color:#ff00ff;">RAND()</span> function.This function generates random numbers between 0 and 1.When specifying a seed inside the RAND(678) function then all the values that are returned from SQL Server are the same no matter how many times you execute the statement.</p>
<p><pre class="brush: sql;">

SELECT RAND(),RAND(),RAND(),RAND()
SELECT RAND(),RAND(),RAND(),RAND(),RAND(678)
</pre></p>
<p>Run the query and see the results.</p>
<p>Another very important function is the <span style="color:#ff00ff;">ROUND()</span> function. We can specify the  precision in this function. That means if we want to round to the decimal value, whole (integer) value. We do that by setting the <strong>second argument</strong> in the arguments list inside the parenthesis. If we specify a number other that <strong>0</strong> for the third argument in the parenthesis in the arguments list it means we want to truncate the value.<br />
ROUND <strong>(</strong> <em>numeric_expression </em><strong>,<em> length </em></strong>[ <strong>,</strong><em>function </em>] <strong>) </strong></p>
<p><pre class="brush: sql;">

SELECT  UnitPrice ,
ROUND(UnitPrice, 0) ,
ROUND(UnitPrice, 0, 1) ,
ROUND(UnitPrice, 1) ,
ROUND(UnitPrice, -1)
FROM    dbo.Products
</pre></p>
<p>Run the query and see the results.</p>
<p>The next function I am going to look is the <span style="color:#ff00ff;">ABS()</span> function that returns the absolute (positive) value of the specified numeric expression.</p>
<p><pre class="brush: sql;">

SELECT ABS(-2),ABS(-3),ABS(9)

</pre></p>
<p>Run the query and see the results.</p>
<p>The next function I am going to look is the <span style="color:#ff00ff;">SQRT()</span> function that returns the square root of the specified value.</p>
<p><pre class="brush: sql;">

SELECT SQRT(16),SQRT(100)

</pre></p>
<p>Run the query and see the results.</p>
<p>The next function I am going to look is the <span style="color:#ff00ff;">SQUARE()</span> function that Returns the square of the specified value.</p>
<p><pre class="brush: sql;">

SELECT SQUARE(16),SQUARE(100)

</pre></p>
<p>Run the query and see the results.</p>
<p>Now let&#8217;s move on and talk about the STRING built-in T-SQL functions. I will start with the <span style="color:#ff00ff;">REPLACE()</span> function. It is very simple really. We do specify the expression we want to be searched (usually a column) then what to search for and finally the third argument is what we want to replace it with. In this example we replace the &#8216;Ms.&#8221; with &#8216;Miss&#8217; in the column <strong>TitleOfCourtesy </strong>of the table <strong>Employees</strong></p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT TitleOfCourtesy,
REPLACE(TitleOfCourtesy, 'Ms.', 'Miss')
FROM    [dbo].[Employees]
</pre></p>
<p>Run the query and see the results.</p>
<p>Another built-in string function is the <span style="color:#ff00ff;">STUFF() </span>function. It inserts a string into another string and we can specify the start position and the length .In this example we</p>
<p>replace (starting from the second character) the &#8216;Dr.&#8217; with  &#8216;Doctor&#8217;</p>
<p><pre class="brush: sql;">

SELECT TitleOfCourtesy,
STUFF(TitleOfCourtesy, 2,5, 'octor')
FROM    [dbo].[Employees]
WHERE TitleOfCourtesy='Dr.'

</pre></p>
<p>Run the query and see the results.</p>
<p>If we want to find the number of characters in a string we can use the <span style="color:#ff00ff;">LEN() </span>function</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT LEN(City)

FROM .[dbo].[Employees]

</pre></p>
<p>Run the query and see the results.</p>
<p>We can use the <span style="color:#ff00ff;">LEFT()</span> and <span style="color:#ff00ff;">RIGHT()</span> functions to get a portion of a column or expression ( left or right ) by specifying a number of characters.Have a look at the examples below.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT LEFT(Phone,5)
FROM dbo.[Shippers]

SELECT LEFT(Phone,LEN(phone)-8)
FROM dbo.[Shippers]

SELECT RIGHT(Phone,4)
FROM dbo.[Shippers]

SELECT RIGHT(Phone,LEN(phone)-10)
FROM dbo.[Shippers]

</pre></p>
<p>Run the query and see the results. You can see that I am using <span style="color:#ff00ff;">LEN()</span> as well. The real power of functions is showing when we use them together.</p>
<p>Now I want to explain how to use the <span style="color:#ff00ff;">SUBSTRING()</span>function. This function allows us to return only a part of a column or expression by specifying the start position (second argument) and the number of characters we want to get back (third argument)</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT  SUBSTRING(FirstName, 1, 1) + '. ' + LastName
FROM  [dbo].[Employees]

</pre></p>
<p>Run the query and see the results.</p>
<p>Now I want to explain how to use the <span style="color:#ff00ff;">CHARINDEX()</span> function.We provide a   &#8216;-&#8217; (expression ) and we look where this &#8220;-&#8221; appears in the <strong>HomePhone</strong> column and we return the position of that &#8220;-&#8221; inside the <strong>HomePhone</strong> column.In the second example I use the<span style="color:#ff00ff;"> CHARINDEX()</span> and the <span style="color:#ff00ff;">SUBSTRING()</span> functions to get only the areacode of the <strong>HomePhone </strong>column</p>
<p><pre class="brush: sql;">

SELECT  CHARINDEX('-', HomePhone)
FROM    dbo.Employees

SELECT  HomePhone ,
SUBSTRING(HomePhone, 1, ( CHARINDEX(')', HomePhone) )) AS 'AreaCode'
FROM    dbo.Employees

</pre></p>
<p>Run the query and see the results.There is another function called <span style="color:#ff00ff;">PATINDEX()</span> . It returns the  starting position of the first occurrence of a pattern in a specified expression.</p>
<p>We can use all the wildcards we use in LIKE statements like &#8220;%&#8221; or &#8220;_&#8221;</p>
<p><pre class="brush: sql;">

SELECT ProductName,QuantityPerUnit,PATINDEX('24 - % g pkgs.',QuantityPerUnit)
FROM dbo.Products
SELECT [CategoryName],PATINDEX('%MEAT%',categoryname)

FROM [dbo].[Categories]

</pre></p>
<p>Run the query and see the results. In this example we will get (in the third column) the starting position of the pattern &#8216;<strong>24 &#8211; % g pkgs.</strong>&#8216; in the<strong> QuantityPerUnit </strong>column of the <strong>Products</strong> table.The second example we look for the starting position of the pattern &#8216;<strong>%meat%</strong>&#8216; in the CategoryName column of the <strong>Categories</strong> table.</p>
<p>If there is no match it will return <strong>0</strong>, as <span style="color:#ff00ff;">CHARINDEX()</span> does.</p>
<p>The next function I am going to look is <span style="color:#ff00ff;">SPACE()</span>.It returns a string of repeated spaces.</p>
<p><pre class="brush: sql;">

USE Northwind

GO

SELECT  FirstName + SPACE(3) + LastName
FROM    dbo.Employees

</pre></p>
<p>Run the query and see the results.</p>
<p>Now I am going to look into<span style="color:#ff00ff;"> CHAR()</span> and <span style="color:#ff00ff;">ASCII()</span> functions. The CHAR() converts an <strong>int</strong> ASCII code to a character.<span style="color:#ff00ff;">ASCII()</span> Returns the ASCII code value of the character.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT CHAR(78) + CHAR(13) + CHAR(80)

SELECT ASCII('P')
</pre></p>
<p>Run the query and see the results.</p>
<p>Now I am going to use the <span style="color:#ff00ff;">UPPER()</span>,<span style="color:#ff00ff;">LOWER()</span>,<span style="color:#ff00ff;">LTRIM()</span>,<span style="color:#ff00ff;">RTRIM()</span> functions. The first function returns an expression that is lowercase and converts it to uppercase. The second function does the exact opposite.There is no <strong>TRIM</strong> function in SQL Server. The <span style="color:#ff00ff;">LTRIM()</span> and <span style="color:#ff00ff;">RTRIM()</span> built in functions remove leading spaces from the left or right of the character expression.</p>
<p><pre class="brush: sql;">

USE Northwind

GO

SELECT  UPPER(FirstName) + ' ' + LOWER(LastName)
FROM    dbo.Employees

SELECT LTRIM ('    I like T-SQL')

SELECT RTRIM ('I like T-SQL      ')

</pre></p>
<p>Now let&#8217;s have a look at the built in functions that support the date and time data types.The <span style="color:#ff00ff;">GETDATE()</span> function returns the date and the time of the server that the query is executing. The <span style="color:#ff00ff;">YEAR()</span>,<span style="color:#ff00ff;">MONTH()</span>,<span style="color:#ff00ff;">DAY()</span> functions return the year,month and day of the expression or column expression that we pass as an argument.</p>
<p><pre class="brush: sql;">

SELECT GETDATE()

SELECT MONTH(GETDATE())
SELECT YEAR(GETDATE())
SELECT DAY(GETDATE())

</pre></p>
<p>Run the T-SQL statements and see the results.</p>
<p>We can use the very useful <span style="color:#ff00ff;">DATEPART()</span> and <span style="color:#ff00ff;">DATENAME()</span> functions. The <span style="color:#ff00ff;">DATEPART()</span> function returns an integer that represents the specified <strong><em>datepart</em></strong> of the specified <em>date. </em>The <strong>datepart</strong> is something we define as the first argument. Have a look <a href="http://msdn.microsoft.com/en-us/library/ms174420.aspx" target="_blank">here</a> , so you can see the various options of the <strong>datepart</strong> argument.The <span style="color:#ff00ff;">DATEPART()</span> function Returns a character string that represents the specified <strong><em>datepart</em></strong> of the specified <strong><em>date</em></strong>.<em></em>The <strong>datepart</strong> is something we define as the first argument. Have a look <a href="http://msdn.microsoft.com/en-us/library/ms174395.aspx" target="_blank">here </a>, so you can see the various options of the <strong>datepart</strong> argument</p>
<p><pre class="brush: sql;">

SELECT
DATEPART(dy, GETDATE()) AS DayOfYear,
DATEPART(dd, GETDATE()) AS DayNum,
DATEPART(ww, GETDATE()) AS WeekNum,
DATEPART(dw, GETDATE()) AS Weekday,
DATEPART(hh, GETDATE()) AS Hour,
DATEPART(mi, GETDATE()) AS Minute,
DATEPART(ss, GETDATE()) AS Seconds;

SELECT
DATENAME(qq, GETDATE()) AS Quarter,
DATENAME(mm, GETDATE()) AS Month,
DATENAME(dw, GETDATE()) AS Weekday,
DATENAME(hh, GETDATE()) AS Hour,
DATENAME(mi, GETDATE()) AS Minute,
DATENAME(ss, GETDATE()) AS Seconds;

</pre></p>
<p>Run the query and see the results.I am going to look into <span style="color:#ff00ff;">DATEADD()</span> and <span style="color:#ff00ff;">DATEDIFF()</span> functions.The <span style="color:#ff00ff;">DATEADD()</span> function is useful when we want to add/subtract  a specified <em>datepart</em> to a date.  The<span style="color:#ff00ff;"> DATEDIFF()</span> function is useful when you want to calculate the difference or the timespan between two dates. In the first example below I add months , years and days to the current date. Then in the next example I get the difference in days between the <strong>OrderDate</strong>, the <strong>RequiredDate</strong> and the <strong>ShippedDate</strong> columns of the table <strong>Orders</strong>.In the last example I get the last day of the month.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT
DATEADD(yy, 3, GETDATE()) AS AddedYears,
DATEADD(mm, 6, GETDATE()) AS AddedMonths,
DATEADD(dd, 6, GETDATE()) AS AddedDays;

SELECT
OrderDate, RequiredDate, ShippedDate,
DATEDIFF(dd, OrderDate, RequiredDate) AS LeadTime,
DATEDIFF(dd, OrderDate, ShippedDate) AS DaysToShip,
DATEDIFF(dd, ShippedDate, RequiredDate) AS DaysEarly
FROM dbo.Orders;

-- finally I get the last day of the month

DECLARE @date datetime
SET @date='2011-10-28'
SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)),
DATEADD(m,1,@date)) AS thelastdayofthemonth

</pre></p>
<p>Run the query and see the results.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT
DATEADD(yy, 3, GETDATE()) AS AddedYears,
DATEADD(mm, 6, GETDATE()) AS AddedMonths,
DATEADD(dd, 6, GETDATE()) AS AddedDays;

SELECT
OrderDate, RequiredDate, ShippedDate,
DATEDIFF(dd, OrderDate, RequiredDate) AS LeadTime,
DATEDIFF(dd, OrderDate, ShippedDate) AS DaysToShip,
DATEDIFF(dd, ShippedDate, RequiredDate) AS DaysEarly
FROM dbo.Orders;

-- finally I get the last day of the month

DECLARE @date datetime
SET @date='2011-10-28'
SELECT DATEADD(dd, -DAY(DATEADD(m,1,@date)),
DATEADD(m,1,@date)) AS thelastdayofthemonth

</pre></p>
<p>Run the query and see the results.</p>
<p>Very often when we write T-SQL statements we want to convert from one data type to another. Sometimes that happens implicitly because SQL Server is clever enough to make the conversion. We should not rely on that fact and always try to convert data types explicitly. Some data types are not compatible with each other and we cannot apply conversion.We will use the <span style="color:#ff00ff;">CAST()</span> and <span style="color:#ff00ff;">CONVERT()</span> functions. Let&#8217;s look at some examples. I have some comments. The second example (SELECT CAST(&#8216;Robert&#8217; AS INT)) will fail&#8230;</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT CAST('12345' AS INT) -- success
SELECT CAST('Robert' AS INT) --fail
SELECT CAST('12/12/1977' AS DATETIME) -- success

--Decimal to Integer
SELECT CAST(69.95 AS INT) -- success

--Decimal to String
SELECT CAST(69.95 AS CHAR(10)) -- success

--Using CONVERT with style

SELECT GETDATE();
SELECT CONVERT(varchar(20), GETDATE(), 1);
SELECT CONVERT(varchar(20), GETDATE(), 101);
SELECT CONVERT(varchar(20), GETDATE(), 102);
SELECT CONVERT(varchar(20), GETDATE(), 126);

SELECT
Quantity,
'$' + CONVERT(varchar(12), Unitprice, 1) AS Unitprice,
'$' + CONVERT(varchar(12), Quantity * UnitPrice, 1) AS Amount
FROM [Order Details]

</pre></p>
<p>Run the queries and see the results.Now I would like to talk about some global functions. Some people call them <strong>global variables</strong>. The  first one is <span style="color:#ff00ff;">@@ROWCOUNT</span> that returns the number of rows that are affected by the last T-SQL statement.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT CompanyName
FROM dbo.Customers
WHERE Country = 'Germany'
SELECT @@ROWCOUNT AS RowsAffected;

</pre></p>
<p>Run the query and see the results.</p>
<p>The  second one is <span style="color:#ff00ff;">@@TRANCOUNT()</span> . This is useful when working with explicit transactions and we want to check if there are any transactions pending.That means if we have transactions that we either need to rollback or commit.The &#8220;BEGIN TRANSACTION&#8221; statement increments the transaction counter by one (@@TRANCOUNT() =1) and the &#8220;ROLLBACK TRANSACTION&#8221; sets the  (@@TRANCOUNT() =0). <span style="color:#ff00ff;">@@IDENTITY</span> retrieves the newly added value inserted in a column that has Identity set.</p>
<p><pre class="brush: sql;">

USE Northwind
GO
BEGIN TRANSACTION
INSERT INTO dbo.Categories (CategoryName)
VALUES ('My Category');
SELECT @@IDENTITY AS AddedCategoryID;
 SELECT @@TRANCOUNT AS TRANCOUNT;

ROLLBACK TRANSACTION
SELECT @@TRANCOUNT AS TRANCOUNT;

</pre></p>
<p>Run the query and see the results.When an error occurs within a T-SQL statement and we want to capture it, we can use the <span style="color:#ff00ff;">@@ERROR</span> that returns the error number for the last Transact-SQL statement executed.In the following statement there is an error in the update statement. After that I get the number of the error(515 in this case) in the select statement.</p>
<p><pre class="brush: sql;">

USE Northwind
GO
UPDATE dbo.Region
SET RegionDescription = NULL
WHERE RegionID=1;
SELECT @@ERROR AS Error;

</pre></p>
<p>Run the query and see the results. I will show in another post how to use the TRY CATCH statements in T-SQL for exception handling.</p>
<p>Now I would like to demonstrate with few examples the use of the Ranking functions.Τhe first one is <span style="color:#ff00ff;">ROW_NUMBER()</span> which returns the sequential number of the row within a result set.The second one is <span style="color:#ff00ff;">RANK()</span> function and it returns the rank of each row within a result set.The third one is <span style="color:#ff00ff;">DENSERANK()</span> function and it returns the rank of each row within a result set without any gaps in the ranking.The fourth one is <span style="color:#ff00ff;">NTILE()</span> function and it distributes the rows in an ordered partition into a specified number of groups.Basically is like saying that I have 1000 values and I want to distribute them into 10 groups. NTILE returns the number of the group to which the row belongs.</p>
<p><strong>ProductName                                               UnitPrice           RANK        DENSERANK</strong></p>
<p>Schoggi Schokolade                                                  43.90                       11                     11<br />
Vegie-spread                                                             43.90                       11                     11<br />
Northwoods Cranberry Sauce                                 40.00                       <strong>1 3</strong>                  <strong> 12</strong><br />
Alice Mutton                                                              39.00                       <strong>14</strong>                    <strong>13</strong><br />
For example when we run the T-SQL below we get some results like the ones below. Note the difference in the results for <strong>RANK</strong> and <strong>DENSERANK</strong> functions.</p>
<p><pre class="brush: sql;">

USE Northwind
GO

SELECT ProductName, UnitPrice,
ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS RowNumber

FROM dbo.Products
ORDER BY UnitPrice DESC;

SELECT ProductName, UnitPrice,
RANK() OVER (ORDER BY UnitPrice DESC) AS Rank
FROM dbo.Products
ORDER BY UnitPrice DESC;

SELECT ProductName, UnitPrice,

DENSE_RANK() OVER (ORDER BY UnitPrice DESC) AS DenseRank,

FROM dbo.Products
ORDER BY UnitPrice DESC;

SELECT ProductName, UnitPrice,
NTILE(10) OVER (ORDER BY UnitPrice DESC) AS NTILE 10
FROM dbo.Products
ORDER BY UnitPrice DESC;

</pre></p>
<p>Run the query and see the results.I have an example for each of the ranking functions.</p>
<p>Now I would like to talk about some functions that have to do with <strong>NULL</strong> values.The <span style="color:#ff00ff;">ISNULL()</span> function replaces NULL with the specified replacement value.Another useful function when working with NULL is the <span style="color:#ff00ff;">NULLIF()</span> function that returns a null value if the two specified expressions are equal . NULL values are not part of aggregate operations.For example if we want to find the average of the Units in stock for our products we would like to exclude the products with <strong>0</strong> units in our inventory.So we would like to have those 0 values convereted to <strong>NULL</strong>. Have a look at the second example below.</p>
<p>The other function I would like to talk is <span style="color:#ff00ff;">COALESCE()</span> function which helps us to find the first nonnull expression among its arguments.Have a look at the third example where we want to find the first value that is non null in the <strong>Region</strong> and <strong>Postal</strong> columns of the Suppliers table.. If none of the values are null the first value is returned.</p>
<p><pre class="brush: sql;">

USE Northwind
go

SELECT CompanyName, City, ISNULL(Region,'Not Known') AS Region
FROM dbo.Suppliers

SELECT AVG(NULLIF(UnitsInStock, 0)) FROM dbo.Products;
-- instead of --
SELECT AVG(UnitsInStock) FROM dbo.Products;

SELECT CompanyName, Region, PostalCode,
COALESCE(Region, PostalCode) AS 'Region-PostalCode'
FROM dbo.Suppliers;

</pre></p>
<p>Run the query and see the results!!!!</p>
<p>In another post of mine I will show you how to create user defined functions.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/builtin-functions/'>builtin functions</a>, <a href='https://dotnetstories.wordpress.com/tag/t-sql/'>T-SQL</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1385/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1385/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1385/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1385/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1385/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1385/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1385/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1385/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1385&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/09/30/using-built-in-functions-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Looking into Views in SQL Server</title>
		<link>https://dotnetstories.wordpress.com/2011/09/19/looking-into-views-in-sql-server/</link>
		<comments>https://dotnetstories.wordpress.com/2011/09/19/looking-into-views-in-sql-server/#comments</comments>
		<pubDate>Mon, 19 Sep 2011 18:44:02 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Sql Server 2005]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[encrypting views]]></category>
		<category><![CDATA[Indexed Views]]></category>
		<category><![CDATA[Views]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1342</guid>
		<description><![CDATA[In this post I would like to look into Views in SQL Server.

As always I will demonstrate all the various concepts with hands on examples.

I know that all these concepts are well documented elsewhere. I will try to show all these with step by step instructions and many screenshots.

Many people have found useful my style of posting. They feel they can follow the steps and master the technology.

Views have many advantages and when used correctly can benefit our applications.Please note that I will use T-SQL to create/alter/drop views. I will not use SSMS wizzards and graphic tools.

Views are virtual tables.What is stored in SQL Server as a distinct object is the definition of the view(SELECT statement) and nothing else. Some people refer to views as a stored query producing a virtual table.The data that is accessible through the view is not stored in the database.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1342&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to look into <strong>Views</strong> in SQL Server.</p>
<p>As always I will demonstrate all the various concepts with hands-on examples.</p>
<p>I know that all these concepts are well documented elsewhere. I will try to look into views with step by step instructions and many screenshots.</p>
<p>Many people have found useful my style of posting. They feel they can follow the steps and master the technology.</p>
<p><strong>Views</strong> have many advantages and when used correctly can benefit our applications.Please note that I will use T-SQL to create/alter/drop views. I will not use SSMS wizzards and graphic tools.</p>
<p><strong>Views are virtual tables</strong>.What is stored in SQL Server as a distinct object is the definition of the view(SELECT statement) and nothing else. Some people refer to views as a stored query producing a virtual table.The data that is accessible through the view is not stored in the database.</p>
<p>View can provide data to client applications.We use them to customise data with different filters and sorts for different users or different applications. The end user or application do not have to know the structure of the data. We can restrict users to specific rows and columns of a table so they do not have access to unecessary or sensitive data. Many times we use views to provide aggregate data to the user and join columns from multiple tables so that they look like a single table.We can also use views to partition data.</p>
<p>One thing many people do not know is that a user or a role that someone else has granted them access to a particular view can have access to the underlying data even if that user or role does not have explicit access to the underlying tables.So permissions granted for a view supersede permissions revoked for the underlying tables.</p>
<p>Now let&#8217;s write some views. We need an instance of SQL Server runing in our machine. I have SQL Server 2008 R2 Developer edition.You can use any edition of SQL Server you might have installed in your machine.We need a database as well. I will use the Northwind database.</p>
<p>You can download and install the free <strong>SQL Server Express</strong> edition from <a href="http://www.microsoft.com/express/Database/" target="_blank">here</a>. If you need the installation scripts for the sample Northwind database, click <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=23654" target="_blank">here</a></p>
<p>There are some rules/restrictions regarding creating views.</p>
<ul>
<li>You cannot have an <strong>ORDER BY</strong> clause unless there is a <strong>TOP</strong> or <strong>FOR XML</strong> clause present</li>
<li>Obviously the name of the view must follow all the rules for identifiers and must be unique for each schema in the database</li>
<li>Nested views cannot exceed 32 levels</li>
<li>Views cannot have rules or defaults</li>
<li>You can have only <strong>INSTEAD OF</strong> triggers applied to views</li>
<li>You cannot create temporary views or views on temporary tables</li>
<li><strong>COMPUTE</strong>,<strong>COMPUTE BY</strong> on <strong>INTO</strong> clauses are not allowed in views</li>
</ul>
<p>We can create views using the SSMS designers or use the Query editor and type raw T-SQL.I will use the later method.</p>
<p>1) Launch SQL Server Management Studio and connect to the local instance of SQL Server.</p>
<p>2) We will create a view that selects every product in the &#8220;Products&#8221; table with a <em>unit price higher than the average unit price</em></p>
<p>If you want to see the full definition of how to create a view click <a href="http://msdn.microsoft.com/en-us/library/ms187956.aspx">here</a></p>
<p><pre class="brush: sql;">
USE Northwind
GO

IF OBJECT_ID ('[Products_Above_Average_Price]', 'V') IS NOT NULL
 DROP VIEW Products_Above_Average_Price ;
 GO

CREATE  VIEW [Products_Above_Average_Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice&gt;(SELECT AVG(UnitPrice) FROM Products)

SELECT * FROM Products_Above_Average_Price

</pre></p>
<p>This is a very easy to create a view. Copy the code and paste in the query window in the SSMS. Run the query and see the results.</p>
<p>Let&#8217;s create another view. In this view we are looking to find the customers with the most orders.</p>
<p><pre class="brush: sql;">

USE Northwind
go

IF OBJECT_ID ('[vwCustomersTopTwenty ]', 'V') IS NOT NULL
DROP VIEW vwCustomersTopTwenty  ;
GO

CREATE VIEW dbo.vwCustomersTopTwenty
AS
SELECT TOP (20) WITH TIES
c.CustomerID,
c.CompanyName,
COUNT(*) AS NumOrders
FROM dbo.Customers AS c
INNER JOIN dbo.Orders AS o
ON c.CustomerID=o.CustomerID
GROUP BY c.CustomerID, c.CompanyName
ORDER BY NumOrders DESC;
GO

SELECT * FROM dbo.vwCustomersTopTwenty

</pre></p>
<p>This is a very easy to create a view. Copy the code and paste in the query window in the SSMS. Run the query and see the results.</p>
<p>We can see the newly created views in the object explorer. Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/view1a.jpg"><img class="aligncenter size-full wp-image-1357" title="view1a" src="http://dotnetstories.files.wordpress.com/2011/09/view1a.jpg?w=460&#038;h=259" alt="" width="460" height="259" /></a><a href="http://dotnetstories.files.wordpress.com/2011/09/view11.jpg"><br />
</a><a href="http://dotnetstories.files.wordpress.com/2011/09/view1.jpg"><br />
</a>You can select a view and then  right-click on it. You can do various things. You can delete, rename an existing view. You can can create a new view.You can see the design of the existing view.You can select the top 1.000 rows.You can also script the view and see the T-SQL for creating,altering,dropping the view.</p>
<p>Now I would like to show you how to encrypt a view. Sometimes we need to encrypt the defintion of the view.</p>
<p><pre class="brush: sql;">
CREATE VIEW dbo.EncryptedView
WITH ENCRYPTION
AS
SELECT LastName, FirstName,city
FROM dbo.Employees
WHERE City='London';
GO
SELECT * FROM EncryptedView;

</pre><br />
<pre class="brush: sql;">
EXEC sp_helptext 'dbo.EncryptedView';
</pre></p>
<p>If we try to get the T-SQL statement that is the definition of the view, we will fail. That is what I try to do with the statement above but I fail.I use the <strong>sp_helptext</strong> system stored procedure to do that.</p>
<p>This is what I get when I execute the code above.</p>
<p><em>The text for object &#8216;dbo.EncryptedView&#8217; is encrypted.</em></p>
<p>Run the T-SQL code above so you can verify yourself what I have just told you and to see the result of the view.</p>
<p>We can also alter the definition of a view. We can do that using the <strong>ALTER</strong> keyword.In the following example I am altering the previous view so I can add the &#8220;WITH CKECK OPTION&#8221;. With this option, we force all data modification statements executed against the view to follow the criteria set within <strong>select statement</strong></p>
<p><pre class="brush: sql;">
alter VIEW dbo.EncryptedView
WITH ENCRYPTION
AS
SELECT LastName, FirstName,city
FROM dbo.Employees
WHERE City='London'
WITH CHECK OPTION;
GO
</pre></p>
<p>Now I will try to update the data through the view. I will try to update the data in the view by setting the values in the <strong>city</strong> column to  &#8220;Paris&#8221;</p>
<p><pre class="brush: sql;">
UPDATE dbo.EncryptedView
SET city = 'paris';

GO
</pre></p>
<p>When I run the statement above I get an error, as expected. The error I get follows.</p>
<p><span style="color:#ff0000;">&#8220;Msg 550, Level 16, State 1, Line 1</span><br />
<span style="color:#ff0000;"> The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.</span><br />
<span style="color:#ff0000;"> The statement has been terminated.&#8221;</span></p>
<p>Another option many people use when creating views is &#8220;SCHEMABINDING&#8221;.</p>
<p><strong>SCHEMABINDING</strong> is an option that when applied to Views forces SQL Server to create dependencies between any objects referenced within the View and the View. We cannot  have their definitions altered whilst the schema-bound View exists. This ensures the integrity of the View.</p>
<p><pre class="brush: sql;">
CREATE VIEW vwSample

With SCHEMABINDING

As

SELECT

CustomerID,

CompanyName,

ContactName

FROM DBO.CUSTOMERS -- Two part name [ownername.objectname]

GO

SELECT * FROM VWSAMPLE

ALTER TABLE dbo.Customers

DROP COLUMN CompanyName
</pre></p>
<p>I create the view vwSample with the<strong> schemabinding</strong> on.Note that I use the schema-table name (dbo.Customers) when referencing the table.</p>
<p>When I try to alter the definition of the table by dropping a column that is referenced in the view (CompanyName) I get an error:</p>
<p><span style="color:#ff0000;">&#8220;Msg 5074, Level 16, State 1, Line 1</span><br />
<span style="color:#ff0000;"> The object &#8216;vwSample&#8217; is dependent on column &#8216;CompanyName&#8217;.&#8221;</span></p>
<p>You can also use the <strong>Template Explorer</strong> to create a view. Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/view-template1.jpg"><img class="aligncenter size-full wp-image-1361" title="view-template" src="http://dotnetstories.files.wordpress.com/2011/09/view-template1.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>We can drop the view, by using T-SQL</p>
<p><pre class="brush: sql;">

DROP VIEW [dbo].[vwCustomersTopTwenty]

</pre></p>
<p>We can use another bit of T-SQL code to drop the database.We query the <strong>sys.views</strong> system view to see if the view exists and thenwe drop the view.</p>
<p><pre class="brush: sql;">

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwCustomersTopTwenty]'))
DROP VIEW [dbo].[vwCustomersTopTwenty]
GO

</pre></p>
<p>We can use views to update data. When data is updated through the view changes will affect only one table.</p>
<p>Columns that are based on expressions, set operators, aggregate functions cannot be updated.</p>
<p>I will create a view below.I get data from both the <strong>Categories</strong> and <strong>Product</strong> tables. Then I have 3 update statements. The first two update statements will succeed but the last one will fail.The first two updates will attempt to change the data for one table only. The third one will fail as it attempts to update data in two tables. This is the error messageI get when I try to update multiple base tables.</p>
<p><span style="color:#ff0000;">&#8220;View or function &#8216;dbo.vwProductInCategories&#8217; is not updatable because the modification affects multiple base tables.&#8221;</span></p>
<p><pre class="brush: sql;">

CREATE VIEW dbo.vwProductInCategories
AS
SELECT  C.CategoryName ,
C.Description ,
P.ProductID ,
P.ProductName ,
p.QuantityPerUnit
FROM    dbo.Products AS P
INNER JOIN dbo.Categories AS C ON P.CategoryID = C.CategoryID
GO

SELECT * FROM dbo.vwProductInCategories

-- This will work
UPDATE dbo.vwProductInCategories
SET ProductName = 'Genen Good'
WHERE ProductID = 15

-- This will work
UPDATE dbo.vwProductInCategories
SET CategoryName = 'Meat'
WHERE ProductID = 19

-- This will not work
UPDATE dbo.vwProductInCategories
SET ProductName = 'chocolate', CategoryName = 'Milk'
WHERE ProductID = 21

</pre></p>
<p>Run the T-SQL above to see the results for yourself.</p>
<p>We can create indexed views as well.  We all know that Indexes enhance performance. We can have indexes on one or multiple columns and we can have faster searches and sorting through the indexes. When we index views we materialise the view. That means the view data is stored as well along with the definition of the view.Ιndexed views boost performance when we have complex aggregations or joins.We must use the <strong>SCHEMABINDING</strong> option.</p>
<p>Indexed view definitions must use the two <strong>part name</strong> (schemaname.tablename).Before I create a view I will write a T-SQL query that performs some aggregate calculation.</p>
<p>I also use the &#8220;SET STATISTICS IO ON&#8221; , which causes SQL Server to display information regarding the amount of disk activity generated by Transact-SQL statements.</p>
<p><pre class="brush: sql;">

SET STATISTICS IO ON

SELECT SUM(UnitPrice*Quantity*(1.00-Discount)) AS Sales,
OrderDate, ProductID
FROM dbo.[Order Details] OD JOIN dbo.Orders O
ON OD.OrderID = O.OrderID
WHERE  ProductID in (7, 89, 22, 34)
AND OrderDate &gt;= '05/01/1998'
GROUP BY OrderDate, ProductID
ORDER BY Sales DESC;

</pre></p>
<p>Have a look at the picture below to see the logical and physical reads required.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/statsio.jpg"><img class="aligncenter size-full wp-image-1370" title="statsio" src="http://dotnetstories.files.wordpress.com/2011/09/statsio.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>Have a look also at the execution plan generated for the above query.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/execplan1.jpg"><img class="aligncenter size-full wp-image-1372" title="execplan1" src="http://dotnetstories.files.wordpress.com/2011/09/execplan1.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>I create a view in the following example. I get the Product sales by date.</p>
<p><pre class="brush: sql;">
CREATE VIEW dbo.vwSalesByProductByDate
WITH SCHEMABINDING
AS
SELECT OrderDate, ProductID,
SUM(UnitPrice*Quantity*(1.00-Discount)) AS Sales,
COUNT_BIG(*) AS LineItemCount
FROM  dbo.[Order Details] OD JOIN dbo.Orders O
ON OD.OrderID=O.OrderID
GROUP BY  OrderDate, ProductID
GO

SELECT * FROM dbo.vwSalesByProductByDate
GO

EXEC sp_spaceused 'dbo.vwSalesByProductByDate'

--Create the index on the view.

CREATE  UNIQUE CLUSTERED INDEX idx_vwSalesByProductByDate
ON dbo.vwSalesByProductByDate (OrderDate, ProductID)
GO

EXEC sp_spaceused 'dbo.vwSalesByProductByDate'
</pre></p>
<p>Then I select the data from the view. Then I use the <strong>sp_spaceused</strong> stored procedure (Displays the number of rows, disk space reserved, and disk space used by a table, indexed view) to see the disk space reserved for the results.</p>
<p>Have a look at the picture below to see the results of that statement.So now we can prove thet data is materialised in the view.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/spaceused.jpg"><img class="aligncenter size-full wp-image-1367" title="spaceused" src="http://dotnetstories.files.wordpress.com/2011/09/spaceused.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>Then I create a clustered index on that view, so I have an indexed view. Then I use the <strong>sp_spaceused</strong> stored procedure  to see the disk space reserved for the results.They are different.</p>
<p>Have a look at the picture below and see the results of that statement.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/spaceused1.jpg"><img class="aligncenter size-full wp-image-1368" title="spaceused1" src="http://dotnetstories.files.wordpress.com/2011/09/spaceused1.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>Now we need to run the query again (the one we created just before we created the view)</p>
<p><pre class="brush: sql;">

SET STATISTICS IO ON

SELECT SUM(UnitPrice*Quantity*(1.00-Discount)) AS Sales,
OrderDate, ProductID
FROM dbo.[Order Details] OD JOIN dbo.Orders O
ON OD.OrderID = O.OrderID
WHERE  ProductID in (7, 89, 22, 34)
AND OrderDate &gt;= '05/01/1998'
GROUP BY OrderDate, ProductID
ORDER BY Sales DESC;

</pre></p>
<p>Have a look at the picture below to see the logical and physical reads required.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/statsio1.jpg"><img class="aligncenter size-full wp-image-1373" title="statsio1" src="http://dotnetstories.files.wordpress.com/2011/09/statsio1.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>Have a look also at the execution plan generated for the above query.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/09/execplan2.jpg"><img class="aligncenter size-full wp-image-1374" title="execplan2" src="http://dotnetstories.files.wordpress.com/2011/09/execplan2.jpg?w=460&#038;h=247" alt="" width="460" height="247" /></a></p>
<p>Compare your findings with the relevant results befere we created the indexed view.  You can see now clearly that the query is using the clustered index and there is a  <strong>huge performance gain.</strong></p>
<p>Do not use indexed views when the data in the underlying tables changes frequently.</p>
<p>In this final part I would like to talk about partitioned views.</p>
<p>A partitioned view is a database object that unions together tables with certain attributes.Tables with the same structure are combined to provide a unified view of a set of data, but that are divided on a &#8220;partitioning column.&#8221;</p>
<p>I will create a new database called &#8220;sample&#8221;.I will have 3 tables and I will populate them with data. The tables are divided/partitioned into the &#8220;city&#8221; column. The tables are <strong>CustomersParis,CustomersAthens,CustomersLondon</strong></p>
<p><pre class="brush: sql;">

Create database [sample]
GO

USE [sample]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[CustomersParis](
[CustomerID] [char](5) NOT NULL,
[CompanyName] [varchar](40) NOT NULL,
[ContactName] [varchar](30) NULL,
[Address] [varchar](60) NULL,
[City] [varchar](15) NOT NULL,
[Region] [nvarchar](15) NULL,
[PostalCode] [nvarchar](10) NULL,
[Country] [nvarchar](15) NOT NULL,
[Phone] [nvarchar](24) NULL,
CONSTRAINT [PK_Cust1] PRIMARY KEY CLUSTERED
(
[City] ASC,
[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[CustomersParis]  WITH CHECK ADD CHECK  (([City]='Paris'))
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[CustomersLondon](
[CustomerID] [char](5) NOT NULL,
[CompanyName] [varchar](40) NOT NULL,
[ContactName] [varchar](30) NULL,
[Address] [varchar](60) NULL,
[City] [varchar](15) NOT NULL,
[Region] [nvarchar](15) NULL,
[PostalCode] [nvarchar](10) NULL,
[Country] [nvarchar](15) NOT NULL,
[Phone] [nvarchar](24) NULL,
CONSTRAINT [PK_Cust2] PRIMARY KEY CLUSTERED
(
[City] ASC,
[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[CustomersLondon]  WITH CHECK ADD CHECK  (([City]='London'))
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[CustomersAthens](
[CustomerID] [char](5) NOT NULL,
[CompanyName] [varchar](40) NOT NULL,
[ContactName] [varchar](30) NULL,
[Address] [varchar](60) NULL,
[City] [varchar](15) NOT NULL,
[Region] [nvarchar](15) NULL,
[PostalCode] [nvarchar](10) NULL,
[Country] [nvarchar](15) NOT NULL,
[Phone] [nvarchar](24) NULL,
CONSTRAINT [PK_Cust] PRIMARY KEY CLUSTERED
(
[City] ASC,
[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[CustomersAthens]  WITH CHECK ADD CHECK  (([City]='Athens'))
GO

</pre></p>
<p>Download the script from <a href="http://nksolutions.gr/portals/0/sample.zip">here</a>. In this .sql file you will find the script to create the database, the tables and populate the tables with data.</p>
<p>Run the script to create the tables and to populate them.</p>
<p>Now we will create the partiotioned view.We  union those tables back together using a partitioned view.</p>
<p><pre class="brush: sql;">

USE [sample]

CREATE VIEW PartitionedView AS
SELECT * FROM dbo.CustomersAthens
UNION ALL
SELECT * FROM dbo.CustomersLondon
UNION ALL SELECT * FROM
dbo.CustomersParis GO

SELECT * FROM PartitionedView
WHERE city ='athens'

</pre></p>
<p>Run the T-SQL code to create the view and to use the view to query the underlying tables.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/sql-server-2005/'>Sql Server 2005</a>, <a href='https://dotnetstories.wordpress.com/category/sql-server-2008/'>SQL Server 2008</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/encrypting-views/'>encrypting views</a>, <a href='https://dotnetstories.wordpress.com/tag/indexed-views/'>Indexed Views</a>, <a href='https://dotnetstories.wordpress.com/tag/views/'>Views</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1342/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1342/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1342/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1342&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/09/19/looking-into-views-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/view1a.jpg" medium="image">
			<media:title type="html">view1a</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/view-template1.jpg" medium="image">
			<media:title type="html">view-template</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/statsio.jpg" medium="image">
			<media:title type="html">statsio</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/execplan1.jpg" medium="image">
			<media:title type="html">execplan1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/spaceused.jpg" medium="image">
			<media:title type="html">spaceused</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/spaceused1.jpg" medium="image">
			<media:title type="html">spaceused1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/statsio1.jpg" medium="image">
			<media:title type="html">statsio1</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/09/execplan2.jpg" medium="image">
			<media:title type="html">execplan2</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Type Converters in WPF</title>
		<link>https://dotnetstories.wordpress.com/2011/07/31/using-type-converters-in-wpf/</link>
		<comments>https://dotnetstories.wordpress.com/2011/07/31/using-type-converters-in-wpf/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 00:37:15 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c# 3.0]]></category>
		<category><![CDATA[c# 4.0]]></category>
		<category><![CDATA[general .net]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[VS 2010]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>
		<category><![CDATA[type conversions]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1320</guid>
		<description><![CDATA[In this post I would like to talk/show you how to implement type conversions in WPF.

We must talk a little bit for Binding in WPF before we move on to explain why we use type converters and show a hands on example.

So what is Binding in WPF? In WPF we can bind any property of any object to any other property of some other object.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1320&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk/show you how to implement type conversions in WPF.</p>
<p>We must talk a little bit for <strong>Binding</strong> in WPF before we move on to explain why we use <strong>type converters</strong> and show a hands on example.</p>
<p>So what is Binding in WPF? In WPF we can bind any property of any object to any other property of some other object.</p>
<p>Binding is typically done in XAML by using the <strong>Binding markup extensions</strong>.For example</p>
<p><strong>&lt;TextBox Text=&#8221;{Binding Path=Property}&#8221; /&gt;</strong></p>
<p>The syntax above implies that we do not set the value of the <strong>Target</strong> to some literal value.</p>
<p>When we use binding in XAML , what really happens is that in runtime we create an instance of the <strong>Binding</strong> class, setting various properties that affect its behaviour.</p>
<p>We can create bindings in code as well. Basically in WPF it is entirely up to the developer if he will write any XAML code to implement the application.</p>
<p>I strongly recommend to use the <strong>XAML approach</strong>.</p>
<p>In binding we have a <strong>Target</strong> object/element. In order for binding to be possible, that object/element must inherit from (be an object of type) <strong>FrameworkElement</strong>.</p>
<p>In the previous small example, <strong>TextBox is a Control</strong> and inherits from <strong>FrameworkElement</strong> class. All controls inherit from that class. So all the WPF controls and their properties/attributes can be part of a Binding situation.</p>
<p>Speaking of properties/attibutes the <strong>Target</strong> property must be a <strong>DepenencyProperty</strong>. So the &#8220;Text&#8221; property in the previous example is a <strong>Dependency</strong> property.</p>
<p>Obviously we need to have some sort of source to bind to.Any .Net object can be a binding source.We can display customers from a customer object in a ListBox control.</p>
<p>We can bind to datasets and entity classes. We can bind to properties of other elements. For example we can bind the value of a <strong>Slider</strong> control to a <strong>TextBlock</strong>.</p>
<p>So we can bind from various sources. Basically any<strong> CLR object</strong> can play the role of the <strong>Binding source</strong>.</p>
<p>We can specify the mode of how data flows between the data and the source. So we have</p>
<ul>
<li>TwoWay &#8211; Data flows both directions</li>
<li>OneWay &#8211; Data flows only from the source to the target</li>
<li>OneTime &#8211; Data flows only from the source to the target but we bind only once to the source. It is a useful only if we do not expect the source to change.</li>
<li>OneWayToSource &#8211; Data flows from the target to the source, for example, we have a textbox that we tell it not to bother read the initial value from the source but update the source with any value the user types in</li>
</ul>
<p>In order to have a better idea how binding works have a look at the picture below</p>
<p><a href="http://dotnetstories.files.wordpress.com/2011/07/binding.png"><img class="aligncenter size-full wp-image-1326" title="binding" src="http://dotnetstories.files.wordpress.com/2011/07/binding.png?w=460&#038;h=220" alt="" width="460" height="220" /></a></p>
<p>So where value converters figure in the above scenario? In many cases the binding source is of a type that needs to be converted so that the target property can bind to.</p>
<p>Value converters are instances of classes that implement the <strong>IValueConverter</strong> interface.</p>
<p>I will create a hands on example to demonstrate how to use type converters in WPF.</p>
<p>1) Launch Visual Studio 2010/2008. From the available templates, choose a <strong>WPF application</strong> template.Choose an appropriate name for your application. I have named it <strong>WpfApplicationConverters</strong>. I will use C# as the development language.</p>
<p>2) We will create a simple WPF application , with a button, 2 comboboxes and a border. The first combobox will load with various font families.Every time the user will select a different font from the combobox the <strong>FontFamily</strong> attribute of the <strong>Button</strong> element will reflect those changes.</p>
<p>3) The second combobox will load with integer values ( 1-10). Every time the user selects a different value from this combobox then the <strong>BorderThickness</strong> property of the <strong>Border</strong> element will change to reflect this change.</p>
<p>In both cases we need to need some sort of value conversions. The values in the FontFamily Combobox are of type <strong>String</strong> and we need to convert it to FontFamily type.</p>
<p>The values of the second combobox has integer values.These values need to be mapped to another type, the <strong>BorderThickness</strong> property.The <strong>BorderThickness</strong> property has four values.</p>
<p>We need to have some sort of classes where we make the conversion.</p>
<p>4) We need to write the UI first. The XAML for the UI follows</p>
<p><pre class="brush: xml;">
&lt;Window x:Class=&quot;WpfApplicationConverters.MainWindow&quot;
xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot;&gt;

&lt;StackPanel&gt;

&lt;Border BorderBrush=&quot;DarkCyan&quot; &gt;

&lt;StackPanel&gt;

&lt;Grid Height=&quot;210&quot;&gt;

&lt;Button FontSize=&quot;16&quot;  Content=&quot;I am a button&quot;  Height=&quot;34&quot;  Name=&quot;button1&quot; Width=&quot;164&quot;   Margin=&quot;166,41,161,135&quot; /&gt;

&lt;ComboBox Height=&quot;32&quot; Name=&quot;BorderThicknessComboBox&quot; Width=&quot;120&quot; Margin=&quot;82,128,289,50&quot;   /&gt;

&lt;ComboBox Name=&quot;FontFamilyComboBox&quot; Width=&quot;136&quot; Height=&quot;34&quot;  Margin=&quot;243,128,112,48&quot;&gt;&lt;/ComboBox&gt;

&lt;/Grid&gt;

&lt;/StackPanel&gt;

&lt;/Border&gt;

&lt;/StackPanel&gt;

&lt;/Window&gt;
</pre></p>
<p>5) Run your application and make sure it works.</p>
<p>Now I need to populate the comboxoxes with the initial values. I will use the <strong>Loaded</strong> event of each control.</p>
<p>I will write the code in the <strong>MainWindow.xaml.cs</strong> file.</p>
<p><pre class="brush: csharp;">
using System.Windows;
using System.Linq;
using System.Collections.Generic;

namespace WpfApplicationConverters
{
/// &lt;summary&gt;
/// Interaction logic for MainWindow.xaml
/// &lt;/summary&gt;
public partial class MainWindow : Window
{
public MainWindow()
{

InitializeComponent();
}

private void ThicknessComboBoxSetUp()
{
BorderThicknessComboBox.ItemsSource = Enumerable.Range(1, 10);
BorderThicknessComboBox.SelectedIndex = 0;
}

private void FillComboBoxWithFontFamilies()
{

FontFamilyComboBox.ItemsSource = new List&lt;string&gt;() { &quot;Arial&quot;, &quot;Arial Black&quot;, &quot;Comic Sans MS&quot;, &quot;Courier New&quot;, &quot;Georgia&quot;,
            &quot;Lucida Sans Unicode&quot;, &quot;Times New Roman&quot;, &quot;Trebuchet MS&quot;, &quot;Verdana&quot; };
FontFamilyComboBox.SelectedIndex = 0;
}

private void FontFamilyComboBox_Loaded(object sender, RoutedEventArgs e)
{
FillComboBoxWithFontFamilies();
}

private void BorderThicknessComboBox_Loaded(object sender, RoutedEventArgs e)
{
ThicknessComboBoxSetUp();
}
</pre></p>
<p>6) The code above is very easy to follow and understand.I create two methods <strong>ThicknessComboBoxSetup()</strong> and <strong>FillComboBoxWithFontFamilies()</strong> and then use these methods in the <strong>BorderThicknessComboBox_Loaded</strong> and <strong>FontFamilyComboBox_Loaded </strong>event handling routines.</p>
<p>Obviously you need to change the XAML code as well.</p>
<p><pre class="brush: xml;">

&lt;ComboBox Height=&quot;32&quot; Name=&quot;BorderThicknessComboBox&quot; Width=&quot;120&quot; Margin=&quot;82,128,289,50&quot; Loaded=&quot;BorderThicknessComboBox_Loaded&quot;/&gt;

&lt;ComboBox Name=&quot;FontFamilyComboBox&quot; Width=&quot;136&quot; Height=&quot;34&quot;  Margin=&quot;243,128,112,48&quot; Loaded=&quot;FontFamilyComboBox_Loaded&quot; /&gt;

</pre></p>
<p>7) Run your application and make sure everything works as expected. Now we will implement the type value converters.</p>
<p>Add a new item to the project, a class file. Name it <strong>FontFamilyConversions.cs. </strong>The code for the class follows<strong><br />
</strong></p>
<p><pre class="brush: csharp;">
using System.Windows.Media;
using System.Windows.Data;

namespace WpfApplicationConverters
{
class FontFamilyConversions: IValueConverter
{

public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FontFamily fontfamily = new FontFamily(&quot;Verdana&quot;);
if (value != null)
{
fontfamily = new FontFamily(value.ToString());
}
return fontfamily;
}

public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}

</pre></p>
<p>8) The code above is easy to understand. I implement the <strong>IValueConverter</strong> interface and the to methods, <strong>Convert</strong> and <strong>ConvertBack </strong>methods.<strong><br />
</strong></p>
<p>I actually implement only the <strong>Convert</strong> method.I convert the string value to a new value of type <strong>FontFamily</strong>.</p>
<p>9) Add a new class to the project so you can perform the second conversion.Name it <strong>IntergerToThicknessConversions.cs</strong></p>
<p>The conversion in this case will be from a type integer to a type <strong>Thickness</strong>.The code for the class follows<strong></strong></p>
<p><pre class="brush: csharp;">

using System;
using System.Windows.Data;
using System.Windows;

namespace WpfApplicationConverters
{
class IntergerToThicknessConversions:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Thickness thicknessValue = new Thickness(0);

if (value != null)
{
thicknessValue =
new Thickness(System.Convert.ToInt32(value));
}
return thicknessValue;

}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
</pre></p>
<p>10) Now we need to hook these classes with the XAML.The first thing I do is to add the namespace of all the classes in our project.</p>
<pre> xmlns:local="clr-namespace:WpfApplicationConverters"</pre>
<p>Then I need to define the classes that implement the type conversions. I do that inside a Window.Resources element.</p>
<pre>&lt;Window.Resources&gt;
    &lt;local:FontFamilyConversions x:Key="FontFamilyConversions" /&gt;
    &lt;local:IntergerToThicknessConversions x:Key="IntergerToThicknessConversions" /&gt;
&lt;/Window.Resources&gt;</pre>
<p>The last thing is to bind the target properties to the Comboboxes <strong>selected values</strong> and the <strong>Conversion</strong> classes.  I use markup extensions in XAML. I bind to the appropriate combobox for each case, then set the <strong>Path</strong> property to the <strong>SelectedValue</strong>. For the conversions I use the Converter attribute to bind to the appropriate conversion classes.</p>
<pre>&lt;Border BorderBrush="DarkCyan"  <strong>BorderThickness="{Binding ElementName=BorderThicknessComboBox, </strong>
<strong>Path=SelectedValue, Converter={StaticResource IntergerToThicknessConversions}}"</strong>&gt;

&lt;Button FontSize="16"  Content="I am a button"  Height="34"  Name="button1" Width="164" 
FontFamily=<strong>"{Binding SelectedValue,ElementName=FontFamilyComboBox, Mode=OneWay,  
 Converter={StaticResource FontFamilyConversions}}"</strong> Margin="166,41,161,135" /&gt;</pre>
<p>The whole code for the UI is this</p>
<p><pre class="brush: xml;">

&lt;Window x:Class=&quot;WpfApplicationConverters.MainWindow&quot;
xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot;
xmlns:local=&quot;clr-namespace:WpfApplicationConverters&quot;
&gt;
&lt;Window.Resources&gt;
&lt;local:FontFamilyConversions x:Key=&quot;FontFamilyConversions&quot; /&gt;
&lt;local:IntergerToThicknessConversions x:Key=&quot;IntergerToThicknessConversions&quot; /&gt;
&lt;/Window.Resources&gt;
&lt;StackPanel&gt;

&lt;Border BorderBrush=&quot;DarkCyan&quot;  BorderThickness=&quot;{Binding ElementName=BorderThicknessComboBox, Path=SelectedValue,
Converter={StaticResource IntergerToThicknessConversions}}&quot;&gt;

&lt;StackPanel&gt;

&lt;Grid Height=&quot;210&quot;&gt;

&lt;Button FontSize=&quot;16&quot;  Content=&quot;I am a button&quot;  Height=&quot;34&quot;  Name=&quot;button1&quot; Width=&quot;164&quot;  FontFamily=&quot;{Binding SelectedValue, ElementName=FontFamilyComboBox, Mode=OneWay, Converter={StaticResource FontFamilyConversions}}&quot; Margin=&quot;166,41,161,135&quot; /&gt;

&lt;ComboBox Height=&quot;32&quot; Name=&quot;BorderThicknessComboBox&quot; Width=&quot;120&quot; Margin=&quot;82,128,289,50&quot;  Loaded=&quot;BorderThicknessComboBox_Loaded&quot;  /&gt;

&lt;ComboBox Name=&quot;FontFamilyComboBox&quot; Width=&quot;136&quot; Height=&quot;34&quot;  Loaded=&quot;FontFamilyComboBox_Loaded&quot; Margin=&quot;243,128,112,48&quot;&gt;&lt;/ComboBox&gt;
&lt;/Grid&gt;
&lt;/StackPanel&gt;
&lt;/Border&gt;
&lt;/StackPanel&gt;
&lt;/Window&gt;&lt;/pre&gt;
</pre></p>
<p>Run your application and change the <strong>Font Family</strong> for the button and the <strong>Thickness</strong> of the border. Make sure everything works as expected.</p>
<p>Email me if you need the source code.<br />
Hope it helps !!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/c-30/'>c# 3.0</a>, <a href='https://dotnetstories.wordpress.com/category/c-4-0/'>c# 4.0</a>, <a href='https://dotnetstories.wordpress.com/category/general-net/'>general .net</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/vs-2010/'>VS 2010</a>, <a href='https://dotnetstories.wordpress.com/category/wpf/'>WPF</a>, <a href='https://dotnetstories.wordpress.com/category/xaml/'>XAML</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/type-conversions/'>type conversions</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1320/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1320/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1320/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1320&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/07/31/using-type-converters-in-wpf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/07/binding.png" medium="image">
			<media:title type="html">binding</media:title>
		</media:content>
	</item>
		<item>
		<title>An introduction to MVVM pattern using WPF</title>
		<link>https://dotnetstories.wordpress.com/2011/07/17/an-introduction-to-mvvm-pattern-using-wpf/</link>
		<comments>https://dotnetstories.wordpress.com/2011/07/17/an-introduction-to-mvvm-pattern-using-wpf/#comments</comments>
		<pubDate>Sat, 16 Jul 2011 21:03:32 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c# 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1278</guid>
		<description><![CDATA[In this post I will show you how to build a simple WPF Application using the popular and well know MVVM pattern.

I assume that you know the basics of XAML,WPF. I am going to use a hands-one example using Visual Studio and 2010.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1278&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I will show you how to build a simple WPF Application using the popular and well know MVVM (Model View View Model) pattern.</p>
<p>I assume that you know the basics of XAML,WPF. I am going to use a hands-one example using Visual Studio and 2010.</p>
<p>Before we go on and begin with our example I must say a few things about MVVM.Make a note that we can use this pattern when building Silverlight applications as well.</p>
<p>So what is MVVM? In a nutshell it is a <strong>UI Design Pattern</strong>. You do not have to explore too many things or spend too much time studying this pattern before start using it.</p>
<p>A pattern is a documented solution to a specific software problem. So <strong>MVVM</strong> being a pattern,  is a set of guidelines that makes it much easier to write WPF applications.</p>
<p>It is based on a very important software principle called <strong>seperation of concerns</strong>.By building WPF applications using <strong>MVMV</strong> we have solid maintainable code.</p>
<p>By breaking apart our application, enables us to do <strong>UI testing</strong>.</p>
<p>On top of that we have applications that ( that are built with MVVM ) are much more maintenable and extensible. We keep the designers and the developers happy!!!! Each of them can focus on their tasks and noone interferes with each other&#8217;s work.</p>
<p>Let&#8217;s have a closer look on the main components of <strong>MVVM</strong> pattern. Have a look at the picture below.It gives a high level overview of the pattern.</p>
<div id="attachment_1279" class="wp-caption aligncenter" style="width: 470px"><a href="http://dotnetstories.files.wordpress.com/2011/07/mvvm.jpg"><img class="size-full wp-image-1279" title="MVVM" src="http://dotnetstories.files.wordpress.com/2011/07/mvvm.jpg?w=460&#038;h=283" alt="MVVM Pattern" width="460" height="283" /></a><p class="wp-caption-text">MVVM Pattern</p></div>
<p>The <strong>Model</strong> has no reference to the <strong>View</strong> or the <strong>ViewModel</strong> . It does not or care about the existence of the <strong>View</strong> or the <strong>Model</strong>.</p>
<p>The <strong>Model </strong>is that data. It could be an xml file or a data access layer (e.g EF). It could be a custom object(s) representing a part of our domain.</p>
<p>The <strong>View</strong> does not have a reference to the <strong>Model</strong>. A <strong>View</strong> is defined in XAML and should not have any logic in the code-behind. It binds to the <strong>ViewModel</strong> by only using data binding.<br />
The <strong>ViewModel</strong> can be thought of as an abstraction of the <strong>View</strong>. It provides enough information about the <strong>Model</strong> data points that the <strong>View</strong> can use for data-binding. It contains Commands the <strong>View</strong> can use to interact with the <strong>Model</strong>. The <strong>ViewModel</strong> has a reference to the <strong>Model</strong>.</p>
<p>Let&#8217;s start with our hands on example.I will create a simple WPF application</p>
<p>1) Launch Visual Studio 2010 (any edition will do). Choose C# as the development language and WPF Application from the available templates.</p>
<p>2) Choose a suitable name for your application. I have named it &#8220;WpfMVVM&#8221;</p>
<p>3) Add 3 folders in your solution with the names <strong>View</strong>,<strong>Model</strong>,<strong>ViewModel</strong>.</p>
<p>4) I will use a custom object to store the data so I will add a new class to the Model folder. I will name it <strong>Footballer.cs</strong> ( yes, we will save and display footballer names ). I will add some properties on this class like  firstname,lastname,age,height,weight and another little property called SavedTime so I know when the data was last updated. So the first version of the <strong>Footballer</strong> class follows.</p>
<p><pre class="brush: csharp;">
   class Footballer
    {

        private string _firstname;

        public string FirstName
        {
            get { return _firstname; }
            set
            {
                _firstname = value;

            }
        }

        private string _lastname;

        public string LastName
        {
            get { return _lastname; }
            set
            {

                _lastname = value;

            }
        }

        private int _age;

        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;

            }
        }

        private double _height;

        public double Height
        {
            get { return _height; }
            set
            {
                _height = value;

            }
        }

        private double _weight;

        public double Weight
        {
            get { return _weight; }
            set
            {
                _weight = value;

            }
        }

        private DateTime _SavedTime;

        public DateTime SavedTime
        {
            get { return _SavedTime; }
            set
            {
                _SavedTime = value;

            }
        }

}
</pre></p>
<p>Then I need to notify my UI (View) that some of these properties changed. I do that by implementing the <strong>INotifyPropertyChanged</strong> interface.</p>
<p>Now the <strong>View</strong> is notified when there changes in the property values,since when that happens notifications are fired. This allows the <strong>View</strong> to display any changes that have been made in the object&#8217;s underlying properties. The second version of the <strong>Footballer</strong> class follows</p>
<p><pre class="brush: csharp;">

class Footballer:INotifyPropertyChanged
{

private string _firstname;

public string FirstName
{
get { return _firstname; }
set
{
_firstname = value;
OnPropertyChanged(&quot;FirstName&quot;);

}
}

private string _lastname;

public string LastName
{
get { return _lastname; }
set
{

_lastname = value;
OnPropertyChanged(&quot;LastName&quot;);
}
}

private int _age;

public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged(&quot;Age&quot;);
}
}

private double _height;

public double Height
{
get { return _height; }
set
{
_height = value;
OnPropertyChanged(&quot;Height&quot;);
}
}

private double _weight;

public double Weight
{
get { return _weight; }
set
{
_weight = value;
OnPropertyChanged(&quot;Weight&quot;);
}
}

private DateTime _SavedTime;

public DateTime SavedTime
{
get { return _SavedTime; }
set
{
_SavedTime = value;
OnPropertyChanged(&quot;SavedTime&quot;);
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string property)
{
if (PropertyChanged !=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}

}

}
</pre></p>
<p>If I want to implement data validation logic, the <strong>Model</strong> class is a good place to do it.In this case I need to implement the <strong>IDataErrorInfo</strong> interface.In this example I will add some validation for the fields &#8220;FirstName&#8221;, &#8220;Lastname&#8221;. These fields cannot be empty.</p>
<p>The third version of the <strong>Footballer</strong> class follows</p>
<p><pre class="brush: csharp;">

class Footballer:INotifyPropertyChanged,IDataErrorInfo
{

private string _firstname;

public string FirstName
{
get { return _firstname; }
set
{
_firstname = value;
OnPropertyChanged(&quot;FirstName&quot;);

}
}

private string _lastname;

public string LastName
{
get { return _lastname; }
set
{

_lastname = value;
OnPropertyChanged(&quot;LastName&quot;);
}
}

private int _age;

public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged(&quot;Age&quot;);
}
}

private double _height;

public double Height
{
get { return _height; }
set
{
_height = value;
OnPropertyChanged(&quot;Height&quot;);
}
}

private double _weight;

public double Weight
{
get { return _weight; }
set
{
_weight = value;
OnPropertyChanged(&quot;Weight&quot;);
}
}

private DateTime _SavedTime;

public DateTime SavedTime
{
get { return _SavedTime; }
set
{
_SavedTime = value;
OnPropertyChanged(&quot;SavedTime&quot;);
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string property)
{
if (PropertyChanged !=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}

}

public string Error
{
get { return null; }
}

public string this[string columnName]
{
get

{
string theerror = string.Empty;

if ((string.IsNullOrEmpty (_firstname)))
{
theerror = &quot;This field is required&quot;;
}

else if ((string.IsNullOrEmpty(_lastname)))
{
theerror = &quot;This field is required&quot;;
}
return theerror;
}
}

}
</pre></p>
<p>We will have to make some changes to the XAML (Set the ValidatesOnDataErrors=True for firstname and lastname elements) for this to work but I will show you later.</p>
<p>Νow let&#8217;s move to the <strong>ViewModel</strong> implementation. This model must have properties that expose instances of the <strong>Model</strong> objects.</p>
<p>So in this case we must have a property in the <strong>ViewModel</strong> class that exposes the Footballer class that lives in the <strong>Model</strong>.</p>
<p>Add a new item to your project, a class file, name it <strong>FootballerViewModel.cs</strong></p>
<p>The first thing I need to do in my new class is to implement the <strong>INotifyPropertyChanged</strong> interface.This is because the <strong>View</strong> is bound to the <strong>ViewModel</strong>. <strong>INotifyPropertyChanged</strong> interface is the way to push data to the <strong>View</strong>.</p>
<p>The first version of the <strong>ViewModel</strong> class follows</p>
<p><pre class="brush: csharp;">
class FootballerViewModel:INotifyPropertyChanged
{

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

}
}
</pre></p>
<p>Let&#8217;s create a property that  is an instance of the <strong>Model</strong> object .The second version of the <strong>ViewModel</strong>class follows</p>
<p><pre class="brush: csharp;">
class FootballerViewModel:INotifyPropertyChanged
{

private Footballer _myfootballer;

public Footballer MyFootballer
{
get { return _myfootballer; }
set

{

_myfootballer = value;
OnPropertyChanged(&quot;MyFootballer&quot;);

}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

}
}
</pre></p>
<p>Now I will use the constructor for the <strong>ViewModel</strong> class and populate it with some random data.</p>
<p>The third version of the <strong>ViewModel</strong> follows</p>
<p><pre class="brush: csharp;">

class FootballerViewModel:INotifyPropertyChanged
{

public FootballerViewModel()
{
LoadFootballers();
}

private void LoadFootballers()
{
MyFootballer  = new Footballer()
{
FirstName = &quot;Steven&quot;,
LastName = &quot;Gerrard&quot;,
Age = 31,
Weight = 88.6,
Height = 1.84

};
}

private Footballer _myfootballer;

public Footballer MyFootballer
{
get { return _myfootballer; }
set

{

_myfootballer = value;
OnPropertyChanged(&quot;MyFootballer&quot;);

}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

}
}

</pre></p>
<p>Now, let&#8217;s create the <strong>View</strong>. The <strong>View</strong> will be purely <strong>XAML. </strong>It consists of the visual elements like buttons,textboxes. It is not responsible for retrieving data,implement business logic or validation logic.<strong><br />
</strong></p>
<p>First things first. Move the <strong>MainWindow.xaml</strong> file to the <strong>View</strong> folder.</p>
<p>Go to the <strong>App.xaml</strong> file and change the <strong>StartupUri</strong> attribute of the <strong>Application</strong> element to <strong><em>StartupUri=&#8221;View/MainWindow.xaml&#8221;</em></strong></p>
<p><pre class="brush: xml;">

&lt;Window x:Class=&quot;WpfMVVM.MainWindow&quot;
xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot; &gt;

&lt;Grid&gt;

&lt;Grid.RowDefinitions&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;RowDefinition Height=&quot;46*&quot; /&gt;
&lt;/Grid.RowDefinitions&gt;
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;121*&quot; /&gt;
&lt;ColumnDefinition Width=&quot;382*&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
&lt;TextBlock Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,12,0,0&quot; Name=&quot;textBlock1&quot; Text=&quot;First Name:&quot; VerticalAlignment=&quot;Top&quot;
Width=&quot;82&quot; FontSize=&quot;16&quot; /&gt;
&lt;TextBox Grid.Column=&quot;1&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,12,0,0&quot; Name=&quot;textBox1&quot; VerticalAlignment=&quot;Top&quot;
Width=&quot;266&quot; /&gt;
&lt;TextBlock Grid.Row=&quot;1&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;12,8,0,0&quot; Name=&quot;textBlock2&quot; Text=&quot;Last Name:&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;82&quot; FontSize=&quot;16&quot; /&gt;
&lt;TextBlock Grid.Row=&quot;2&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;12,9,0,0&quot; Name=&quot;textBlock3&quot; Text=&quot;Age:&quot;
VerticalAlignment=&quot;Top&quot; FontSize=&quot;16&quot; /&gt;
&lt;TextBlock Grid.Row=&quot;3&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,12,0,0&quot; Name=&quot;textBlock4&quot; Text=&quot;Height:&quot;
VerticalAlignment=&quot;Top&quot; FontSize=&quot;16&quot; /&gt;
&lt;TextBlock Grid.Row=&quot;4&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;10,9,0,0&quot; Name=&quot;textBlock5&quot; Text=&quot;Weight:&quot;
VerticalAlignment=&quot;Top&quot; FontSize=&quot;16&quot; /&gt;
&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,9,0,0&quot; Name=&quot;textBox2&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot;  /&gt;
&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;2&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,9,0,0&quot; Name=&quot;textBox3&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot;  /&gt;
&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;3&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,12,0,0&quot; Name=&quot;textBox4&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot;  /&gt;
&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;4&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,9,0,0&quot; Name=&quot;textBox5&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot;  /&gt;
&lt;TextBlock Grid.Row=&quot;5&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;12,12,0,13&quot; Name=&quot;textBlock6&quot; Text=&quot;Time Saved:&quot; FontSize=&quot;16&quot; /&gt;
&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;5&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,13,0,0&quot; Name=&quot;textBox6&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; /&gt;
&lt;Button Content=&quot;Update&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;6&quot; Height=&quot;24&quot; HorizontalAlignment=&quot;Left&quot;
Margin=&quot;92,15,0,0&quot; Name=&quot;button1&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;156&quot; FontSize=&quot;16&quot; FontFamily=&quot;Garamond&quot;
FontWeight=&quot;Bold&quot; BorderBrush=&quot;#FF407F2E&quot; Foreground=&quot;#FFE39223&quot; Background=&quot;#FF175D17&quot; /&gt;
&lt;/Grid&gt;
&lt;/Window&gt;

</pre></p>
<p>Now let&#8217;s make the necessary changes on the <strong>View</strong> so it can bind to the <strong>Model</strong> through the <strong>ViewModel</strong>.</p>
<p>We have first to make a reference to theViewModel class/object so I include the following namespace.</p>
<pre>xmlns:football="clr-namespace:WpfMVVM.ViewModel"</pre>
<p>This is the first step to hook a <strong>View</strong> to the <strong>ViewModel. </strong>We tell WPF where our <strong>ViewModel</strong> lives<strong>.<br />
</strong></p>
<p><strong></strong>Then I will create the <strong>ViewModel</strong> as a resource (static resource).</p>
<pre>&lt;Window.Resources&gt;

        &lt;football:FootballerViewModel x:Key="FootballerViewModel" /&gt;

&lt;/Window.Resources&gt;</pre>
<p>Then in the <strong>Grid</strong> element I make the following change</p>
<pre>Grid DataContext="{StaticResource FootballerViewModel}" &gt;</pre>
<p>The <strong>DataContext</strong> property <strong>inherits its value to child elements</strong>. So you can set the <em><strong>DataContext</strong></em> on a layout container (Grid) and its values are inherited to all child elements. This is very useful in our case where we want to bind to the same data object.</p>
<p>Databinding is <strong>typically done in XAML</strong> by using the <strong>{Binding}</strong> markup extension. We have to bind the <strong>Text</strong> attribute of the <strong>TextBox</strong> element to the various properties as implemented in the <strong>Model </strong>through the <strong>ViewModel</strong>.</p>
<p><pre class="brush: xml;">
&lt;TextBox Grid.Column=&quot;1&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,12,0,0&quot; Name=&quot;textBox1&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; Text=&quot;{Binding MyFootballer.FirstName ValidatesOnDataErrors=True}&quot; /&gt;

&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,9,0,0&quot; Name=&quot;textBox2&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; Text=&quot;{Binding MyFootballer.LastName, ValidatesOnDataErrors=True}&quot; /&gt;

&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;2&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,9,0,0&quot; Name=&quot;textBox3&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; Text=&quot;{Binding MyFootballer.Age}&quot; /&gt;

&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;3&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,12,0,0&quot; Name=&quot;textBox4&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; Text=&quot;{&lt;strong&gt;Binding MyFootballer.Height&lt;/strong&gt;}&quot; /&gt;

&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;4&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,9,0,0&quot; Name=&quot;textBox5&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; Text=&quot;{Binding MyFootballer.Weight}&quot; /&gt;

&lt;TextBox Grid.Column=&quot;1&quot; Grid.Row=&quot;5&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;45,13,0,0&quot; Name=&quot;textBox6&quot;
VerticalAlignment=&quot;Top&quot; Width=&quot;266&quot; Text=&quot;{Binding MyFootballer.SavedTime}&quot; /&gt;
</pre></p>
<p>Run your application and see the values from the domain object appearing in the textboxes.</p>
<p>We do have a button in our UI. We need to update data from the UI and bind the new data to the textboxes.</p>
<p>We need to have a different communnication between the <strong>View</strong> and the <strong>ViewModel</strong>. In this case we will use <strong>Commands</strong>.</p>
<p>First we need to update the XAML.</p>
<p><pre class="brush: xml;">
&lt;Button Content=&quot;Update&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;6&quot; Height=&quot;24&quot; HorizontalAlignment=&quot;Left&quot; Margin=&quot;92,15,0,0&quot;
Name=&quot;button1&quot; VerticalAlignment=&quot;Top&quot; Width=&quot;156&quot; FontSize=&quot;16&quot; FontFamily=&quot;Garamond&quot;
FontWeight=&quot;Bold&quot; BorderBrush=&quot;#FF407F2E&quot; Foreground=&quot;#FFE39223&quot; Background=&quot;#FF175D17&quot;
Command=&quot;{Binding SaveFootballerCommand}&quot; /&gt;
</pre></p>
<p>So I updated the XAML for the button element by adding the <em>Command=&#8221;{Binding SaveFootballerCommand}&#8221;</em></p>
<p>Now we must add some more code in our <strong>ViewModel</strong>.</p>
<p><pre class="brush: csharp;">
public class SaveFootballerCommand:ICommand
{

Action _saveMethod;

public bool CanExecute(object parameter)
{
return true;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
_saveMethod.Invoke();
}
}
</pre></p>
<p>I create a new class, SaveFootballerCommand, that has to implement the<strong> ICommand</strong> interface. Then I define an Action, <em>_saveMethod</em>, which is what is executed when the button is clicked.</p>
<p>The <em>CanExecute</em> tells me if I am allowed to execute the command.Then I create the <em>Execute</em> method and invoke it.</p>
<p>Now we need to create a property in my <strong>ViewModel</strong> that exposes that command.</p>
<p><pre class="brush: csharp;">
private ICommand _SaveFootballerCommand;

public ICommand SaveFootballerCommand
{
get { return _SaveFootballerCommand; }
set
{
_SaveFootballerCommand = value;
OnPropertyChanged(&quot;SaveFootballerCommand&quot;);

}
}

</pre></p>
<p>Now we need to create an instance of the <em>SaveFootballerCommand</em>.</p>
<p><pre class="brush: csharp;">
private void FireCommand()
{
SaveFootballerCommand = new SaveFootballerCommand(updateFootballer) ;
}

</pre></p>
<p>I place the inside my constructor the <strong>FireCommand()</strong> method.</p>
<p><pre class="brush: csharp;">
public FootballerViewModel()
{
FireCommand();
LoadFootballers();
}

</pre></p>
<p>The <em>updateFootballer</em> method is going to be invoked when the command is executed.So I must implement it.</p>
<p><pre class="brush: csharp;">
private void updateFootballer()
{

MyFootballer.SavedTime = DateTime.Now;

}
</pre></p>
<p>Now I need to create a constructor of the <strong>SavePersonCommand</strong> class that takes a parameter. The code follows</p>
<p><pre class="brush: csharp;">
public SaveFootballerCommand(Action updateFootballer)
{
_saveMethod = updateFootballer;

}
</pre></p>
<p>The whole code for the ViewModel class follows</p>
<p><pre class="brush: csharp;">
public SaveFootballerCommand(Action updateFootballer)
{
class FootballerViewModel:INotifyPropertyChanged
{

public FootballerViewModel()
{
FireCommand();
LoadFootballers();
}

private void FireCommand()
{
SaveFootballerCommand = new SaveFootballerCommand(updateFootballer) ;
}

private void updateFootballer()
{

MyFootballer.SavedTime = DateTime.Now;

}

private void LoadFootballers()
{
MyFootballer  = new Footballer()
{
FirstName = &quot;Steven&quot;,
LastName = &quot;Gerrard&quot;,
Age = 31,
Weight = 88.6,
Height = 1.84

};
}

private Footballer _myfootballer;

public Footballer MyFootballer
{
get { return _myfootballer; }
set

{

_myfootballer = value;
OnPropertyChanged(&quot;MyFootballer&quot;);

}
}

private ICommand _SaveFootballerCommand;

public ICommand SaveFootballerCommand
{
get { return _SaveFootballerCommand; }
set
{
_SaveFootballerCommand = value;
OnPropertyChanged(&quot;SaveFootballerCommand&quot;);

}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

}
}

}
</pre></p>
<p>Run your application and click the button.Note how the date is updated.</p>
<p>Note that we do not have written a single line of code to the <strong>MainWindow.xaml.cs</strong> file.</p>
<p>Now that we have a clear understanding of what <strong>MVVM</strong> is and what the different components are, let&#8217;s review again the main concepts.</p>
<p>The <strong>ViewModel</strong> is responsible for the state and behaviour of the <strong>View</strong> and it acts like the &#8220;middle man&#8221; between the <strong>View</strong> and the <strong>Model</strong>.</p>
<p>It the middle layer and its main job is to send <strong>View</strong> information to the <strong>Model</strong> and <strong>Model</strong> information to the <strong>View</strong>.</p>
<p>It has no dependency on the <strong>View</strong> so we can reuse the <strong>ViewModel</strong> on different <strong>Views</strong> or even other platforms.</p>
<p>The <strong>ViewModel</strong> exposes the <strong>Model</strong> as <strong>properties</strong> or <strong>commands</strong>.</p>
<p>In any case it must implement the <strong>INotifyPropertyChanged</strong> interface.</p>
<p>The <strong>View</strong> binds to properties in the <strong>ViewModel</strong>. It does that by setting the <strong>DataContext</strong> of a <strong>View</strong> to an instance of the <strong>ViewModel</strong> object.</p>
<p>The <strong>Model</strong> is tha data.Simple as that. The Model&#8217;s job is to represent the data and has no knowledge of where or how the data will be presented.</p>
<p>By using this pattern we can have the designers in our company designing the Views with xaml using Visual Studio Designer or Blend. The developers in our company can work with the <strong>Model</strong> and the <strong>ViewModel</strong> writing the data access code and businnes logic . We reduce the development time.</p>
<p>This is great pattern because we can make our code more <strong>testable</strong> and <strong>maintainable</strong>.</p>
<p>If you want to have a look at the MVVM more closely have a look <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">here</a>.</p>
<p>It would be nice if you could spare some time and have a  look at these related patterns with <strong>MVVM</strong> pattern like <a href="http://msdn.microsoft.com/en-us/magazine/cc188690.aspx">MVP</a>,<a href="http://msdn.microsoft.com/en-us/library/ff649643.aspx">MVC</a>,<a href="http://martinfowler.com/eaaDev/PresentationModel.html">PM</a>.</p>
<p>Hope it helps!!! Email me if you need the source code.</p>
<a href="http://polldaddy.com/poll/1079054">Take Our Poll</a>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/c-4-0/'>c# 4.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/wpf/'>WPF</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/mvvm/'>MVVM</a>, <a href='https://dotnetstories.wordpress.com/tag/patterns/'>Patterns</a>, <a href='https://dotnetstories.wordpress.com/tag/wpf/'>WPF</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1278/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1278&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2011/07/17/an-introduction-to-mvvm-pattern-using-wpf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2011/07/mvvm.jpg" medium="image">
			<media:title type="html">MVVM</media:title>
		</media:content>
	</item>
		<item>
		<title>Create a master details application with WPF and the Entity framework</title>
		<link>https://dotnetstories.wordpress.com/2010/11/26/wpf-and-the-entity-framework/</link>
		<comments>https://dotnetstories.wordpress.com/2010/11/26/wpf-and-the-entity-framework/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 16:47:13 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[general .net]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Entity framework]]></category>
		<category><![CDATA[master-detail]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1246</guid>
		<description><![CDATA[I have been studying WPF for some time now and I am impressed with its extensive API and the incredible-stunning applications that one can build.

In this post I would like to show you how to create a WPF application that will fetch data from a database<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1246&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been studying WPF for some time now and I am impressed with its extensive API and the incredible-stunning applications that one can build.</p>
<p>In this post I would like to show you how to create a WPF application that will fetch data from a database. Then I will enhance the simple application by creating a master details form. I will demonstrate all these with a hands on, step by step example. I will do all that without writing a single line of code.</p>
<p>My favourite data access technology is Entity framework and I am going to use EF to fetch data from the database.</p>
<p>I am going to use the Pubs database. You can download the installation scripts of the Pubs database from <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&amp;displaylang=en" target="_blank">here</a>.</p>
<p>I am going to use Visual Studio 2010 and C# as the development language. So here it is.</p>
<ol>
<li>Fire up Visual Studio 2010. Create a new project and choose &#8220;Wpf Application&#8221; from the available templates. Save your project with a name that you want in the desired location.</li>
<li>Add new item in your WPF project. From the available items choose &#8220;Ado.Net Entity Data Model&#8221; name your model <strong>pubs.edmx</strong> and click <strong>Add</strong>. In the Entity Data Model wizard click generate from database and click <strong>Next</strong>. Create a new connection and choose the SQL Server instance that the Pubs database is attached to. Then click <strong>OK</strong> to close the  <strong>Connections</strong> window and return to the Entity Data model wizard window. Click <strong>Next</strong> and choose from the &#8220;<strong>Choose your Database Objects</strong>&#8221; window all the tables. Then click <strong>Finish</strong>.</li>
<li>Go to <strong>Data</strong>-&gt;<strong>Show Data Sources</strong> option and click <strong>Show Data Sources</strong> option. You will see immediately all the classes availablee to use in my application. That is awesome. Drag and drop the <strong>Publishers</strong> class on the <strong>MainWindow.xaml</strong> file.</li>
</ol>
<p></p>
<p style="font-family:Verdana;font-size:1.1em;">
Now let&#8217;s go and have a look at the XAML code generated. We notice that we have a <strong>DataGrid</strong> control.Some of the xaml code generated is show in the snippet below.</p>
<p style="font-family:consolas;font-size:.8em;"><span style="color:#000000;">&lt;Window.Resources&gt;         &lt;CollectionViewSource x:Key=&#8221;publishersViewSource&#8221; d:DesignSource=&#8221;{d:DesignInstance my:publisher, CreateList=True}&#8221; /&gt;     &lt;/Window.Resources&gt;     &lt;Grid DataContext=&#8221;{StaticResource publishersViewSource}&#8221;&gt;         &lt;DataGrid AutoGenerateColumns=&#8221;False&#8221; EnableRowVirtualization=&#8221;True&#8221; Height=&#8221;125&#8243; HorizontalAlignment=&#8221;Left&#8221; ItemsSource=&#8221;{Binding}&#8221; Margin=&#8221;12,12,0,0&#8243; Name=&#8221;publishersDataGrid&#8221; RowDetailsVisibilityMode=&#8221;VisibleWhenSelected&#8221; VerticalAlignment=&#8221;Top&#8221; Width=&#8221;479&#8243;&gt;             &lt;DataGrid.Columns&gt;                 &lt;DataGridTextColumn x:Name=&#8221;pub_idColumn&#8221; Binding=&#8221;{Binding Path=pub_id}&#8221; Header=&#8221;pub id&#8221; Width=&#8221;SizeToHeader&#8221; /&gt;                 &lt;DataGridTextColumn x:Name=&#8221;pub_nameColumn&#8221; Binding=&#8221;{Binding Path=pub_name}&#8221; Header=&#8221;pub name&#8221; Width=&#8221;SizeToHeader&#8221; /&gt;                 &lt;DataGridTextColumn x:Name=&#8221;cityColumn&#8221; Binding=&#8221;{Binding Path=city}&#8221; Header=&#8221;city&#8221; Width=&#8221;SizeToHeader&#8221; /&gt;                 &lt;DataGridTextColumn x:Name=&#8221;stateColumn&#8221; Binding=&#8221;{Binding Path=state}&#8221; Header=&#8221;state&#8221; Width=&#8221;SizeToHeader&#8221; /&gt;                 &lt;DataGridTextColumn x:Name=&#8221;countryColumn&#8221; Binding=&#8221;{Binding Path=country}&#8221; Header=&#8221;country&#8221; Width=&#8221;SizeToHeader&#8221; /&gt;             &lt;/DataGrid.Columns&gt;         &lt;/DataGrid&gt;     &lt;/Grid&gt;</span></p>
<p style="font-family:Verdana;font-size:1.1em;">We notice the <strong>CollectionViewSource</strong> which is our binding source to the underlying data.Let&#8217;s see some of the code that it is generated from Visual Studio for us in the code behind file.</p>
<pre style="font-family:consolas;font-size:.9em;"> <span style="color:blue;">private</span> <span style="color:blue;">void</span> Window_Loaded(<span style="color:blue;">object</span> sender, <span style="color:#2b91af;">RoutedEventArgs</span> e)
 {

WpfMasterDetailEF.<span style="color:#2b91af;">pubsEntities</span> pubsEntities = <span style="color:blue;">new</span> WpfMasterDetailEF.<span style="color:#2b91af;">pubsEntities</span>();
 <span style="color:green;">// Load data into publishers. You can modify this code as needed.</span>
System.Windows.Data.<span style="color:#2b91af;">CollectionViewSource</span> publishersViewSource = ((System.Windows.Data.<span style="color:#2b91af;">CollectionViewSource</span>)(<span style="color:blue;">this</span>.FindResource(<span style="color:#a31515;">"publishersViewSource"</span>)));
System.Data.Objects.<span style="color:#2b91af;">ObjectQuery</span>&lt;WpfMasterDetailEF.<span style="color:#2b91af;">publisher</span>&gt; publishersQuery = <span style="color:blue;">this</span>.GetpublishersQuery(pubsEntities);
publishersViewSource.Source = publishersQuery.Execute(System.Data.Objects.<span style="color:#2b91af;">MergeOption</span>.AppendOnly);
 }</pre>
<p>4) Run your application and you will see the data in your application.That is pretty cool and I did not have to write a single line of code.</p>
<p>5) Now we will enhance this application by creating a master details application. From the <strong>Data-&gt;Show Data Sources</strong> drag and drop the <strong>employees</strong> entity to the <strong>MainWindow.xaml</strong>.</p>
<p>Have a look at the picture below.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2010/11/wpf-ef.png"><img class="aligncenter size-full wp-image-1261" title="wpf-ef" src="http://dotnetstories.files.wordpress.com/2010/11/wpf-ef.png?w=460&#038;h=271" alt="" width="460" height="271" /></a></p>
<p>6) Have a look at the generated code.</p>
<p>Note the second <strong>CollectionViewSource </strong>which is our binding source to the undelying data.<strong><br />
</strong></p>
<pre style="font-family:consolas;font-size:.9em;"> &lt;CollectionViewSource x:Key="publishersemployeesViewSource" Source="{Binding Path=employees, Source={StaticResource publishersViewSource}}" /&gt;</pre>
<p>7) Run your application and see that we have a master/detail functionality out of the box. That is pretty cool.</p>
<p>Hope it helps.</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/general-net/'>general .net</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/wpf/'>WPF</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/entity-framework/'>Entity framework</a>, <a href='https://dotnetstories.wordpress.com/tag/master-detail/'>master-detail</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1246/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1246&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/11/26/wpf-and-the-entity-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2010/11/wpf-ef.png" medium="image">
			<media:title type="html">wpf-ef</media:title>
		</media:content>
	</item>
		<item>
		<title>How to change the master page depending on the client&#8217;s browser</title>
		<link>https://dotnetstories.wordpress.com/2010/10/06/how-to-change-the-master-page-depending-on-the-clients-browser/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/06/how-to-change-the-master-page-depending-on-the-clients-browser/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 23:16:32 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[browser]]></category>
		<category><![CDATA[master page]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1234</guid>
		<description><![CDATA[In one of my seminars on ASP.Net, I was asked a question from a student regarding master pages and the various browser appications. He basically asked if it was possible to have a different master page depending on the client&#8217;s browser. My initial answer was to find the browser&#8217;s version programmatically and according to this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1234&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In one of my seminars on ASP.Net, I was asked a question from a student regarding master pages and the various browser appications.</p>
<p>He basically asked if it was possible to have a different master page depending on the client&#8217;s browser.</p>
<p>My initial answer was to find the browser&#8217;s version programmatically and according to this value to have a particular <em>master page</em> dynamically assigned during the PreInit stage of the Page lifecycle.</p>
<p>But there is a simpler way.At first we need to create a website using Visual Studio 2008/2010.</p>
<p>Then copy the original <strong>Site.master</strong> page to the root directory of the website and rename it to <strong>AnotherSite.master</strong>.</p>
<p>Then we need to copy and paste in the root direcotory the <strong>Site.css</strong> and rename it to <strong>NewSite.css</strong>.</p>
<p>So we have now two master pages and two .css files.</p>
<p>Edit the <strong>AnotherSite.master</strong> and change the css reference</p>
<p>from</p>
<pre> &lt;link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /&gt;
to</pre>
<pre> &lt;link href="~/Styles/NewSite.css" rel="stylesheet" type="text/css" /&gt;</pre>
<p>Now we do need to make some changes to the <strong>Newsite.css</strong> file.  You can change the background color, for example</p>
<pre>body   
{
background:#efefef;</pre>
<p>The page layout</p>
<pre>.page
{
    width: 1200px;</pre>
<p>Now we can go add a new web form to our page. We will call it &#8220;Anotherpage.aspx&#8221;.</p>
<p>Select as a master page the <strong>AnotherSite.master</strong>.</p>
<p>Then go to the &#8220;Source&#8221; of the newly created page and edit the Page directive according to the following line.</p>
<pre>&lt;%@ Page Title="" Language="C#"
mozilla:MasterPageFile="~/AnotherSite.master" 
ie:MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="MyNewPage.aspx.cs" Inherits="MyNewPage" %&gt;</pre>
<p>Run your application with IE and Firefox and notice the respective masterpages being applied to the web page.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/browser/'>browser</a>, <a href='https://dotnetstories.wordpress.com/tag/master-page/'>master page</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1234/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1234&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/06/how-to-change-the-master-page-depending-on-the-clients-browser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>How to use cookies in ASP.Net applications</title>
		<link>https://dotnetstories.wordpress.com/2010/10/06/how-to-use-cookies-in-asp-net-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/06/how-to-use-cookies-in-asp-net-applications/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 23:10:08 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[VB 2005]]></category>
		<category><![CDATA[VB 2008]]></category>
		<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[cookie]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1231</guid>
		<description><![CDATA[In this post we are going to see a step by step example on how to read,write,delete cookies in asp.net websites. Cookies are small pieces of text that you can associate with a website which are transfered down to the user&#8217;s computer when the user visits the website. You can use any of the versions [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1231&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post we are going to see a step by step example on how to read,write,delete cookies in asp.net websites.</p>
<p>Cookies are small pieces of text that you can associate with a website which are transfered down to the user&#8217;s computer when the user visits the website.</p>
<p>You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).</p>
<p>I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.</p>
<p>Before we begin it is very important to note some of the limitations of cookies. They store relatively small amount of information about 4kbytes.</p>
<p>Browsers limit the number of cookies associated with a website ( 20 cookies for a certain website ). There is also a limit on how many cookies a browser can handle regarding all websites and that is about 300.</p>
<p>All the data in cookies is stored as text so bear that in mind that you should not store sensitive information in a cookie. You should use the information in the cookie to identify a user, a user&#8217;s last visit e.t.c</p>
<p>1) Create an Asp.net web site and name it as you want.</p>
<p>2) Let&#8217;s add a cookie in the cookies collection. In the <strong>Page_Load</strong> event handling routine of the <strong>default.aspx</strong> page type</p>
<pre>Response.Cookies("LastVisit").Value = DateTime.Now.ToString()
Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(10)</pre>
<p>3)  We add a new cookie now that it will be stored in the user&#8217;s computer and we set it to expire after 10 days.So if someone visits our website today and then it visits it after 12 days, the browser will delete the cookie</p>
<p>from the users hard disk.Comment out the two line of code in the <strong>Page_Load</strong> event handling routine.We can use an alternative way to create a cookie and write information on it.</p>
<pre>Dim mycookie As HttpCookie = New HttpCookie("LastVisit")
mycookie.Value = DateTime.Now.ToString()
mycookie.Expires = DateTime.Now.AddDays(10)
Response.Cookies.Add(mycookie)</pre>
<p>4)  You can store multiple values in the same cookie with the help of <strong>subkeys</strong>. Comment out the 4 lines of code above. Type the following lines of code in the <strong>Page_Load</strong> routine</p>
<pre>Response.Cookies("mydata")("LastVisit") = DateTime.Now.ToString()
Response.Cookies("mydata")("username") = "fofo"
Response.Cookies("mydata").Expires = DateTime.Now.AddDays(10)</pre>
<p>5) Comment out the line above. We will write the same statement as above with a different syntax.Type the following lines of code in the <strong>Page_Load</strong> routine</p>
<pre> Dim mycookie As HttpCookie = New HttpCookie("mydata")
mycookie.Values("LastVisit") = DateTime.Now.ToString()
mycookie.Values("username") = "fofo"
mycookie.Expires = DateTime.Now.AddDays(10)
Response.Cookies.Add(mycookie)</pre>
<p>6) Another thing we can do with the cookies is to specify the scope of the cookie. For example we might want to have a cookie stored on the user&#8217;s computer only</p>
<p>if the user visits a specific folder-page e.g Marketing. So if someone visits <strong>www.mysite.com </strong>the cookie is not visible, but if he visits <strong>www.mysite.com/marketing</strong> and all pages within that folder the cookie is visible.</p>
<p>In order to achieve that we use the <strong>Path</strong> property to restrict the cookie to a particular path to a website.Comment out the lines above and type the following</p>
<pre>Dim mycookie As HttpCookie = New HttpCookie("mydata")

        mycookie.Values("LastVisit") = DateTime.Now.ToString()
        mycookie.Values("username") = "fofo"
        mycookie.Expires = DateTime.Now.AddDays(10)
        mycookie.Path = "/Marketing"
        Response.Cookies.Add(mycookie)</pre>
<p>7) Another property we can use is the <strong>Domain</strong> property. So in the previous example we can comment out the</p>
<p>mycookie.Path = &#8221;/Marketing&#8221;</p>
<p>and type</p>
<pre>mycookie.Domain = "help.mysite.com"</pre>
<p>This cookie will only be sent back to the server is the page is associated with the domain &#8220;help.mysite.com&#8221;</p>
<p>8) In order to read cookies sent through the user&#8217;s browser back to the server we do the following.</p>
<p>First you need to add a label web server control to your default.aspx page. Then in the <strong>Page_Load</strong> event handling routine type</p>
<pre>If Not Request.Cookies("LastVisit") Is Nothing Then 

Label1.Text = Server.HtmlEncode(Request.Cookies("LastVisit").Value)
End If</pre>
<p>9) Run you application and you will see that you successfully set a cookie and read it back from the user&#8217;s computer.</p>
<p>10) If you want to modify the cookie&#8217;s value and expiration date you can type something like</p>
<pre>Response.Cookies("LastVisit").Value = DateTime.Now.ToString()
Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(30)</pre>
<p>The code above will reset the value of &#8220;LastVisit&#8221; to the actual current time and set a new expiration date for the cookie</p>
<p>11) If you want to delete a cookie from the user&#8217;s computer you can type the following</p>
<pre> Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(-1)</pre>
<p>Then the browser will delete the cookie from the user&#8217;s  computer.</p>
<p>If you need the source code just email me.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2005/'>VB 2005</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2008/'>VB 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/cookie/'>cookie</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1231/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1231/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1231/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1231/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1231/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1231/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1231/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1231/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1231&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/06/how-to-use-cookies-in-asp-net-applications/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Caching an ASP.Net page</title>
		<link>https://dotnetstories.wordpress.com/2010/10/06/caching-an-asp-net-page/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/06/caching-an-asp-net-page/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 23:07:25 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[VB 2005]]></category>
		<category><![CDATA[VB 2008]]></category>
		<category><![CDATA[VB 9.0]]></category>
		<category><![CDATA[Visual Basic 10.0]]></category>
		<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[VS 2010]]></category>
		<category><![CDATA[caching]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1228</guid>
		<description><![CDATA[The issue of &#8220;caching&#8221; keeps coming up in my asp.net seminars so I though it would be a good idea to write a post. I know it is a well documented feature and widely used but I really believe most people will be able to use this rather simple example and understand the concepts behind [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1228&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The issue of &#8220;caching&#8221; keeps coming up in my asp.net seminars so I though it would be a good idea to write a post. I know it is a well documented feature and widely used but I really believe most people will be able to use this rather simple example and understand the concepts behind caching.</p>
<p>You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).</p>
<p>I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.</p>
<p>1) Create an Asp.net web site and name it as you want.</p>
<p>2) In the <strong>default.aspx</strong> page add a new paragraph or header with content of your choice.In my case i have added something like this</p>
<p>&lt;h2&gt;Caching is really useful!!!!&lt;/h2&gt;</p>
<p>3) Let&#8217;s think simple at first. We do want to cache the entire page (<strong>default.aspx</strong>)</p>
<p>Just below the <strong>Page</strong> directive ( top of the page ) you add the following bit of code:</p>
<pre>&lt;%@ OutputCache Duration="20" VaryByParam="none" %&gt;</pre>
<p>We do cache the page for 20 seconds. That is determined by the <strong>Duration</strong> Attribute.</p>
<p>4) Save your work and run your application. The first time we see the output of the asp.net page, this is served directly from the asp.net engine.</p>
<p>If you hit refresh for a period for less than 20 seconds the page is served from the <strong>Cache</strong>.</p>
<p>5) Let&#8217;s see a more complex scenario involving query strings and how we can make a decision on whether to cache the page or not based on the value of the query string. Add a new label control to the .aspx page</p>
<pre> &lt;asp:Label ID="mylabel" runat="server"&gt;&lt;/asp:Label&gt;</pre>
<p>In the Page_Load event handler routine add the code</p>
<pre>If (Not Request("id") Is Nothing) Then 
mylabel.Text = " The query string value is " + Request("id").ToString()

End If</pre>
<p>6) Change the <strong>OutputCache</strong> directive to</p>
<pre> &lt;%@ OutputCache Duration="20" VaryByParam="id" %&gt;</pre>
<p>7) Run your application and type in the url address bar <strong>http://localhost:6141/caching/Default.aspx?id=5</strong>. See the results. If you hit refresh right away the page is refreshed from the cache and it is not reloaded.</p>
<p>If you type this <strong>http://localhost:6141/caching/Default.aspx?id=6</strong> ( within the 20 seconds period ) it senses that the id has changed now and it re-renders the page. It also sets a new caching period of 20 seconds.</p>
<p>8) What is really interesting to bear in mind ( and not many people know ) is that you can have different caching settings depending on the client&#8217;s browser.The first step is to change the <strong>OutputCache</strong> directive to this</p>
<pre>&lt;%@ OutputCache Duration="20" VaryByParam="id" VaryByCustom="browser" %&gt;</pre>
<p>9) Basically we say &#8220;Continue to cache the page as long as the clients use the same browser&#8221;. So if you have 3 people in a row that have IE8 hitting your page, will all get the same cached version of the page.</p>
<p>If someone hits our page with Firefox or Chrome, they will a brand new rendered page. At this time it will be created a 20 seconds cache window period specific for each browser.This functionality is built into the caching module, and will insert separate cached versions of the page for each browser name and major version.</p>
<p>10) Now if we need to apply the caching techniques we just learnt in all pages of our asp.net application we will have to make a few modifications in the <strong>web.config</strong> file.We will add something that is called &#8220;Cache Profiles&#8221;</p>
<p>Just below the <strong>&lt;system.web&gt;</strong> add this snippet</p>
<pre> &lt;caching&gt;
      &lt;outputCacheSettings&gt;
        &lt;outputCacheProfiles&gt;
          &lt;add name="basic" 
               duration="20" 
               varyByParam="id" 
               varyByCustom="browser"
               /&gt;

        &lt;/outputCacheProfiles&gt;

      &lt;/outputCacheSettings&gt;

    &lt;/caching&gt;</pre>
<p>So we have created a new profile that is called &#8220;basic&#8221;. Now let&#8217;s apply this cache profile to one or more pages in our website.</p>
<p>So we switch back to our <strong>default.aspx</strong> page and in the <strong>OutputCache</strong> directive, type</p>
<pre> &lt;%@ OutputCache CacheProfile="basic" %&gt;</pre>
<p>Run your application again and you will see that we do have the same caching effects.</p>
<p>Obviously you can create different cache profiles and apply them to various pages.</p>
<p>I will have more posts on <strong>caching</strong> shortly.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2005/'>VB 2005</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2008/'>VB 2008</a>, <a href='https://dotnetstories.wordpress.com/category/vb-90/'>VB 9.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-basic-10-0/'>Visual Basic 10.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>, <a href='https://dotnetstories.wordpress.com/category/vs-2010/'>VS 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/caching/'>caching</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1228/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1228&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/06/caching-an-asp-net-page/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Caching an asp.net page depending on the user&#8217;s browser language</title>
		<link>https://dotnetstories.wordpress.com/2010/10/06/caching-an-asp-net-page-depending-on-the-users-browser-language/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/06/caching-an-asp-net-page-depending-on-the-users-browser-language/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 23:02:02 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[VB 2005]]></category>
		<category><![CDATA[VB 2008]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[browser]]></category>
		<category><![CDATA[caching]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1222</guid>
		<description><![CDATA[This is my second post regarding caching in asp.net applications. A friend of mine asked me if he can control caching of an asp.net page depending on the user&#8217;s language browser. Let&#8217;s see how we can accomplish that with a step by step example. You can use any of the versions of Visual studio (VS [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1222&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is my second post regarding caching in asp.net applications.</p>
<p>A friend of mine asked me if he can control caching of an asp.net page depending on the user&#8217;s language browser.</p>
<p>Let&#8217;s see how we can accomplish that with a step by step example.</p>
<p>You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).</p>
<p>I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.</p>
<p>We will identify the language of the user&#8217;s browser from the HTTP headers.</p>
<p>More specifically we will look at the <strong>Accept-Language header item.</strong></p>
<p>1) Create an Asp.net web site and name it as you want.Add a label web server control to your <strong>default.aspx</strong> page.</p>
<p>2) In the <strong>default.aspx</strong> just below the <strong>Page</strong> directive ( top of the page ) you add the following bit of code:</p>
<pre>&lt;%@ OutputCache Duration="50" VaryByHeader="Accept-Language"
VaryByParam="none"
 %&gt;</pre>
<p>We want to use <strong>VaryByHeader</strong> and assign it to the header item <strong>Accept-Language </strong>that we want to vary caching by<strong>.</strong></p>
<p>So now this page is going to be cached based on the language of the user&#8217;s browser.</p>
<p>3) Now switch back to the code behind and in the <strong>Page_Load</strong> event handling routine type the following</p>
<pre>If Not (Request.Headers("Accept-Language")) Is Nothing Then 
mylabel.Text = "language of the user is " +
 Request.Headers("Accept-Language").ToString
End If</pre>
<p>4) Run your application and see the result-your browser&#8217;s language. In most cases it will be something like &#8220;<strong>en-us</strong>&#8220;, or anything else that the HTML page will output. So if now we have 20 people</p>
<p>hitting our page &#8211; within the 50 seconds cache period &#8211; and all of them have &#8220;en-us&#8221; as their browser&#8217;s language they are going to get the cached version of the page. The page will not be re-rendered through the whole</p>
<p>page events-lifecycle.</p>
<p>5) If we have people hitting our page with a browser with a different language (.eg fr,es ) the Asp.Net would cache a second version of the page in french. So now we would have 2 cached versions of the page, one in english and one in french.So the first french person (browser language) to hit the page, he would see the page rendered to him ( the whole page lifecycle will run ) and at the same time it will be cached so subsequent requests from french people-users-browsers will be served from the cache.</p>
<p>If you need the code, just email me.</p>
<p>Hope it helps !!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2005/'>VB 2005</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2008/'>VB 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/browser/'>browser</a>, <a href='https://dotnetstories.wordpress.com/tag/caching/'>caching</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1222/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1222/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1222/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1222/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1222/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1222/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1222/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1222/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1222&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/06/caching-an-asp-net-page-depending-on-the-users-browser-language/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Linq to Objects in ASP.Net</title>
		<link>https://dotnetstories.wordpress.com/2010/10/06/linq-to-objects-in-asp-net/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/06/linq-to-objects-in-asp-net/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 22:58:49 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[LINQ to objects]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1219</guid>
		<description><![CDATA[In this post I would like to talk about  Linq to Objects in an ASP.Net application. In all my classes people seem to have the following answer to this question, &#8220;What kind of data can we query with LINQ?&#8220; Most people say &#8220;Well, we can query an SQL server database&#8221; . I am not very [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1219&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about  <strong>Linq to Objects in an ASP.Net application</strong>.</p>
<p>In all my classes people seem to have the following answer to this question, &#8220;<strong>What kind of data can we query with LINQ?</strong>&#8220;</p>
<p>Most people say &#8220;<strong>Well, we can query an SQL server database</strong>&#8221; . I am not very pleased when people forget the other flavors.</p>
<p>LINQ to Objects allow us to write “queries” over collections of objects.This is the first and most basic flavor of LINQ. LINQ to Objects enables you to perform<br />
complex query operations against any enumerable object. By that I mean any object that implements the <strong>IEnumerable</strong> interface.</p>
<p>I will use Visual Studio 2010 Ultimate edition.You can use <strong>VS 2010/VS2008</strong> Professional edition.</p>
<p><strong>VS 2010/VS2008</strong> Epxress editions will be fine for this example. I am using C# for this one.</p>
<p>1) Fire VS and create a new asp.net website with a name of your choice. Choose local filesystem as the location of your website files.</p>
<p>2)  Add a <strong>GridView</strong> web server control to the <strong>Default.aspx</strong> page.</p>
<p>3) Add a Class file in your website ( Add &#8211; &gt; New item ) . I am going to have data related to football so i named it <strong>Football.cs</strong></p>
<p>4) Inside the <strong>public class Football</strong> type</p>
<pre>        public string FootballTeamName { get; set; }
        public string Manager { get; set; }
        public string TeamCaptain { get; set; }
        public int ChampionshipsWon { get; set; }</pre>
<p>5) Now that we have a class to work with, we should create a simple generic List of the <strong>Football</strong> objects and then bind that list to the Gridview control.</p>
<p>6) This is the code for the generic list of the <strong>Football</strong> objects. We place this code in the <strong>Default.aspx</strong> page.</p>
<pre>public List&lt;Football&gt; GetFootballData()
{
return new List&lt;Football&gt; {
new Football { FootballTeamName="Liverpool", Manager="Roy Hodgson", 
TeamCaptain="Steven Gerrard",ChampionshipsWon=18  },
new Football { FootballTeamName="ManUtd", Manager="Alex Ferguson", 
TeamCaptain="Rio Ferdinand", ChampionshipsWon=18},
new Football { FootballTeamName="Chelsea", Manager="Carlos Ancelotti", 
TeamCaptain="Frank Lampard",ChampionshipsWon=4 },
new Football { FootballTeamName="Everton", Manager="David Moyes", 
TeamCaptain="Phil Neville",ChampionshipsWon=9 }

};

}</pre>
<p>7) Now we add the code in the Page_Load() event handling routine. We just type</p>
<pre> var football = GetFootballData();
 this.GridView1.DataSource = football;
 this.GridView1.DataBind();</pre>
<p>8) Run your application and see the results in the web browser.</p>
<p>9) Imagine we want to filter our data. Let&#8217;s write the query first in a non-LINQ way.</p>
<p>Comment out the code in the <strong>Page_Load</strong> event handling routine.We want to query the data where the <strong>Manager</strong> is &#8220;Roy Hodgson&#8221;.</p>
<p>In the <strong>Page_Load</strong> event handling routine type</p>
<pre> var football = GetFootballData();
var query = new List&lt;Football&gt;();
foreach (var f in football)
{
if (f.Manager == "Roy Hodgson" ) query.Add(f);
}
this.GridView1.DataSource = query;
    this.GridView1.DataBind();</pre>
<p>10) Run your application and see the in the browser the record that satisfies the criteria.</p>
<p>11) If we want to have more complex queries (grouping or sorting ) then the code becomes a bit hard to follow and maintain.</p>
<p>12) Now we will write a number of queries the &#8220;LINQ&#8221; way. We do not have to worry anymore on exactly how a query is going to be executed.</p>
<p>We just need to define what the query should return. The compiler must come up with a way and determine how the query will be executed.</p>
<p>13) Comment out the code inside the <strong>Page_Load</strong> event handling routine and type this code</p>
<pre>        var football = GetFootballData();
        var query = from f in football
                    select f;
        this.GridView1.DataSource = query;
        this.GridView1.DataBind();
 
</pre>
<p>14) Run your application and see the results. We use the <strong>GetFootballData()</strong> method to obtain the generic list collection.Then we use the simplest LINQ query to select all the <strong>Football</strong> objects from the generic collection.</p>
<p>We do have new language keywords like <strong>select</strong> and <strong>from</strong>.</p>
<p>15) Now let&#8217;s say that we want only the <strong>Manager</strong> and <strong>FootballTeamName</strong> values. Comment out the code inside the <strong>Page_Load</strong> event handling routine and type this code</p>
<pre>           var football = GetFootballData();
           var query = from f in football
                       select new { f.FootballTeamName, f.Manager };
           this.GridView1.DataSource = query;
           this.GridView1.DataBind();</pre>
<p>Run your application and see the results.What we did here is called <strong>Projection</strong> and contains the <strong>Manager</strong> and <strong>FootballTeamName</strong> values for all the objects.</p>
<p>16) If we want to have some ordering(get the values back according to the object <strong>Manager</strong> descending) of the data we just re-write the code above</p>
<pre>        var football = GetFootballData();
        var query = from f in football
                    orderby f.Manager descending
                    select new { f.FootballTeamName, f.Manager };
        this.GridView1.DataSource = query;
        this.GridView1.DataBind();</pre>
<p>Run your application and see the results.</p>
<p>17) We do have query filters in LINQ. We can use the <strong>where</strong> clause.If we want to find how many teams won more than 10 championships we should type ( after commenting out all our code in the <strong>Page_Load </strong>)</p>
<pre>        var football = GetFootballData();
        var query = from f in football
                    where f.ChampionshipsWon &gt; 10
                    select f;

        this.GridView1.DataSource = query;
        this.GridView1.DataBind();</pre>
<p>Run your application and see the results.</p>
<p>18) If we want to get only the Manager name and the team captain name for the last 2 records we should type (after commenting out all our code in the <strong>Page_Load</strong>)</p>
<pre>        var football = GetFootballData();
        var query = (from f in football

        select new { f.Manager, f.TeamCaptain }).Reverse().Take(2);

        this.GridView1.DataSource = query;
        this.GridView1.DataBind();</pre>
<p>Run your application and see the results. We use the <strong>Reverse()</strong> method that inverts the order of the elements in a sequence.</p>
<p>We also use the<strong> Take()</strong> method to return a specified number of elements from the start of a sequence.</p>
<p>This post can be very useful to people that begin to learn LINQ.Email me if you want the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/linq/'>LINQ</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/linq-to-objects/'>LINQ to objects</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1219/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1219&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/06/linq-to-objects-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Cross-Page postbacks in ASP.Net</title>
		<link>https://dotnetstories.wordpress.com/2010/10/05/cross-page-postbacks-in-asp-net/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/05/cross-page-postbacks-in-asp-net/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 17:35:13 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[postback]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1215</guid>
		<description><![CDATA[In this post I would like to talk about cross-page postbacks in ASP.Net.

When you have a .aspx page with a button on it and you click that button the page will be posted back to the original page.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1215&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to talk about cross-page postbacks in ASP.Net.</p>
<p>When you have a <strong>.aspx</strong> page with a button on it and you click that button the page will be posted back to the original page.</p>
<p>What we want to do now is to click that button and post back to an alternate page rather than the original one.</p>
<p>I am going to use Visual Studio 2010 Ultimate edition. You can use VS 2008/2005. All the express editions will suffice for our example.</p>
<p>I am going to use C# as the development language.</p>
<p>Let&#8217;s move on to our hands-on example.</p>
<p>1) Create an ASP.Net web site with an appropriate name in your file system.</p>
<p>2) In this first example we will see the typical scenario on how you postback back to the original page.</p>
<p>You should add some web server controls in the <strong>default.aspx</strong> page. Add 4 textboxes for ( Name,Age,Address,City ) and 4 labels and a button.</p>
<p>Basically, the markup should look like this</p>
<pre>     Name:
    &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt;
    &lt;br /&gt;
    Age:  &lt;asp:TextBox ID="TextBox4" runat="server"&gt;&lt;/asp:TextBox&gt;
    &lt;br /&gt;
    Address:
    &lt;asp:TextBox ID="TextBox2" runat="server"&gt;&lt;/asp:TextBox&gt;
    &lt;br /&gt;
    &lt;br /&gt;
    City:
    &lt;asp:TextBox ID="TextBox3" runat="server"&gt;&lt;/asp:TextBox&gt;
    &lt;br /&gt;
    &lt;br /&gt;
    &lt;asp:Button ID="Button1" runat="server" Text="Submit" 
          onclick="Button1_Click" /&gt;</pre>
<p>&lt;br /&gt;</p>
<pre>     &lt;asp:Label ID="labName" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;
     &lt;asp:Label ID="lblAge" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;
    &lt;asp:Label ID="labAddress" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;
    &lt;asp:Label ID="labCity" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;</pre>
<p>3)  In the <strong>Page_Load</strong> event handling routine of the <strong>default.aspx</strong> page type.</p>
<pre> if (IsPostBack)
    {
     
      labName.Text = TextBox1.Text;
      lblAge.Text = TextBox4.Text;
      labAddress.Text = TextBox2.Text;
      labCity.Text = TextBox3.Text;
    }</pre>
<p>4) Run you application and see all the data that we inputed in the textboxes appearing in the label controls.This is a typical postback within the same page.</p>
<p>5) Add another page in your site and name it <strong>SecondPage.aspx</strong>. Cut the label controls from the <strong>default.aspx</strong> and paste them in the <strong>SecondPage.aspx</strong> so we have,</p>
<pre>    &lt;asp:Label ID="labName" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;
     &lt;asp:Label ID="lblAge" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;
    &lt;asp:Label ID="labAddress" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;
    &lt;br /&gt;
    &lt;asp:Label ID="labCity" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;</pre>
<p>6) Now we want to post back from the <strong>Default.aspx</strong> page to the <strong>SecondPage.aspx.</strong></p>
<p>We go to the <strong>default.aspx</strong> page and we set the <strong>PostBackUrl</strong> property of the button to the <strong>SecondPage.aspx.</strong></p>
<pre>          &lt;asp:Button ID="Button1" runat="server" Text="submit" 
          onclick="Button1_Click" PostBackUrl="~/SecondPage.aspx" /&gt;</pre>
<p>7)  We go to the <strong>Page_Load </strong>event handling routine of the <strong>SecondPage.aspx </strong>and we type</p>
<p>labName.Text = TextBox1.Text;<br />
lblAge.Text = TextBox4.Text;<br />
labAddress.Text = TextBox2.Text;<br />
labCity.Text = TextBox3.Text;</p>
<p>Straight away we see that we have error indicators that inform us that <strong>TextBox1,TextBox2,TextBox3,TextBox4</strong> are dot declared.</p>
<p>We have to modify our code and try to reference the textbox controls from the<strong> SecondPage.aspx .</strong></p>
<p>So the new code in the <strong>Page_Load</strong> event is like this</p>
<p>if (this.PreviousPage.IsCrossPagePostBack)</p>
<p>{</p>
<p>TextBox text1 = this.PreviousPage.FindControl(&#8220;TextBox1&#8243;) as TextBox;<br />
TextBox text2 = this.PreviousPage.FindControl(&#8220;TextBox2&#8243;) as TextBox;<br />
TextBox text3 = this.PreviousPage.FindControl(&#8220;TextBox3&#8243;) as TextBox;<br />
TextBox text4 = this.PreviousPage.FindControl(&#8220;TextBox4&#8243;) as TextBox;<br />
labName.Text = text1.Text;<br />
lblAge.Text = text4.Text;<br />
labAddress.Text = text2.Text;<br />
labCity.Text = text3.Text;<br />
}</p>
<p>8) We do use <strong>FindControl()</strong> method to locate a reference to the controls on the source page (<strong>Default.aspx</strong>).We store those references in new object variables.</p>
<p>Then we assign in the label controls the <strong>Text</strong> values we get from the referenced controls. We use the <strong>IsCrossPagePostBack </strong> property to determine if a postback occurred from the source page.</p>
<p>9) Run your application, fill in the  and see for yourself that textbox control values are posted back to the <strong>SecondPage.aspx</strong></p>
<p>Email me if you want the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/postback/'>postback</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1215/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1215/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1215/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1215/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1215/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1215/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1215/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1215&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/05/cross-page-postbacks-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Send email in ASP.Net applications</title>
		<link>https://dotnetstories.wordpress.com/2010/10/05/send-email-within-asp-net-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/05/send-email-within-asp-net-applications/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 17:16:20 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1211</guid>
		<description><![CDATA[I know that this topic is also well documented in the web. But I decided to have a go, after so many people ask me the same question

"How can I send emails from asp.net web applications?"<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1211&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I know that this topic is also well documented in the web. But I decided to have a go, after so many people ask me the same question</p>
<p><strong>&#8220;How can I send emails from asp.net web applications?&#8221;</strong></p>
<p>I know we live in the era of Microsoft Messenger,Skype,Twitter,facebook and RSS. All these platforms-technologies are proven alternatives but nothing has eclipsed</p>
<p>the classic email protocols and the use of email as the primary means of direct communication over the web.</p>
<p>I will use a step by step example with screenshots as usual.</p>
<p>You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 &#8211; express editions work fine as well).</p>
<p>I will use VS 2010 Ultimate edition and C# as the .Net language of choice.</p>
<p>The main methods we are going to use reside in the <strong>System.Net.Mail</strong> class. Have a look <a href="http://www.systemnetmail.com/" target="_blank">here</a> for an excellent resource on <strong>System.Net.Mail.</strong></p>
<p>1) Create a new website with the VS version that you have and name it as you want.</p>
<p>2)  Now, before we begin to send any email we need to configure the smtp settings to indicate which mail server you will be talking to.Some people argue that you can set these settings programmatically.</p>
<p>My humble opinion is to set the settings for email sending declaratively in the <strong>web.config</strong> and more specifically in the <strong>mailSettings</strong> element.</p>
<p>So in the <strong>web.config</strong> type the following &#8211; obviously in your case you fill in your specific settings</p>
<p>&lt;system.net&gt;</p>
<p>&lt;mailSettings&gt;</p>
<pre>&lt;smtp from="nikos.kantzelis@mycompany.com"&gt;
&lt;network host="smtp.mycompany.com" port="25" userName="fofo" password="liverpool13" defaultCredentials="false"/&gt;
&lt;/smtp&gt;
&lt;/mailSettings&gt;
&lt;/system.net&gt;</pre>
<p>3) I have added a new web form in my website. I have named it &#8220;SendMail.aspx&#8221;. Set it as the start page. Add a reference to the <strong>System.Net.Mail namespace</strong>.</p>
<p>The main classes we are going to use are <strong>MailMessage</strong> and <strong>SmtpClient</strong>. Now let&#8217;s see how to send a plain-text email from an asp.net page.</p>
<p>4) In the <strong>Page_Load </strong>event handling routine of the <strong>SendMail.aspx</strong> page,  type ( obviously in your case you fill in your specific settings where applicable)</p>
<pre>MailMessage m = new MailMessage();

m.From = new MailAddress("nkantzelis@q-training.gr");
m.To.Add("nikolaosk@hotmail.com");
m.Subject = "Liverpool trip";
m.Body = "Are we going to Anfield this year?";

SmtpClient sc = new SmtpClient();
sc.Send(m);</pre>
<p>5) Run your application and if everything is configured correctly the email will be sent.</p>
<p>6) Most people that receive emails, probably your clients, would want their email to be sent as HTML formatted.</p>
<p>You might think that the easiest way to send an HTML-formatted email is just to write some markup into the body of your email.</p>
<p>The problem with this approach is that not all email clients are able to display HTML.</p>
<p>Users of some clients won’t be able to read your message easily because they’ll have to &#8220;go&#8221; through raw HTML to find it.</p>
<p>So the best way is to suit all clients. So the HTML version of the message is going to be as an alternative view.</p>
<p>In the <strong>Page_Load</strong> event handling routine comment out all the lines of code and type</p>
<pre> MailMessage m = new MailMessage();
 m.From = new MailAddress("nkantzelis@q-training.gr");
 m.To.Add("nikolaosk@hotmail.com");
 m.Subject = "Liverpool trip";
 m.Body = "Are we going to Anfield this year?";
 AlternateView html = AlternateView.CreateAlternateViewFromString(
 "Are we going to &lt;b&gt;Anfield&lt;/b&gt; this year?", null,
 "text/html");
 m.AlternateViews.Add(html);

 SmtpClient sc = new SmtpClient();
 sc.Send(m);</pre>
<p>You can read more about the alternative view class <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.alternateview.aspx" target="_blank">here</a>.</p>
<p>Run your application and if everything is configured correctly the email will be sent.</p>
<p>7) When you want to send content such as a Microsoft Word file, or a PDF file, you’ll need to send that file as an attachment to a mail message.</p>
<p>Comment out all the code you have typed so far. In the <strong>Page_Load</strong> event handling routine type</p>
<pre>  MailMessage mail = new MailMessage();
  mail.From = new MailAddress("nkantzelis@q-training.gr");
  mail.To.Add("nikolaosk@hotmail.com");
  mail.Subject = "Liverpool History";
  mail.Body = "Liverpool has won so far 18 championships";

  string path = Server.MapPath("~/test.doc");
  mail.Attachments.Add(new Attachment(path));

  SmtpClient client = new SmtpClient();
  client.Send(mail);</pre>
<p>The code above sends an attachment a file named <strong>test.doc</strong> that exists in the root of the web application.</p>
<p>Notice that we attach the file by creating an Attachmentobject and adding the object to the mail’s Attachments collection</p>
<p>Run your application and if everything is configured correctly the email with the attachment will be sent.</p>
<p>8) But what if the remote SMTP server is down or not responding?</p>
<p>What if the SMTP server is responding extremely slowly?</p>
<p>Your page won’t finish loading or displaying until the email is sent, or until an error is returned from the SMTP server.</p>
<p>Imagine the dissapointment-frustration on the user&#8217;s end. They will brand your application obsolete and unresponsive.</p>
<p>So in our final part of this post we will discuss on how to send emails from an asp.net page asynchronously.</p>
<p>The first thing to notice is to enable the boolean <strong>Async</strong> directive in the Page element.</p>
<p>So the Page directive becomes</p>
<pre>&lt;%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="SendMail.aspx.cs" Inherits="SendMail"  Async="true" %&gt;</pre>
<p>In the top of the SendMail.aspx.cs add a reference to these namespaces.</p>
<pre>using System.ComponentModel;
using System.Diagnostics;</pre>
<p>Sending email asynchronously is as easy as setting up a delegate and calling the <strong>SendAsync</strong> method.</p>
<p>In the <strong>Page_Load</strong> event handling routine comment out all the lines of code and type</p>
<pre> MailMessage m = new MailMessage
("nkantzelis@q-training.gr", "nikolaosk@hotmail.com", "Liverpool", "You will never walk alone.");

 SmtpClient sc = new SmtpClient();
 sc.SendCompleted += new SendCompletedEventHandler(MailSendCompleted);
 sc.SendAsync(m, m);</pre>
<p>Just after the end of the <strong>Page_Load</strong> event handling routine type the code</p>
<pre> public static void MailSendCompleted(
                     object sender, AsyncCompletedEventArgs e)
    {
        MailMessage mail = e.UserState as MailMessage;
        if (e.Cancelled)
        {
            Debug.Write("Email to " + mail.To + " was cancelled.");
        }
        if (e.Error != null)
        {
            Debug.Write("Email to " + mail.To + " failed.");
            Debug.Write(e.Error.ToString());
        }
        else
            Debug.Write("Message has been sent.");
    }</pre>
<p>Within the handler, we need to check the <strong>Cancelled</strong> and <strong>Error</strong> properties of the <strong>AsyncCompletedEventArgs</strong> object to ensure that nothing went wrong.</p>
<p>Run your application and if everything is configured correctly the email will be sent.</p>
<p>Leave a comment if you would like me to email you the code.</p>
<p>Hope it helps!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/email/'>email</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1211/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1211/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1211/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1211/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1211/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1211/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1211/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1211/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1211&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/05/send-email-within-asp-net-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Session State in ASP.Net</title>
		<link>https://dotnetstories.wordpress.com/2010/10/05/session-state-in-asp-net/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/05/session-state-in-asp-net/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 17:02:51 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[VB 2008]]></category>
		<category><![CDATA[Visual Basic 10.0]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[session state]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1208</guid>
		<description><![CDATA[In this post I will talk about ASP.Net State management. I will provide a hands on example with VS and VB.Net.

Before I go on with my example I would like to give a short introduction first.

Web applications are built on Hypertext Transfer Protocol (HTTP).  HTTP is a stateless protocol and each request to the server from the client is understood as an independent request.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1208&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I will talk about ASP.Net State management. I will provide a hands on example with VS and VB.Net.</p>
<p>Before I go on with my example I would like to give a short introduction first.</p>
<p>Web applications are built on Hypertext Transfer Protocol (HTTP).  HTTP is a stateless protocol and each request to the server from the client is understood as an independent request.</p>
<p>ASP.NET provides a powerful way to store a user’s session specific data using the Session State which is accessible as long as the user’s session is alive.</p>
<p>At some point we might need to access complex information such as custom objects.Obviously we can’t persist them to cookies.In our application we could have strict security requirements that prevents us  from storing information about a client in view state or in a custom cookie. In cases like that, we must use the built-in session state facility.We can store any type of data in memory on the server. The information is protected, because it is never transmitted to the client, and it’s uniquely bound to a specific session. Every client that accesses<br />
the application has a different session and a distinct collection of information. We could store in session state things such as the items in the current user’s shopping basket when the<br />
user browses from one page to another.</p>
<p>One might ask, &#8220;What is the mechanism for session tracking?&#8221;<br />
ASP.NET uses a unique 120-bit identifier and produces a unique value  that  evil people can’t reverse-engineer or “hack” the session ID a given client is using. This is the only piece of session-related information that is transmitted between the web server and the client.</p>
<p>The client presents the session ID, the what happens is that ASP.NET looks up the corresponding session, retrieves the objects stored and places them into a special collection so they can be accessed by our code.</p>
<p>The client must present the appropriate session ID with each request.</p>
<p>We can accomplish this in two ways:</p>
<p><strong>Cookies</strong>: In this case, the session ID is transmitted in a special cookie (named<br />
ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is<br />
used.<br />
<strong>Using URLs</strong>: In this case, the session ID is transmitted in a specially modified URL. This allows you to create applications that use session state with clients<br />
that don’t support cookies.<br />
Session state can slow down our application. It solves many of the problems associated with other forms of state management but places a heavy load on the server in terms of memory.<br />
If we have hundreds or thousands of clients access the site then the performance will be very bad.<br />
The last thing we want is to have an application that cannot scale gracefully.</p>
<p>I will be using VS 2010 Ultimate edition and VB.Net to create a simple asp.net application.<br />
We will use in our next example session state to store several <strong>Car</strong> objects.</p>
<p>1) Launch Visual Studio 2010/2008/2005.Express edition will suffice.</p>
<p>2) Create a web site with an appropriate name.</p>
<p>3) Add a class file in your site and name it <strong>Car.vb</strong>. The code should be like this</p>
<pre>Public Class Car
    Public Name As String
    Public Colour As String
    Public Cost As Double
    Public Sub New(ByVal name As String, _
    ByVal colour As String, ByVal cost As Double)
        Me.Name = name
        Me.Colour = Colour
        Me.Cost = cost
    End Sub
End Class</pre>
<p>4) Add a listbox,2 label controls and a button in the <strong>default.aspx</strong> page. Name the listbox control as <strong>lstItems</strong>, the 2 labels as <strong>lblSessionInfo</strong> and <strong>lblCarInfo</strong>. Leave the default name for the button control.</p>
<p>5) In the <strong>Page_Load</strong> event handling routine type</p>
<pre>If Me.IsPostBack = False Then
           
          
            Dim car1 As New Car("BMW", _
            "Blue", 32000)
            Dim car2 As New Car("VW Polo", _
            "Black", 18667)
            Dim car3 As New Car("Audi", _
            "Red", 30345)
            Dim car4 As New Car("Citroen", _
            "Gray", 9878)
          
            Session("mycar1") = car1
            Session("mycar2") = car2
            Session("mycar3") = car3
            Session("mycar4") = car4
        
            lstItems.Items.Add(car1.Name)
            lstItems.Items.Add(car2.Name)
            lstItems.Items.Add(car3.Name)
            lstItems.Items.Add(car4.Name)
        End If
      
        lblSessionInfo.Text = "Session ID: " &amp; Session.SessionID
        lblSessionInfo.Text &amp;= "&lt;br /&gt;Number of Objects: "
        lblSessionInfo.Text &amp;= Session.Count.ToString()
        lblSessionInfo.Text &amp;= "&lt;br /&gt;Mode: " &amp; Session.Mode.ToString()
        lblSessionInfo.Text &amp;= "&lt;br /&gt;Is Cookieless: "
        lblSessionInfo.Text &amp;= Session.IsCookieless.ToString()
        lblSessionInfo.Text &amp;= "&lt;br /&gt;Is New: "
        lblSessionInfo.Text &amp;= Session.IsNewSession.ToString()
        lblSessionInfo.Text &amp;= "&lt;br /&gt;Timeout (minutes): "
        lblSessionInfo.Text &amp;= Session.Timeout.ToString()</pre>
<p>The Car objects are created the first time when the page is loaded, and they’re stored in<br />
session state. The user can then choose from a list of car names. When a selection<br />
is made, the corresponding object will be retrieved, and its information will be displayed.The code is very simple.</p>
<p>6) Double click on the button and in the event handling routine type</p>
<pre>  If lstItems.SelectedIndex = -1 Then
            lblCarInfo.Text = "No item selected."
        Else
           
            Dim Key As String
            Key = "mycar" &amp; _
        (lstItems.SelectedIndex + 1).ToString()
           
            Dim TheCar As Car = CType(Session(Key), Car)
           
            lblCarInfo.Text = "Name: " &amp; TheCar.Name
            lblCarInfo.Text &amp;= "&lt;br /&gt;Color: "
            lblCarInfo.Text &amp;= TheCar.Colour
            lblCarInfo.Text &amp;= "&lt;br /&gt;Cost: " &amp; TheCar.Cost.ToString("c")
</pre>
<p>We retrieve the current Car object from Session like this</p>
<pre> Dim TheCar As Car = CType(Session(Key), Car)</pre>
<p>7) Run your application and see the names of the <strong>Car</strong> objects stored in the Session listed in the ListBox control. You will also see when the page loads useful information about the Session.</p>
<p>Select one car name and hit the button. You will see whole information about the specific car object stored in the session state.</p>
<p>Email me if you want the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/vb-2008/'>VB 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-basic-10-0/'>Visual Basic 10.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/session-state/'>session state</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1208/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1208&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/05/session-state-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Populate web server controls in ASP.Net applications from a web service</title>
		<link>https://dotnetstories.wordpress.com/2010/10/05/populate-web-server-controls-in-asp-net-applications-from-a-web-service/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/05/populate-web-server-controls-in-asp-net-applications-from-a-web-service/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 16:44:11 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[web service]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1205</guid>
		<description><![CDATA[In this post I would like to present you with a very simple example on how to create a simple web service that access data from a database.

Then we will create a consuming application that will consume the web service. I will use VS 2010 Ultimate edition and C# as the development language.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1205&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to present you with a very simple example on how to create a simple web service that access data from a database.</p>
<p>Then we will create a consuming application that will consume the web service. I will use VS 2010 Ultimate edition and C# as the development language.</p>
<p>I know that web services are explained in many places over the web but I will have a go.</p>
<p>They are small units of code that handle specific tasks (they convert kilometers to miles ) and are based on XML communication protocols.</p>
<p>They are great because they are independent of operating systems,languages,systems and devices.</p>
<p>Before you read on, I assume that you understand terms like <a href="http://www.w3schools.com/soap/default.asp" target="_blank">SOAP</a>, <a href="http://www.w3schools.com/wsdl/default.asp" target="_blank">WSDL</a> and <a href="http://www.w3schools.com/xml/default.asp" target="_blank">XML</a> .</p>
<p>1) Use VS 2010/2008/2005. Express editions will suffice. I am going to use the Pubs database. You can download the installation scripts of the Pubs database from <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&amp;displaylang=en" target="_blank">here</a>.</p>
<p>I am going to retrieve all the data from the <strong>Authors</strong> table.</p>
<p>2) Create a new project and choose asp.net web service application. You have this option from the available templates when you click <strong>File-&gt;New Project</strong>.</p>
<p>3) Add these namespaces at the top of the <strong>Service.cs</strong></p>
<pre>using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;
 
</pre>
<p>Also note that our web service class inherits from <strong>WebService</strong> base class and not from the <strong>Page</strong> class</p>
<pre>public class Service : System.Web.Services.WebService
</pre>
<p>4) In the <strong>web.config </strong>file in the <strong>&lt;connectionStrings&gt;</strong> add</p>
<pre>  &lt;connectionStrings&gt;
    &lt;add name="pubs" connectionString="Data Source=.;
Initial Catalog=pubs;Integrated Security=True"
        providerName="System.Data.SqlClient" /&gt;
  &lt;/connectionStrings&gt;</pre>
<p>5) Delete the <strong>Helloworld</strong> method. Under the <strong>[WebMethod]</strong></p>
<pre> public DataSet GetAuthors()
    {
        SqlConnection conn = new SqlConnection
(WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString);
        SqlDataAdapter myAdapter;
        DataSet productDataSet;
        string commandString = "Select * from Authors";
        myAdapter = new SqlDataAdapter(commandString, conn);
        productDataSet = new DataSet();
        myAdapter.Fill(productDataSet);
        return productDataSet;

    }</pre>
<p>I just get the connection string from the <strong>web.config</strong> using the <strong>WebConfigurationManager</strong> class and create a new <strong>connection</strong> object. I store my SQL Query in a string and then use the <strong>connection</strong> object and the string that stores the SQL query as paramaters when creating an <strong>Adapter</strong> object.Then I create a <strong>dataset</strong> and fill this dataset using the<strong>adapter</strong> object.</p>
<p>6) Build and run your application. You will see the service running and Invoke the <strong>GetAuthors</strong> method. Make sure it works.</p>
<p>7) Add a new item to your project, a <strong>web form</strong>.Leave the default name.</p>
<p>8) Add a <strong>Gridview</strong> web server control in the <strong>default.aspx</strong> page. Now we need to add a reference to the web service.Add <strong>Web Reference-&gt; Select Web services in this solution</strong> and type in the web reference the name, <strong>AuthService</strong></p>
<p>9) In the <strong>Page_Load</strong> event handling routine, type</p>
<pre> AuthorService.Service auth = new AuthorService.Service();
 GridView1.DataSource = auth.GetAuthors();
 GridView1.DataBind();</pre>
<p>We just create an object of the AuthorService.Service class (<strong>auth</strong>) and then it is very easy(we call the <strong>GetAuthors()</strong> method) to bind the results to the <strong>GridView</strong>.</p>
<p>10) Run your application and see the author data populating the <strong>GridView</strong> control.</p>
<p>Email me if you want the source code.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/c/'>C#</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/web-service/'>web service</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1205/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1205&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/05/populate-web-server-controls-in-asp-net-applications-from-a-web-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Using profile in ASP.Net applications</title>
		<link>https://dotnetstories.wordpress.com/2010/10/05/using-profile-in-asp-net-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2010/10/05/using-profile-in-asp-net-applications/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 16:33:30 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[profile]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1201</guid>
		<description><![CDATA[With Profile we store user specific data that is accessible anywhere in our ASP.Net application.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1201&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We all want when we visit a website to have some unique treatment (personalisation). Developers on the other side must devise mechanisms to remember our personal settings and preferences. This makes it more likely for us to return. ASP.Net developers must track users and save somehow their preferences between visits.</p>
<p>There are many ways to do that. Some are easy and some more complex. A lot of people seem not to know the profile feature that is in our disposal from ASP.NET 2.0.</p>
<p>With <strong>Profile</strong> we store user specific data that is accessible anywhere in our ASP.Net application.</p>
<p>We define properties using the <strong>web.config</strong> file. We use standard XML code to do that. ASP.NET reads the schema defined in web.config and automatically generates a class that is accessible from the <strong>Profile</strong> property on a page.</p>
<p>I am going to show you a small example of the <strong>Profile</strong> property.</p>
<p>I will be using VS 2010 Ultimate edition and <strong>C#</strong> to create a simple asp.net application.</p>
<p>1) Launch Visual Studio 2010/2008/2005.Express edition will suffice.</p>
<p>2) Create a web site with an appropriate name.</p>
<p>3) In the <strong>default.aspx</strong> add four <strong>TextBox</strong> controls and a <strong>button</strong>. Leave the default names.The markup should look like this</p>
<pre>Name: &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;
Age:&lt;asp:TextBox ID="TextBox2" runat="server"&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;
Url:&lt;asp:TextBox ID="TextBox3" runat="server"&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;
Comments: &lt;asp:TextBox ID="TextBox4" runat="server" TextMode=MultiLine&gt;
&lt;/asp:TextBox&gt;&lt;br /&gt;
&lt;asp:Button ID="Button1" runat="server" Text="Save to Profile" 
        onclick="Button1_Click" /&gt;</pre>
<p>4) Inside the <strong>web.config</strong>, in the <strong>&lt;system.web&gt;</strong> section add these lines of code</p>
<pre> &lt;profile&gt;
        &lt;properties&gt;
          &lt;add name="Name"/&gt;
          &lt;add name="Age"/&gt;
          &lt;add name="Url"/&gt;
          &lt;add name="Comments"/&gt;
        &lt;/properties&gt;
      &lt;/profile&gt;</pre>
<p>5) In the <strong>Button1_Click</strong> event handling routine type</p>
<pre> Profile.Name = TextBox1.Text;
 Profile.Age = TextBox2.Text;
 Profile.Url = TextBox3.Text;
 Profile.Comments = TextBox4.Text;</pre>
<p>6) Run your application and fill in the textbox values that will eventually be stored in the <strong>Profile</strong>.</p>
<p>7) Add another page in your site. Leave the default name. Add 4 <strong>Labels</strong> in the new page. The markup should look like this</p>
<pre>&lt;asp:Label ID="Label1" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;&lt;br /&gt;
&lt;asp:Label ID="Label2" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;&lt;br /&gt;
&lt;asp:Label ID="Label3" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;&lt;br /&gt;
&lt;asp:Label ID="Label4" runat="server" Text="Label"&gt;&lt;/asp:Label&gt;&lt;br /&gt;</pre>
<p>8) In the <strong>Page_Load</strong> event handling routine, type</p>
<pre> Label1.Text = Profile.Name ;
 Label2.Text=Profile.Age ;
 Label3.Text=Profile.Url;
 Label4.Text=Profile.Comments;</pre>
<p>9) Run your application( Set the <strong>Default.aspx</strong> as the start page ). Fill in the texboxes and click the button. Close the web browser.</p>
<p>10) Run the <strong>default2.aspx</strong> page. You will see the values from the <strong>Profile</strong> object appearing in the label controls.</p>
<p>You can use the Profile object to hard code values in the web.config that are important to your site. Do not forget that you can encrypt your site.</p>
<p>Imagine if you have a website and it has 100 pages. If the admin&#8217;s email changes then you need to update all 100 pages with the new admin&#8217;s email. I have seen that happening in one web site where</p>
<ul>
<li>It did not use a master page.</li>
<li>The admin&#8217;s email was not retrieved from the database.</li>
</ul>
<p>Email me if you need the source code.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/profile/'>profile</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1201/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1201&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/10/05/using-profile-in-asp-net-applications/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Tracing at application and page level in ASP.NET applications</title>
		<link>https://dotnetstories.wordpress.com/2010/08/24/tracing-at-application-and-page-level-in-asp-net-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2010/08/24/tracing-at-application-and-page-level-in-asp-net-applications/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 18:36:23 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[Visual Studio 2005]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[trace]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1181</guid>
		<description><![CDATA[When we debug our applications we need to have as much information as possible at our disposal. There are a lot of techniques and ways to achieve that.

One way to get lots of debugging information is to use Tracing. We can enable Tracing at the Page Level and Application Level. We can view the viewstate information and the events chain when a page is executing, among other things.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1181&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When we debug our applications we need to have as much information as possible at our disposal. There are a lot of techniques and ways to achieve that.</p>
<p>One way to get lots of debugging information is to use <strong>Tracing</strong>. We can enable Tracing at the <strong>Page Level</strong> and <strong>Application Level</strong>. We can view the viewstate information and the events chain when a page is executing, among other things.</p>
<p>Let&#8217;s see, how to enable Tracing at the Page level.</p>
<p>1) Start a new ASP.NET Web site with visual studio 2010 or an earlier version</p>
<p>2) Go to the default.aspx page in the  &#8220;Source View&#8221; and in the Page directive add this</p>
<pre><strong> </strong>Trace="true"</pre>
<p>The whole directive should like this</p>
<blockquote>
<h6 style="text-align:left;">&lt;%@ Page Title=&#8221;Home Page&#8221; <strong>Trace=&#8221;true&#8221;</strong> Language=&#8221;C#&#8221;<br />
MasterPageFile=&#8221;~/Site.master&#8221; AutoEventWireup=&#8221;true&#8221;<br />
CodeFile=&#8221;Default.aspx.cs&#8221; Inherits=&#8221;_Default&#8221; %&gt;</h6>
</blockquote>
<p>3) Run your application and see the tracing information in the <strong>Default.aspx</strong> page</p>
<p>Have a look at the picture below to see the various settings for enabling tracing at the page level. You can also set <strong>TraceMode</strong> to <strong>SortedByTime</strong> or <strong>SortByCategory</strong>.</p>
<p><a href="http://dotnetstories.files.wordpress.com/2010/08/trace.jpg"><img class="aligncenter size-full wp-image-1188" title="trace" src="http://dotnetstories.files.wordpress.com/2010/08/trace.jpg?w=460&#038;h=238" alt="" width="460" height="238" /></a></p>
<p>4) You can also use the Trace object in your code. Have a look at the code below</p>
<blockquote>
<pre>protected void Page_Load(object sender, EventArgs e)
    {
        Trace.Warn("this is my message");
        Trace.Write("this is another message");
    }</pre>
</blockquote>
<p>Run your application and see the messages printed in the screen. The <strong>Trace.Warn</strong> method outputs the message on the screen in red.</p>
<p>If you want to enable tracing at the application level, type the following in the web.config page</p>
<pre> &lt;trace enabled="true"/&gt;
</pre>
<p>Then run again your application. After the root of the application , in my case (http://localhost:13983/trace), type <strong>trace.axd</strong></p>
<p>The whole URL should look like this.</p>
<p>http://localhost:13983/trace/<strong>trace.axd</strong></p>
<p>In that page you can view trace details for all pages of the application.</p>
<p>Bear in mind that page level tracing settings overrides the tracing options at the application level.</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2005/'>Visual Studio 2005</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/trace/'>trace</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1181/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1181&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/08/24/tracing-at-application-and-page-level-in-asp-net-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>

		<media:content url="http://dotnetstories.files.wordpress.com/2010/08/trace.jpg" medium="image">
			<media:title type="html">trace</media:title>
		</media:content>
	</item>
		<item>
		<title>JQuery and ASP.Net &#8211; How to access all textboxes using JQuery</title>
		<link>https://dotnetstories.wordpress.com/2010/08/24/jquery-and-asp-net-how-to-access-all-textboxes-using-jquery/</link>
		<comments>https://dotnetstories.wordpress.com/2010/08/24/jquery-and-asp-net-how-to-access-all-textboxes-using-jquery/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 18:18:20 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1175</guid>
		<description><![CDATA[I am going to start a series of posts on ASP.Net and JQuery that will explain a lot of common tasks that can be accomplished using this fantastic open source Javascript library.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1175&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I am going to start a series of posts on ASP.Net and JQuery that will explain a lot of common tasks that can be accomplished using this fantastic open source Javascript library.</p>
<p>Initially I found out about JQuery when I did browse Scott&#8217;s Gu blog <a href="TextBox&gt;&lt;br /&gt; Now we need to modify our JQuery code.Add this code just below the code we entered in the &lt;head&gt; section of the Site.master page.    $('input[id$=btn2]').click(function (e) {                 e.preventDefault();                 $(&quot;#showselected&quot;).text('')                 .append($(&quot;input.sel&quot;).map(function () {                     return $(this).val() || null;                 }).get().join(&quot;&lt;br/&gt;  &quot;));             }); Run your application and check that everything works ok. Only the content of the last two textboxes will be shown.   I have tested this JQuery example with all the modern browsers.Please note that you do need to have a basic understanding of JQuery to fully understand this and the following JQuery &amp; Asp.net tutorials.  Hope it helps." target="_blank">post</a>. Have a look <a href="http://blog.jquery.com/2008/09/28/jquery-microsoft-nokia/" target="_blank">here</a> as well if you want to see the official announcement from the JQuery people.</p>
<p>It is widely known that JQuery ships now with Visual Studio. You can find it as a seperate download <a href="http://docs.jquery.com/Downloading_jQuery" target="_blank">here</a>.</p>
<p>Sadly, we canot cover the basics of JQuery in this post so here are a few resources for you to focus on</p>
<p>The main site is <a href="http://jquery.com/">this</a><br />
<a href="http://blog.jquery.com/" target="_blank">http://blog.jquery.com/</a><br />
<a href="http://docs.jquery.com/Main_Page" target="_blank">http://docs.jquery.com/Main_Page</a><br />
A fantastic <a href="http://docs.jquery.com/Main_Page" target="_blank">video series</a> for the absolute beginner.</p>
<p>In this first post I will show you how to access all textboxes using JQuery.</p>
<p>We will demonstrate this with a step by step example. I will use Visual Studio 2010. You can also use Visual Studio 2008 if you do not have Visual Studio 2010. Express editions work fine.</p>
<p>1) Create an ASP.Net website. Choose an appropriate name for your site.</p>
<p>2) Now we have the default web site ready. We will add some textboxes in the default.aspx page</p>
<p>so the code-markup looks like this</p>
<blockquote><p>&lt;asp:TextBox ID=&#8221;Txt1&#8243; runat=&#8221;server&#8221; Text=&#8221;MyFirstTextBox&#8221;&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;<br />
&lt;asp:TextBox ID=&#8221;Txt2&#8243; runat=&#8221;server&#8221; Text=&#8221;MySesondTextBox&#8221;&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;<br />
&lt;asp:TextBox ID=&#8221;Txt3&#8243; runat=&#8221;server&#8221; Text=&#8221;MyThirdTextBox&#8221;&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;<br />
&lt;asp:TextBox ID=&#8221;Txt4&#8243; runat=&#8221;server&#8221; Text=&#8221;MyFourthTextBox&#8221;&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;<br />
&lt;asp:Button ID=&#8221;btn1&#8243; runat=&#8221;server&#8221; Text=&#8221;Display&#8221; /&gt;<br />
&lt;p id=&#8221;showselected&#8221;&gt;&lt;/p&gt;</p></blockquote>
<p>3) In the <strong>Site.master</strong> file before the &lt;/head&gt; tag add this line of code</p>
<p><span style="color:#000000;"><strong>&lt;script src=&#8221;Scripts/jquery-1.4.1.js&#8221; type=&#8221;text/javascript&#8221;&gt;&lt;/script&gt;</strong></span></p>
<p>4)In the <strong>Site.master</strong> file before the <strong>&lt;/head&gt;</strong> tag add this line of code<br />
5) In the &lt;head&gt; section of the Site.master page we need to add the actual  JQuery code that makes the selection of the textboxes text possible</p>
<blockquote><p>&lt;script&gt;<br />
$(function () {<br />
$(&#8216;input[id$=btn1]&#8216;).click(function (e) {<br />
e.preventDefault();<br />
$(&#8220;#showselected&#8221;).text(&#8221;)<br />
.append($(&#8220;input:text&#8221;).map(function () {<br />
return $(this).val() || null;<br />
}).get().join(&#8220;&lt;br/&gt;  &#8220;));<br />
});</p>
<p>});<br />
&lt;/script&gt;</p></blockquote>
<p>When the button is clicked, the postback is prevented using e.preventDefault().We then use a<br />
Selector to match all input elements of type text (input:text) I am using the map function to iterate though the textbox controls.</p>
<p>We do apply a filter , which is that we do not want to have textboxes with empty values appended in the paragraph with id &#8220;showselected&#8221;. Run your application and check that everything works ok.</p>
<p>6) If you want to display only some textboxes you can use a class property.</p>
<p>So you can add in the markup</p>
<blockquote><p>&lt;asp:TextBox ID=&#8221;Txt5&#8243; runat=&#8221;server&#8221; Text=&#8221;MyFifthTextBox&#8221; CssClass=&#8221;sel&#8221;&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;<br />
&lt;asp:TextBox ID=&#8221;Txt6&#8243; runat=&#8221;server&#8221; Text=&#8221;MySixthTextBox&#8221; CssClass=&#8221;sel&#8221;&gt;&lt;/asp:TextBox&gt;&lt;br /&gt;</p></blockquote>
<p>Now we need to modify our JQuery code.Add this code just below the code we entered in the &lt;head&gt; section of the Site.master page.</p>
<blockquote><p>$(&#8216;input[id$=btn2]&#8216;).click(function (e) {<br />
e.preventDefault();<br />
$(&#8220;#showselected&#8221;).text(&#8221;)<br />
.append($(&#8220;input.sel&#8221;).map(function () {<br />
return $(this).val() || null;<br />
}).get().join(&#8220;&lt;br/&gt;  &#8220;));<br />
});<br />
Run your application and check that everything works ok. Only the content of the last two textboxes will be shown.</p></blockquote>
<p>I have tested this JQuery example with all the modern browsers.Please note that you do need to have a basic understanding of JQuery to fully understand this and the following JQuery &amp; Asp.net tutorials.</p>
<p>Hope it helps.</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2008/'>Visual Studio 2008</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/jquery/'>jquery</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1175/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1175/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1175/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1175/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1175/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1175/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1175/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1175/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1175&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/08/24/jquery-and-asp-net-how-to-access-all-textboxes-using-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Change the master page depending on the client&#8217;s browser</title>
		<link>https://dotnetstories.wordpress.com/2010/08/24/change-the-master-page-depending-on-the-clients-browser/</link>
		<comments>https://dotnetstories.wordpress.com/2010/08/24/change-the-master-page-depending-on-the-clients-browser/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 17:55:34 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[browser]]></category>
		<category><![CDATA[master page]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1164</guid>
		<description><![CDATA[In one of my seminars on ASP.Net, I was asked a question from a student regarding master pages and the various browser appications.

He basically asked if it was possible to have a different master page depending on the client's browser.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1164&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In one of my seminars on ASP.Net, I was asked a question from a student regarding master pages and the various browser appications.</p>
<p>He basically asked if it was possible to have a different master page depending on the client&#8217;s browser.</p>
<p>My initial answer was to find the browser&#8217;s version programmatically and according to this value to have a particular master page dynamically assigned during the <strong><span style="color:#000000;">PreInit</span></strong> stage of the Page lifecycle.</p>
<p>But there is a simpler way.At first we need to create a website using Visual Studio 2008/2010.</p>
<p>Then copy the original <strong><span style="color:#000000;">Site.master</span></strong> page to the root directory of the website and rename it to <span style="color:#000000;"><strong>AnotherSite.master</strong></span>.</p>
<p>Then we need to copy and paste in the root direcotory the Site.css and rename it to <strong><span style="color:#000000;">NewSite.css</span></strong>.</p>
<p>So we have now two master pages and two .css files.</p>
<p>Edit the <strong><span style="color:#000000;">AnotherSite.master</span></strong> and change the css reference</p>
<p>from</p>
<p><span style="color:#000000;"><strong>&lt;link href=&#8221;~/Styles/Site.css&#8221; rel=&#8221;stylesheet&#8221; type=&#8221;text/css&#8221; /&gt;</strong></span></p>
<p>to</p>
<p><span style="color:#000000;"><strong>&lt;link href=&#8221;~/Styles/NewSite.css&#8221; rel=&#8221;stylesheet&#8221; type=&#8221;text/css&#8221; /&gt;</strong></span><br />
Now we do need to make some changes to the <span style="color:#000000;"><strong><span style="color:#000000;">N</span></strong><strong>ewsite.css</strong></span> file.<br />
you can change the background color, for example</p>
<blockquote><p>body<br />
{<br />
background:#efefef;<br />
&#8230;.</p></blockquote>
<p>The page layout</p>
<blockquote><p>.page<br />
{<br />
width: 1200px;</p></blockquote>
<p>Now we can go add a new web form to our page. We will call it <strong><span style="color:#000000;">&#8220;Anotherpage.aspx&#8221;</span></strong>.</p>
<p>Select as a master page the <span style="color:#000000;"><strong>AnotherSite.master</strong></span>.</p>
<p>Then go to the &#8220;Source&#8221; of the newly created page and edit the Page directive according to the following line.</p>
<blockquote><p>&lt;%@ Page Title=&#8221;" Language=&#8221;C#&#8221; mozilla:MasterPageFile=&#8221;~/AnotherSite.master&#8221;<br />
ie:MasterPageFile=&#8221;~/Site.master&#8221; AutoEventWireup=&#8221;true&#8221;<br />
CodeFile=&#8221;MyNewPage.aspx.cs&#8221; Inherits=&#8221;MyNewPage&#8221; %&gt;</p></blockquote>
<p>Run your application with IE and Firefox and notice the respective masterpages<br />
being applied to the web page.<br />
Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/browser/'>browser</a>, <a href='https://dotnetstories.wordpress.com/tag/master-page/'>master page</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1164/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1164/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1164/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1164&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/08/24/change-the-master-page-depending-on-the-clients-browser/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Tableless menu control in ASP.Net 4.0</title>
		<link>https://dotnetstories.wordpress.com/2010/04/05/tableless-menu-control-in-asp-net-4-0/</link>
		<comments>https://dotnetstories.wordpress.com/2010/04/05/tableless-menu-control-in-asp-net-4-0/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 13:07:12 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[ASP.NET 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1153</guid>
		<description><![CDATA[One of the issues I really like to read and learn is client side technologies. I am an ASP.Net guy at heart but I find CSS particular useful and I have been blogging about CSS in my other  blog. Have a look here if you want to have a look at some interesting posts on [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1153&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the issues I really like to read and learn is client side technologies. I am an ASP.Net guy at heart but I find CSS particular useful and I have been blogging about CSS in my other  blog.</p>
<p>Have a look <a href="http://dotnetstories.wordpress.com/tag/css/" target="_blank">here</a> if you want to have a look at some interesting posts on CSS.</p>
<p>I believe in designing web applications and sites according to web standards. I do not think designing our websites with tables is correct.</p>
<p>Tables should be used for what they are good at doing, <strong>Display tabular data</strong> .</p>
<p>So if we are in charge of our web template we should use <strong>Divs</strong> and an external CSS file to style the main areas of our template.</p>
<p>When it comes to web server controls we have the issue of not being in charge of the HTML that is emitted from the asp.net engine.</p>
<p>In asp.net 4.0, we have more control of the HTML that is produced from the asp.net engine.</p>
<p>Let&#8217;s see a little example by using the ASP.Net menu web server control and how it renders its HTML in ASP.Net 4.0.</p>
<p>To follow along with this example you must have .Net framework and VS 2010 RC installed in your machine.</p>
<p>1) Launch VS 2010</p>
<p>2) Create a new web site by selecting ASP.Net website from the templates</p>
<p>3) Choose C# or VB as the development language.</p>
<p>4) Save your site with an appropriate filename in your local filesystem</p>
<p>5) Create an ASP.Net menu control on the <strong>default.aspx</strong>. Change the <strong>RenderingMode to Table</strong>. This is a new property in ASP.Net 4.0. What this makes is to instruct the asp.net engine to render HTML code for the menu control the old way.</p>
<p>Your code should be like this</p>
<div>
<p><strong> &lt;asp:Menu runat=&#8221;server&#8221; ID=&#8221;mymenu&#8221; RenderingMode=&#8221;Table&#8221;&gt;<br />
&lt;Items&gt;<br />
&lt;asp:MenuItem Text=&#8221;Orders&#8221; Value=&#8221;orders&#8221;&gt;</strong></p>
<p><strong>&lt;/asp:MenuItem&gt;</strong></p>
<p><strong>&lt;asp:MenuItem Text=&#8221;Sales&#8221; Value=&#8221;Sales&#8221;&gt;</strong></p>
<p><strong>&lt;/asp:MenuItem&gt;<br />
&lt;asp:MenuItem Text=&#8221;Customers&#8221; Value=&#8221;Customers&#8221;&gt;</strong></p>
<p><strong>&lt;/asp:MenuItem&gt;<br />
&lt;asp:MenuItem Text=&#8221;Employees&#8221; Value=&#8221;Employees&#8221;&gt;</strong></p>
<p><strong>&lt;/asp:MenuItem&gt;<br />
&lt;/Items&gt;</strong></p>
<p><strong>&lt;/asp:Menu&gt;</strong></p>
<p>6) Save your application and run it. Go to <strong>View-&gt;Source</strong> in the IE browser menu and see the HTML emitted.</p>
<p>It should be something like this. So it is styled like a table.</p>
<p><span style="color:#808080;"><em>&lt;table id=&#8221;MainContent_mymenu&#8221; class=&#8221;MainContent_mymenu_2&#8243; cellpadding=&#8221;0&#8243; cellspacing=&#8221;0&#8243; border=&#8221;0&#8243;&gt;<br />
&lt;tr onmouseover=&#8221;Menu_HoverStatic(this)&#8221; onmouseout=&#8221;Menu_Unhover(this)&#8221; onkeyup=&#8221;Menu_Key(this)&#8221; id=&#8221;MainContent_mymenun0&#8243;&gt;<br />
&lt;td&gt;&lt;table cellpadding=&#8221;0&#8243; cellspacing=&#8221;0&#8243; border=&#8221;0&#8243; width=&#8221;100%&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td style=&#8221;white-space:nowrap;width:100%;&#8221;&gt;&lt;a class=&#8221;MainContent_mymenu_1&#8243; href=&#8221;javascript:__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'orders&#8217;)&#8221;&gt;Orders&lt;/a&gt;&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/table&gt;&lt;/td&gt;<br />
&lt;/tr&gt;&lt;tr onmouseover=&#8221;Menu_HoverStatic(this)&#8221; onmouseout=&#8221;Menu_Unhover(this)&#8221; onkeyup=&#8221;Menu_Key(this)&#8221; id=&#8221;MainContent_mymenun1&#8243;&gt;<br />
&lt;td&gt;&lt;table cellpadding=&#8221;0&#8243; cellspacing=&#8221;0&#8243; border=&#8221;0&#8243; width=&#8221;100%&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td style=&#8221;white-space:nowrap;width:100%;&#8221;&gt;&lt;a class=&#8221;MainContent_mymenu_1&#8243; href=&#8221;javascript:__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'Sales&#8217;)&#8221;&gt;Sales&lt;/a&gt;&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/table&gt;&lt;/td&gt;<br />
&lt;/tr&gt;&lt;tr onmouseover=&#8221;Menu_HoverStatic(this)&#8221; onmouseout=&#8221;Menu_Unhover(this)&#8221; onkeyup=&#8221;Menu_Key(this)&#8221; id=&#8221;MainContent_mymenun2&#8243;&gt;<br />
&lt;td&gt;&lt;table cellpadding=&#8221;0&#8243; cellspacing=&#8221;0&#8243; border=&#8221;0&#8243; width=&#8221;100%&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td style=&#8221;white-space:nowrap;width:100%;&#8221;&gt;&lt;a class=&#8221;MainContent_mymenu_1&#8243; href=&#8221;javascript:__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'Customers&#8217;)&#8221;&gt;Customers&lt;/a&gt;&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/table&gt;&lt;/td&gt;<br />
&lt;/tr&gt;&lt;tr onmouseover=&#8221;Menu_HoverStatic(this)&#8221; onmouseout=&#8221;Menu_Unhover(this)&#8221; onkeyup=&#8221;Menu_Key(this)&#8221; id=&#8221;MainContent_mymenun3&#8243;&gt;<br />
&lt;td&gt;&lt;table cellpadding=&#8221;0&#8243; cellspacing=&#8221;0&#8243; border=&#8221;0&#8243; width=&#8221;100%&#8221;&gt;<br />
&lt;tr&gt;<br />
&lt;td style=&#8221;white-space:nowrap;width:100%;&#8221;&gt;&lt;a class=&#8221;MainContent_mymenu_1&#8243; href=&#8221;javascript:__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'Employees&#8217;)&#8221;&gt;Employees&lt;/a&gt;&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/table&gt;&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;/table&gt;</em></span></p>
<p>7) Change the <strong>RenderingMode to List, </strong>and build again your site.Go to <strong>View-&gt;Source</strong> in the IE browser menu and see the HTML emitted.</p>
<p>Youw will not see any tables. In its place you will see a list.Here it is.</p>
<p><em> <span style="color:#808080;">&lt;ul class=&#8221;level1&#8243;&gt;</span></em></p>
<p><span style="color:#808080;"><em><br />
&lt;li&gt;&lt;a class=&#8221;level1&#8243; href=&#8221;http://weblogs.asp.net/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=1153&amp;postid=7430143#&#8221; onclick=&#8221;__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'orders&#8217;)&#8221;&gt;Orders&lt;/a&gt;&lt;/li&gt;</em></span></p>
<p><span style="color:#808080;"><em>&lt;li&gt;&lt;a class=&#8221;level1&#8243; href=&#8221;http://weblogs.asp.net/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=1153&amp;postid=7430143#&#8221; onclick=&#8221;__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'Sales&#8217;)&#8221;&gt;Sales&lt;/a&gt;&lt;/li&gt;</em></span></p>
<p><span style="color:#808080;"><em>&lt;li&gt;&lt;a class=&#8221;level1&#8243; href=&#8221;http://weblogs.asp.net/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=1153&amp;postid=7430143#&#8221; onclick=&#8221;__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'Customers&#8217;)&#8221;&gt;Customers&lt;/a&gt;&lt;/li&gt;</em></span></p>
<p><span style="color:#808080;"><em>&lt;li&gt;&lt;a class=&#8221;level1&#8243; href=&#8221;http://weblogs.asp.net/controlpanel/blogs/posteditor.aspx?SelectedNavItem=Posts&amp;sectionid=1153&amp;postid=7430143#&#8221; onclick=&#8221;__doPostBack(&#8216;ctl00$MainContent$mymenu&#8217;,'Employees&#8217;)&#8221;&gt;Employees&lt;/a&gt;&lt;/li&gt;</em></span></p>
<p><span style="color:#808080;"><em><br />
&lt;/ul&gt;</em><br />
</span></p>
<p>It is so much easier to style menus with CSS when we have <strong>ul,li</strong> elements as the HTML semantic.</p>
<p>To see how to do that have a look <a href="http://dotnetstories.wordpress.com/2008/05/31/create-vertical-and-horizontal-navigation-menus-with-css/" target="_blank">here</a></p>
<p>Hope that helps!!!</p>
</div>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/asp-net-4-0/'>ASP.NET 4.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1153/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1153&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/04/05/tableless-menu-control-in-asp-net-4-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Hidden Div elements in ASP.Net 4.0</title>
		<link>https://dotnetstories.wordpress.com/2010/04/05/hidden-div-elements-in-asp-net-4-0/</link>
		<comments>https://dotnetstories.wordpress.com/2010/04/05/hidden-div-elements-in-asp-net-4-0/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 13:01:40 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[ASP.NET 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1148</guid>
		<description><![CDATA[This is a very short post for a new feature that ships with VS 2010 and ASP.Net 4.0. It is about the hidden fields in ASP.Net 4.0. We do know that ASP.Net is using hidden fields as a state control mechanism. It is used to preserve viewstate and control state. They are usually included in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1148&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a very short post for a new feature that ships with VS 2010 and ASP.Net 4.0.</p>
<p>It is about the hidden fields in ASP.Net 4.0. We do know that ASP.Net is using hidden fields as a state control mechanism. It is used to preserve viewstate and control state.</p>
<p>They are usually included in a <strong>div</strong> element, <strong>&lt;div&gt;&lt;/div&gt;</strong>.</p>
<p>So if you create a simple asp.net application with VS 2008 and .Net 3.5, run it, and view the source code from the browser,</p>
<p>you would see something like that</p>
<p><span style="color:#999999;"><em>&lt;div&gt;<br />
&lt;input type=&#8221;hidden&#8221; name=&#8221;__EVENTTARGET&#8221; id=&#8221;__EVENTTARGET&#8221; value=&#8221;" /&gt;<br />
&lt;input type=&#8221;hidden&#8221; name=&#8221;__EVENTARGUMENT&#8221; id=&#8221;__EVENTARGUMENT&#8221; value=&#8221;" /&gt;<br />
&lt;input type=&#8221;hidden&#8221; name=&#8221;__VIEWSTATE&#8221; id=&#8221;__VIEWSTATE&#8221; value=&#8221;/wEPDwUKLTQ0NTA1MjAxMmRkjIozh8I5q9vNjFXLeK/1IBsUwBM=&#8221; /&gt;<br />
&lt;/div&gt;</em></span></p>
<p>Sometimes if you style your <strong>div</strong> elements in your external css file, those rules that apply for all <strong>div</strong> elementsin your code, will apply for that <strong>&lt;div&gt;</strong> that surrounds the hidden field elements that deal with the viewstate.</p>
<p>Sometimes you can end up having a result in your browser window that is different from what you expected. The guilty part for that outcome can be the styling of those <strong>div</strong> tags that surround viewstate.</p>
<p>We have a small but very welcome change in ASP.Net 4.0</p>
<p>If you create a simple asp.net application with VS 2010 and view the source code after you run it, you will see something like this</p>
<p><span style="color:#999999;"><em><span style="color:#000000;"><strong>&lt;div class=&#8221;aspNetHidden&#8221;&gt;</strong></span><br />
&lt;input type=&#8221;hidden&#8221; name=&#8221;__VIEWSTATE&#8221; id=&#8221;__VIEWSTATE&#8221; value=&#8221;/wEPDwUJNzM3NjE2MDI3ZGRgQNiFxlXngQrLz2ewgBmti+Ee0T+BGCrLcGwY5QJnmQ==&#8221; /&gt;<br />
&lt;/div&gt;</em></span></p>
<p>As we can clearly see, ASP.NET 4 renders the <span class="input">div</span> element for hidden fields with a <strong>CSS class</strong>.</p>
<p>In that way we can differentiate the hidden fields <span class="input">div</span> from others.</p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/asp-net-4-0/'>ASP.NET 4.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1148/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1148&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/04/05/hidden-div-elements-in-asp-net-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>301 permanent redirects and ASP.Net 4.0</title>
		<link>https://dotnetstories.wordpress.com/2010/03/22/301-permanent-redirects-and-asp-net-4-0/</link>
		<comments>https://dotnetstories.wordpress.com/2010/03/22/301-permanent-redirects-and-asp-net-4-0/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 15:50:30 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[ASP.NET 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1142</guid>
		<description><![CDATA[We can permanently redirect traffic to the new pages without losing page rankings by using the 301 permanent redirect. RedirectPermanent help us to achieve that.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1142&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p> Hello all,</p>
<p>In this post, I would like to talk about a new method of the Response object that comes with ASP.Net 4.0.</p>
<p>The name of the method is <strong>RedirectPermanent</strong>.</p>
<p>Let&#8217;s talk a bit about 301 redirection and permanent redirection.301 redirect is the most efficient and <strong>Search Engine Friendly</strong> method for webpage redirection.</p>
<p>Let&#8217;s imagine that we have this scenario. This is a very common scenario. We have redesigned and move folders to some pages that have high search engine rankings. We do not want to lose those rankings.</p>
<p>We can permanently redirect traffic to the new pages without losing page rankings by using the 301 permanent redirect. <strong>RedirectPermanent</strong> help us to achieve that.</p>
<p>In order to demonstrate this new helper method, I will create the default asp.net website that comes with asp.net 4.0.</p>
<p>1) Fire VS 2010 and create a new website. Choose the filesystem to save your website ann VB as the .net language for this website</p>
<p>This is a much richer template that the previous ones that were created with VS 2008.</p>
<p>We have a <strong>Home</strong> page and an <strong>About </strong>page.</p>
<p>2) Create a new page and call it <strong>NewAbout</strong> (NewAbout.aspx)</p>
<p>3) Write some dummy content on it like &#8220;This is our new About us page&#8221;</p>
<p>4) Move to the <strong>About.aspx.vb</strong>, and in the page load event, type the following</p>
<p><strong>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load<br />
       <em> Response.RedirectPermanent(&#8220;~/NewAbout.aspx&#8221;)</em><br />
    End Sub</strong></p>
<p>5)  Now run your application and then click &#8220;About&#8221; page. You will permanently redirect to the new &#8220;NewAbout&#8221; page.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/asp-net-4-0/'>ASP.NET 4.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1142/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1142/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1142&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/03/22/301-permanent-redirects-and-asp-net-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.Net 4.0 and session state compression</title>
		<link>https://dotnetstories.wordpress.com/2010/03/22/asp-net-4-0-and-session-state-compression/</link>
		<comments>https://dotnetstories.wordpress.com/2010/03/22/asp-net-4-0-and-session-state-compression/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 15:46:43 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[ASP.NET 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1139</guid>
		<description><![CDATA[The important setting that was added in ASP.Net 4.0 is the last setting, compressionEnabled="true".<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1139&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hello folks,</p>
<p>In this post I would like to talk about a new feature of ASP.NET 4.0 -  <strong>easy state compression</strong>.</p>
<p>When we create web-asp.net applications the user must feel that whenever he interacts with the website, he actually interacts with something that can be safely described as an application.</p>
<p>What I mean by this is that is that during a postback the whole page is re-created and is sent back to the client in a fraction of a second. The server has no idea what the user does with the page.</p>
<p>If we had to work on that basis then we would not have an application but a series of disconnected web pages with no use at all.</p>
<p>In order to overcome this deficit, we do have various <strong>session state mechanisms</strong> that are well documented elsewhere on the internet.</p>
<p><strong>ASP.NET session state</strong> can identify requests from the same user during a specified time interval and gives us a way to preserve variable values for the duration of that session-time interval.</p>
<p>Here come the obvious question. Where are all those variables stored?</p>
<p><strong>ASP.NET session state</strong> supports several different storage options for session data. One of them is SQL Server.</p>
<p>All the variables data persist to a SQL Server database rather than being stored in memory.</p>
<p>We must create the tables and stored procedures that ASP.NET will look for on the SQL Server. Have a look here for more details on how to accomplish <a href="http://support.microsoft.com/kb/317604#appliesto" target="_blank">that</a>.</p>
<p>So what happens is that Session state is serialised into bytes and stored in those sql server tables.</p>
<p>Now we must add some configuration to our application. and how do we do that?</p>
<p>We do add some lines in the <strong>web.config</strong> file.Have a look</p>
<p><strong><span style="color:#800000;">&lt;sessionState allowCustomSqlDatabase=&#8221;true&#8221; sqlConnectionString=&#8221;data source=local;Initial Catalog=sessionstatedb&#8221; compressionEnabled=&#8221;true&#8221; /&gt; </span></strong></p>
<p>The important setting that was added in ASP.Net 4.0 is the last setting, <strong>compressionEnabled=&#8221;true&#8221;.</strong></p>
<p>This means that all the session data that is transferred between the client and the server can now be compressed, resulting in better performance.<span style="font-family:Calibri;font-size:small;"><br />
</span></p>
<p>Hope it helps!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a>, <a href='https://dotnetstories.wordpress.com/category/asp-net-4-0/'>ASP.NET 4.0</a>, <a href='https://dotnetstories.wordpress.com/category/visual-studio-2010/'>Visual Studio 2010</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1139/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1139&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/03/22/asp-net-4-0-and-session-state-compression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>Maintaining scroll position in ASP.Net applications</title>
		<link>https://dotnetstories.wordpress.com/2010/03/07/maintaining-scroll-position-in-asp-net-applications/</link>
		<comments>https://dotnetstories.wordpress.com/2010/03/07/maintaining-scroll-position-in-asp-net-applications/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 21:04:28 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[scroll position]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1132</guid>
		<description><![CDATA[How to maintain the scroll position-location when a postback occurs in an ASP.NET application<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1132&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the most common questions I get is &#8221; How to maintain the scroll position-location when a postback occurs in our ASP.NET application? &#8220;</p>
<p>A lot of times when  we click on a e.g a button in our application and a postback occurs, our application &#8220;loses&#8221; its scroll position.</p>
<p>The default behaviour is to go back to the top of the page.</p>
<p>There is a very nice feature in ASP.NET that enables us to maintain the scroll position in ASP.NET.</p>
<p>The name of this attribute is <strong>MaintainScrollPositionOnPostBack</strong>.</p>
<p>We can set the  <strong>MaintainScrollPositionOnPostBack=&#8221;true&#8221;</strong></p>
<p>we can do that within the <strong>Page</strong> directive e.g</p>
<p><strong>&lt;% Page Language =&#8221;C#&#8221;</strong> <strong>MaintainScrollPositionOnPostBack=&#8221;true&#8221; %&gt;</strong></p>
<p>So now the browser remembers where it was before the post back occured and knows how to keep track of the scroll position.</p>
<p>This is of course achieved with client-side Javascript code that it is injected into the page for us.</p>
<p>So if you go to View &#8211;&gt;Source in your browser window, you will see the generated Javascript code.</p>
<p>Hope it helps!!!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/scroll-position/'>scroll position</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1132/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1132&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/03/07/maintaining-scroll-position-in-asp-net-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
		<item>
		<title>How to deploy Asp.Net applications in retail mode</title>
		<link>https://dotnetstories.wordpress.com/2010/03/06/how-to-deploy-asp-net-applications-in-retail-mode/</link>
		<comments>https://dotnetstories.wordpress.com/2010/03/06/how-to-deploy-asp-net-applications-in-retail-mode/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 22:06:25 +0000</pubDate>
		<dc:creator>fofo</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[machine.config]]></category>
		<category><![CDATA[web.config]]></category>

		<guid isPermaLink="false">http://dotnetstories.wordpress.com/?p=1129</guid>
		<description><![CDATA[I have this friend of mine who is responsible of a team of asp.net developers that develop applications for people from all walks of life. One of his main concerns were that he had to check the deployment stage of every application very carefully and constantly had to correct common mistakes in the web.config file. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1129&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have this friend of mine who is responsible of a team of asp.net developers that develop applications for people from all walks of life.</p>
<p>One of his main concerns were that he had to check the deployment stage of every application very carefully and constantly had to correct common mistakes in the <strong>web.config </strong>file.</p>
<p>Some common mistakes in the <strong>web.config </strong>are detailed in this <a href="/dotnetstories/archive/2009/10/24/five-common-mistakes-in-the-web-config-file.aspx">post</a></p>
<p>One of the most common corrections is  to set</p>
<p><strong>&lt;compilation debug =&#8221;true&#8221;&gt;</strong> to <strong>&lt;compilation debug =&#8221;false&#8221;&gt;</strong></p>
<p>If we leave <strong>debug = &#8220;true&#8221;</strong> , we have an application that is less secure and not performing well.</p>
<p>It takes more time to compile. Memory usage is higher. Scripts and images cannot be cached.</p>
<p>His question was how to set  <strong>&lt;compilation debug =&#8221;false&#8221;&gt; </strong>to all web applications that are hosted under a particular server running IIS  &#8211; deployment machine.</p>
<p>We do know that lots of the settings in the <strong>web.config</strong> are inherited from the <strong>machine.config</strong>. The <strong>web.config</strong> settings can overwrite the settings in the <strong>machine.config</strong>.</p>
<p>Works like the cascading stylesheets ( the internal stylesheet overwrites the external, for the same property:value pair )</p>
<p>In order to have all our sites deployed in retail fashion we must open and edit the <strong>machine.config </strong>file. you can find this file in this path in your PC.</p>
<p><strong>C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG </strong></p>
<p>You can add these lines of code</p>
<p><strong>&lt;system.web&gt;</strong></p>
<p><strong> &lt;deployment retail=&#8221;true&#8221; /&gt;</strong></p>
<p><strong>&lt;/system.web&gt;</strong></p>
<p><span style="color:blue;"><span style="color:#000000;">This setting overrides application level security settings.</span></span></p>
<p>This means that even if we do have in our application <strong>web.config</strong> file this setting</p>
<p><strong>&lt;compilation debug =&#8221;true&#8221;&gt;</strong></p>
<p>it will just ignore it and force this web application of ours to behave like this</p>
<ul>
<li>debug set to false</li>
<li>disable page output tracing</li>
<li><span style="color:blue;"><span style="color:#000000;">custom error pages to be shown to the remote users instead of detailed error messages or the stack trace</span></span></li>
</ul>
<p><span style="color:blue;"><span style="color:#000000;">We should not edit <strong>machine.config</strong> too often, unless we have to.<br />
</span></span></p>
<p>Hope it helps !!!</p>
<br />Filed under: <a href='https://dotnetstories.wordpress.com/category/aspnet/'>asp.net</a> Tagged: <a href='https://dotnetstories.wordpress.com/tag/machine-config/'>machine.config</a>, <a href='https://dotnetstories.wordpress.com/tag/web-config/'>web.config</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetstories.wordpress.com/1129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetstories.wordpress.com/1129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetstories.wordpress.com/1129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetstories.wordpress.com/1129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetstories.wordpress.com/1129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetstories.wordpress.com/1129/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetstories.wordpress.com/1129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetstories.wordpress.com/1129/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetstories.wordpress.com&amp;blog=1661705&amp;post=1129&amp;subd=dotnetstories&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://dotnetstories.wordpress.com/2010/03/06/how-to-deploy-asp-net-applications-in-retail-mode/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/ecbfd3584f3b2c0c3f528bacdfc15e0a?s=96&#38;d=https%3A%2F%2Fsecure.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">fofo</media:title>
		</media:content>
	</item>
	</channel>
</rss>
