Configure WCF Service – Reuse Collection Types Issue

December 14, 2009 14:22 by wjchristenson2

In VS 2008, there is a problem with reusing collection types when you configure a WCF service and wish to “Reuse types in all refrenced assemblies”.  If you want to pass collections around via your WCF service, a Visual Studio will create a proxy class for each collection type regardless whether your collection type is included within referenced assemblies or not.  I will show you how to bypass this shortcoming.

First, locate the Reference.svcmap file for the WCF service reference you are having problems with.  If you can’t see it, ensure your project  has “Show All Files” enabled.  If you open the Reference.svcmap, you’ll find that it is written in XML.  Locate the CollectionMappings node.  Within CollectionMappings, add your collection type so when you update your service reference, it recognizes it as a known type and will not generate a proxy class for you.  Hope this helps.


   1:  <CollectionMappings>
   2:      <CollectionMapping TypeName="System.Collections.Generic.List`1" Category="List" />
   3:      <CollectionMapping TypeName="WpfApplication1.Objects.MyCollection" Category="List" />
   4:  </CollectionMappings>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Fiddler - Inspecting WCF Binary Encoded Messages

November 25, 2009 08:57 by wjchristenson2

Fiddler is the tool of choice when it comes to inspecting WCF messages that utilize an HTTP transport.  In a previous post I mentioned that HTTP WCF messages should be in encoded in a binary format to decrease their size.  The problem you run into when encoding your WCF messages is that when Fiddler attempts to inspect an encoded message, it’s not in a readable format.  To resolve this limitation, you can download a free plug-in which will add an inspector to Fiddler to decode binary WCF message.  Using this new inspector, you can inspect binary encoded WCF messages freely from within Fiddler.

http://code.msdn.microsoft.com/wcfbinaryinspector



Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Silverlight 3 WCF Binary Message Encoding

October 14, 2009 13:29 by wjchristenson2

Silverlight 3 offers us some new features when it comes to WCF web services.  In Silverlight 2, BasicHttpBinding was the only supported binding.  This essentially encodes your serialized objects in clear text and sends them over an HTTP transport.  Because the objects were sent as clear text, the message size could get out-of-hand.  When sending data across HTTP/Internet, you obviously want to decrease the size as this will improve performance of your client application.  Silverlight 3 offers the ability to create custom bindings which support the ability to encode your WCF web service messages as a binary format.

Binary encoding offers some serious performance gains over text encoding.  Personally I’ve seen 30% – 40% reduction in message size between the server and client when binary encoding is enabled.  Keep in mind that binary encoding is a WCF-specific feature.  Therefore if you have heterogeneous technologies wanting to consume your service, you’ll need to stick with BasicHttpBinding.  Here is an example of how to enable binary encoding for your WCF service:


   1:  <bindings>
   2:     <customBinding>
   3:        <binding name="binaryHttpBinding">
   4:           <binaryMessageEncoding />
   5:           <httpTransport />
   6:        </binding>
   7:     </customBinding>
   8:  </bindings>
   9:   
  10:  <endpoint address="" binding="customBinding" bindingConfiguration="binaryHttpBinding" contract="MyService" />

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Introduction to SQL Server Change Tracking

October 3, 2009 12:39 by wjchristenson2

An all too familiar challenge of today’s applications is to support the mobile user.  A mobile user is not always guaranteed to have a connection to the home office.  They need an application that can support both offline and online connection states.  An application that is occasionally connected is often referred to as an “Occasionally Connected Application” (OCA).  OCAs will often work offline and when brought online will execute synchronization processes.  In this blog, I’ll briefly introduce some nice features included with SQL Server 2008 Change Tracking.

SQL Server has had replication features for quite some time now.  I’m by no means an expert when it comes to SQL Server Transactional replication, but personally I’ve found it difficult to setup, troubleshoot, customize, and unable to easily communicate across N-Tier application environments.  In the past, the next option from replication was to create our own SQL synchronization engines utilizing triggers, timestamp columns, tombstone tables, etc to track database changes on the client and server and then synchronize up the differences.  There are some problems with this solution.  First glaring issue to me is the use of triggers.  Triggers cause transactions to take longer to commit and cause blocking issues.  So basically performance and storage issues result from this solution prior to SQL 2008 Change Tracking.  SQL 2008 now provides a new feature which is available in all versions: SQL Change Tracking. 

SQL Server Change Tracking Advantages/Features:

1)  Easy to Setup.  It does not require timestamp columns, tombstone tables, triggers, etc.  You can simply script or use SQL Management Studio to turn on SQL Change Tracking for a database and then what tables you want to track changes on.

2)  Better Performance.  Changes are tracked at commit time rather than when DML operations occur.  What this basically means is transactions run quicker and this also helps with blocking issues.

3)  Minimal Disk Space Costs.  Change Tracking stores changes in SQL system tables and the disk space cost is minimal.

4)  Integrates with the .NET Sync Framework.  If you are using the .NET Sync Framework to develop your OCA, then .NET/Visual Studio has some nice features that are at the developer’s disposal.

5)  Synchronize with other DB Platforms.  SQL Change Tracking runs independently from other databases.  So if your server is running an Oracle DB and you want to run SQL Compact on your client with Change Tracking enabled, it will support that just fine.  Changes on the client are tracked independently of the server and obviously vice versa.

6)  Packaged Functions.  SQL Server comes with packaged functions that are used to query the SQL Change Tracking system tables to acquire incremental changes.

7)  Auto Clean Up.  When SQL Change Tracking is enabled for a database, you can specify when change history will be purged automatically for you.

8)  Column or Entire Row.  You can enable change tracking to record that an entire row/record had something changed in it or you can even track down to what column was changed to limit the amount of data changes returned when querying for incremental changes.

Example 1 - Turn on SQL Change Tracking for a Database:


   1:  ALTER DATABASE [AdventureWorks2008] SET CHANGE_TRACKING = ON (CHANGE_RETENTION = 365 DAYS, AUTO_CLEANUP = ON);
   2:  GO

Example 2 – Turn on SQL Change Tracking for a Table:


   1:  ALTER TABLE HumanResources.[Department] ENABLE CHANGE_TRACKING WITH (TRACK_COLUMNS_UPDATED = OFF);
   2:  GO

Example 3 – Return Incremental Table Inserts:


   1:  DECLARE @sync_last_received_anchor BIGINT, @sync_new_received_anchor BIGINT;
   2:   
   3:  SELECT @sync_last_received_anchor = CHANGE_TRACKING_CURRENT_VERSION();
   4:   
   5:  INSERT INTO [HumanResources].[Department] (Name, GroupName, ModifiedDate) VALUES ('Test1', 'My Group', GETDATE())
   6:  INSERT INTO [HumanResources].[Department] (Name, GroupName, ModifiedDate) VALUES ('Test2', 'My Group', GETDATE())
   7:  INSERT INTO [HumanResources].[Department] (Name, GroupName, ModifiedDate) VALUES ('Test3', 'My Group', GETDATE())
   8:   
   9:  SELECT @sync_new_received_anchor = CHANGE_TRACKING_CURRENT_VERSION();
  10:   
  11:  --return inserts
  12:  SELECT dept.*
  13:  FROM [HumanResources].[Department] AS dept 
  14:      INNER JOIN CHANGETABLE(CHANGES [HumanResources].[Department], @sync_last_received_anchor) CT ON CT.[DepartmentID] = dept.[DepartmentID]
  15:  WHERE (CT.SYS_CHANGE_OPERATION = 'I' AND CT.SYS_CHANGE_CREATION_VERSION <= @sync_new_received_anchor)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

ExecuteNonQuery with “GO” Separators

September 25, 2009 08:26 by wjchristenson2

If you’ve ever tried to run a collection of SQL batches via the .NET DbCommand.ExecuteNonQuery method, you probably received an error similar to the following: “Incorrect Syntax near ‘GO’ …”.  DbCommand.ExecuteNonQuery is intended to execute a single SQL batch statement against a database.  The “GO” separator is a command that is used/understood by SQL Server Query Analyzer and Query Editor utilities to separate out SQL batches when ran.

There has been some workarounds that I’ve seen that involve regular expressions and string manipulation/splitting to break out the script with “GO” separators into a collection of SQL statements and run them each individually.  This can work, but you will run into situations where commented areas will contain the “GO” statement and other problems can/will arise.  Such situations would cause the workaround to fail.

The proper way to run scripts with the “GO” separator is to employ SQL Server Management Objects (SMOs).  Microsoft’s SQL Server 2008 Feature Pack contains links to download/install the SMO assemblies (.NET Framework object model) .  Developers can use SMOs to perform SQL Server management routines through their .NET application code.

Steps to Use SMOs:

1) Download and Install SMOs - Download the SQL Server Management Objects found on this page.  Run the installation package.  If you are running SQL Server 2005, you may need to search for the 2005 version as the link I gave is for 2008.

2) Add references - After the SMOs are installed,  we’ll need to add references to them in our project.  The SMO assemblies should appear under your .NET tab when adding references to your project.  If you can’t  find them there, the assemblies were installed to “C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies” for me.  To run scripts with “GO” statement, we’ll need references to the following DLLs:
  a) Microsoft.SqlServer.ConnectionInfo.dll
  b) Microsoft.SqlServer.Management.Sdk.Sfc.dll
  c)  Microsoft.SqlServer.Smo.dll

3) Import the required namespaces and execute your SQL script with “GO” statements like below:


   1:  Imports System.Data.SqlClient
   2:  Imports Microsoft.SqlServer.Management.Smo
   3:  Imports Microsoft.SqlServer.Management.Common
   4:   
   5:  Class Window1
   6:   
   7:      Public Sub ExecuteSqlStatements(ByVal connectionString As String, ByVal sqlStatements As String)
   8:          If Not String.IsNullOrEmpty(sqlStatements) Then
   9:              Using mySqlConnection As SqlConnection = New SqlConnection(connectionString)
  10:                  Dim mySqlServer As Server = New Server(New ServerConnection(mySqlConnection))
  11:                  mySqlServer.ConnectionContext.ExecuteNonQuery(sqlStatements)
  12:              End Using
  13:          End If
  14:      End Sub
  15:   
  16:  End Class

SqlBatchExecNonQuery_Soln.zip (965.09 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Silverlight Custom Content Control with Events

July 6, 2009 13:40 by wjchristenson2

In an earlier post, I wrote about how to develop a Silverlight custom content control.  Since then I’ve received inquiries as to how to add events to it.  More specifically, how can we add interactivity to the control and have the control raise events which can be handled by the consumer of our control.

Step 1: Add Template UI Elements to Receive User Interaction

In the previous post, I described how to create a generic.xaml file to house our templated control UI (style).  In this example, I am going to create a close HyperlinkButton and raise a close event.  Here’s our style which is defined in the generic.xaml file.  Take not of our new hlbClose HyperlinkButton (line 34).


   1:  <ResourceDictionary 
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:      xmlns:local="clr-namespace:ContentControlExample.Controls">
   5:   
   6:      <!-- CustomContentControl -->
   7:      <Style TargetType="local:CustomContentControl">
   8:          <Setter Property="Background" Value="Transparent" />
   9:          <Setter Property="Foreground" Value="Black" />
  10:          <Setter Property="BorderBrush" Value="Transparent" />
  11:          <Setter Property="BorderThickness" Value="0" />
  12:          <Setter Property="HorizontalAlignment" Value="Stretch" />
  13:          <Setter Property="VerticalAlignment" Value="Stretch" />
  14:          <Setter Property="HorizontalContentAlignment" Value="Left" />
  15:          <Setter Property="VerticalContentAlignment" Value="Top" />
  16:          <Setter Property="Template">
  17:              <Setter.Value>
  18:                  <ControlTemplate TargetType="local:CustomContentControl">
  19:                      <Border Background="White" BorderBrush="#87AFDA" BorderThickness="1">
  20:                          <Grid>
  21:                              <Grid.RowDefinitions>
  22:                                  <RowDefinition Height="Auto" />
  23:                                  <RowDefinition Height="*" />
  24:                              </Grid.RowDefinitions>
  25:                              
  26:                              <Border Grid.Column="0" Grid.Row="0" Background="#D4E6FC" BorderThickness="0,0,0,1" BorderBrush="#87AFDA">
  27:                                  <Grid>
  28:                                      <Grid.ColumnDefinitions>
  29:                                          <ColumnDefinition />
  30:                                          <ColumnDefinition Width="20" />
  31:                                      </Grid.ColumnDefinitions>
  32:                                  
  33:                                      <ContentControl Grid.Column="0" Content="{TemplateBinding Header}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Foreground="#224499" FontWeight="Bold" FontFamily="Arial" FontSize="12" Margin="3,3,3,3" />
  34:                                      <HyperlinkButton x:Name="hlbClose" Grid.Column="1" Content="[X]" />
  35:                                  </Grid>
  36:                              </Border>
  37:                              <ContentControl Grid.Column="0" Grid.Row="1" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Cursor="{TemplateBinding Cursor}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" FontFamily="Arial" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" Foreground="{TemplateBinding Foreground}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" />
  38:                          </Grid>
  39:                      </Border>
  40:                  </ControlTemplate>
  41:              </Setter.Value>
  42:          </Setter>
  43:      </Style>
  44:  </ResourceDictionary>

Step 2: Get a Handle to Template UI Elements

Once we have our control UI looking the way we want it, the next step is to get a handle to our HyperlinkButton and add a handler for its click event.  When the user clicks the HyperlinkButton, we want to raise our control’s Close event.  The trick is to override the OnApplyTemplate of our control and get our handle to the HyperlinkButton using the GetTemplateChild method.  The GetTemplateChild method accepts the id/name of the control we are looking for.  It traverses the visual tree and returns a DependencyObject if found.  Below I show how we can do this:


   1:  Public Class CustomContentControl
   2:      Inherits ContentControl
   3:   
   4:      Private _hlbClose As HyperlinkButton
   5:   
   6:      Public Shared ReadOnly HeaderProperty As DependencyProperty = DependencyProperty.Register("Header", GetType(UIElement), GetType(CustomContentControl), Nothing)
   7:      Public Event Close(ByVal sender As CustomContentControl)
   8:   
   9:      Public Property Header() As UIElement
  10:          Get
  11:              Return DirectCast(Me.GetValue(CustomContentControl.HeaderProperty), UIElement)
  12:          End Get
  13:          Set(ByVal value As UIElement)
  14:              Me.SetValue(CustomContentControl.HeaderProperty, value)
  15:          End Set
  16:      End Property
  17:   
  18:      Public Sub New()
  19:          MyBase.New()
  20:          Me.DefaultStyleKey = GetType(CustomContentControl)
  21:      End Sub
  22:   
  23:      Public Overrides Sub OnApplyTemplate()
  24:          MyBase.OnApplyTemplate()
  25:          _hlbClose = DirectCast(GetTemplateChild("hlbClose"), HyperlinkButton)
  26:          AddHandler _hlbClose.Click, AddressOf hlbClose_Click
  27:      End Sub
  28:   
  29:      Private Sub hlbClose_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
  30:          RaiseEvent Close(Me)
  31:      End Sub
  32:  End Class

Step 3: Raise Control Events

Now that we have acquired a handle to our HyperlinkButton and also have added a handler for its click event, all we have to do now is raise our control’s Close event when the HyperlinkButton is clicked.  The control consumers can handle the close event if they wish.


   1:      Private Sub hlbClose_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
   2:          RaiseEvent Close(Me)
   3:      End Sub

ContentControlExample_Soln.zip (627.32 kb)


Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Get Child, Parent, or Children Objects in Silverlight

June 17, 2009 18:10 by wjchristenson2

As a programmer, you may have situations where you need a handle to a control to set its property programmatically.  Pretty simple right?  Let’s add some complexity.  What if you are not guaranteed to know exactly where the control resides.  Is it in our Grid at child index 0 or is it in a StackPanel within the Grid?  What if we want to set the background of all Canvas objects on our page to Transparent?

The Silverlight API provides the VisualTreeHelper class to assist with the traversal of the visual object tree.  Silverlight has a logical and visual object tree.  The visual tree is a subset of the logical object tree and is only populated by objects that have rendering implications.  In a general sense, a collection class would not be included in the visual tree however the Grid you are using as your LayoutRoot of your page would be.  The VisualTreeHelper class has 3 methods to assist with the visual object tree: GetChild(), GetChildrenCount(), GetParent().  Their names are self-descriptive and what I’d like to do is create a few recursive helper methods/extensions to these methods that are a bit more powerful.


Helper Method #1: GetParentObject

This method returns the first parent of a given type and/or name of an object’s parent hierarchy.  For instance, let’s say you know that our StackPanel resides somewhere in the bowels of a Grid named LayoutRoot.  To get a handle to LayoutRoot we could do the following:


   1:  Dim g As Grid = GetParentObject(Of Grid)(myStackPanel, "LayoutRoot")

Helper Method #2: GetChildObject

This method returns the first child of a given type and/or name of an object’s child hierarchy.  So let’s take the inverse of the above.  We have a StackPanel named myStackPanel that resides somewhere beneath our Grid LayoutRoot.  The get the handle to myStackPanel we could do the following:


   1:  Dim sp As StackPanel = GetChildObject(Of StackPanel)(Me.LayoutRoot, "myStackPanel")


Helper Method #3: GetChildObjects

This method returns a list collection of all children of a given type and/or name of an object’s child hierarchy.  So let’s say we want all rectangles which reside somewhere on our page.  Again, our page has a Grid named LayoutRoot.  We could get a list collection of all rectangles on the page by making the following call:


   1:  Dim rectangles As List(Of Rectangle) = GetChildObjects(Of Rectangle)(Me.LayoutRoot)


Helper Methods

Below is the actual methods’ code.  I’m also attaching my zipped test solution.


   1:  Module Common
   2:      ''' <summary>
   3:      ''' Navigates up the object's parent hierarchy and returns the first parent match of the specified type and/or object name.
   4:      ''' </summary>
   5:      ''' <typeparam name="T"></typeparam>
   6:      ''' <param name="obj"></param>
   7:      ''' <param name="name"></param>
   8:      ''' <returns></returns>
   9:      ''' <remarks></remarks>
  10:      Public Function GetParentObject(Of T As FrameworkElement)(ByVal obj As DependencyObject, Optional ByVal name As String = "") As T
  11:          Dim parent As DependencyObject = VisualTreeHelper.GetParent(obj)
  12:   
  13:          While parent IsNot Nothing
  14:              If TypeOf parent Is T AndAlso (CType(parent, T).Name = name Or String.IsNullOrEmpty(name)) Then
  15:                  Return CType(parent, T)
  16:              End If
  17:   
  18:              parent = VisualTreeHelper.GetParent(parent)
  19:          End While
  20:   
  21:          Return Nothing
  22:      End Function
  23:   
  24:      ''' <summary>
  25:      ''' Recursively searches an object's child hierarchy and returns the first child match of the specified type and/or object name.
  26:      ''' </summary>
  27:      ''' <typeparam name="T"></typeparam>
  28:      ''' <param name="obj"></param>
  29:      ''' <param name="name"></param>
  30:      ''' <returns></returns>
  31:      ''' <remarks></remarks>
  32:      Public Function GetChildObject(Of T As FrameworkElement)(ByVal obj As DependencyObject, Optional ByVal name As String = "") As T
  33:          Dim child As DependencyObject = Nothing, grandChild As T = Nothing
  34:   
  35:          For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
  36:              child = VisualTreeHelper.GetChild(obj, i)
  37:   
  38:              If TypeOf child Is T AndAlso (CType(child, T).Name = name Or String.IsNullOrEmpty(name)) Then
  39:                  Return CType(child, T)
  40:              Else
  41:                  grandChild = GetChildObject(Of T)(child, name)
  42:                  If grandChild IsNot Nothing Then Return grandChild
  43:              End If
  44:          Next
  45:   
  46:          Return Nothing
  47:      End Function
  48:   
  49:      ''' <summary>
  50:      ''' Recursively searches an object's child hierarchy and returns the all children that are of the specified type and/or object name.
  51:      ''' </summary>
  52:      ''' <typeparam name="T"></typeparam>
  53:      ''' <param name="obj"></param>
  54:      ''' <param name="name"></param>
  55:      ''' <returns></returns>
  56:      ''' <remarks></remarks>
  57:      Public Function GetChildObjects(Of T As FrameworkElement)(ByVal obj As DependencyObject, Optional ByVal name As String = "") As List(Of T)
  58:          Dim child As DependencyObject = Nothing, childList As List(Of T) = New List(Of T)
  59:   
  60:          For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
  61:              child = VisualTreeHelper.GetChild(obj, i)
  62:   
  63:              If TypeOf child Is T AndAlso (CType(child, T).Name = name Or String.IsNullOrEmpty(name)) Then
  64:                  childList.Add(CType(child, T))
  65:              End If
  66:   
  67:              childList.AddRange(GetChildObjects(Of T)(child))
  68:          Next
  69:   
  70:          Return childList
  71:      End Function
  72:  End Module

VisualTreeHelper_Soln.zip (589.38 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Common Table Expressions – What are They?

May 26, 2009 13:48 by wjchristenson2

Microsoft SQL 2005 introduced a new construct called CTEs (common table expressions).  CTEs provide a way to break down complex queries into simpler chunks and offer more readable queries.  UDFs, derived tables, and temp tables are all constructs that can be employed to help break up complex queries, however they often muddy up your SQL script.  They also exist beyond the context of the one SQL statement you may have desired to use it for.  CTEs also provide the ability for recursion without the need for recursive stored procedures.

Therefore, at a high level CTEs are used for:

1) Improving readability of your SQL scripts.

2)  Simplifying complex queries.

3)  Recursion.

A Simple CTE Example:


   1:  WITH OrderTotals (OrderID, OrderTotal) AS (
   2:      SELECT OrderDetails.OrderID, SUM(((OrderDetails.UnitPrice * OrderDetails.Quantity) - OrderDetails.Discount)) AS OrderTotal 
   3:      FROM dbo.[Order Details] AS OrderDetails WITH (NOLOCK)
   4:      GROUP BY OrderDetails.OrderID
   5:  )
   6:  SELECT * FROM dbo.Orders WITH (NOLOCK)
   7:      INNER JOIN OrderTotals ON OrderTotals.OrderID = Orders.OrderID
   8:  WHERE OrderTotals.OrderTotal > 100

In this first simple example, I used the Northwind database to find all orders which exceeded $100.  The first step is to use the keyword WITH and then name my CTE, define my columns, then enclose what SQL makes up the CTE within parenthesis.  I then proceed to use the CTE in the final query.  Notice how the final query is much simpler to read without the GROUP BY, SUM, etc logic in the CTE.

Two CTEs Example:


   1:  WITH OrderTotals (OrderID, OrderTotal) AS (
   2:      SELECT OrderDetails.OrderID, SUM(((OrderDetails.UnitPrice * OrderDetails.Quantity) - OrderDetails.Discount)) AS OrderTotal 
   3:      FROM dbo.[Order Details] AS OrderDetails WITH (NOLOCK)
   4:      GROUP BY OrderDetails.OrderID
   5:  ), OrdersMoreThan100 (OrderID, OrderTotal) AS (
   6:      SELECT OrderTotals.* FROM OrderTotals WHERE OrderTotals.OrderTotal > 100
   7:  )
   8:  SELECT * FROM dbo.Orders WITH (NOLOCK)
   9:      INNER JOIN OrdersMoreThan100 ON OrdersMoreThan100.OrderID = Orders.OrderID;

In this example, we get a little more complex with our CTEs.  Here we can see that you can comma delimit as many CTEs as you want.  I also reference the first CTE within my second CTE and simplify our final SQL statement even further.

CTE Gotchas/Notes:

1) Always terminate SQL with a “;” before you declare a CTE.

2) You can use CTEs with SELECT, UPDATE, INSERT, DELETE queries.

3) CTEs can only be used by the final SQL statement (the statement following the CTE definitions).  Subsequent SQL queries will not be able to use your CTE definitions.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Set an Enum Dependency Property with XAML

April 23, 2009 09:10 by wjchristenson2

Some new light has been shed on this topic in a Silverlight.net forum thread found here: http://silverlight.net/forums/t/91790.aspx

My explanation below assumes that custom logic is needed when converting from a string to an enumerated type.  The above thread shows how to setup an Enumurated Type dependency property and .NET will convert from string the the enumerated type just fine.

I'm going to leave the post below as there are going to be situations where you may want to use a TypeConverter.

***************************************************************************

There are situations where you want to set a property's value in XAML and .NET is unable to convert the string value to the property's type.  I’ve created a solution which provides an example of how to fix this using a TypeConverter.

The TypeConverter will basically tell .NET that we can convert a string to our type and furthermore, we will provide the logic on how to convert it to our custom type.

First step is to create our TypeConverter.  In my example, I have a vehicle control and we are going to set the type of vehicle.  Here is the code for our VehicleTypeConverter.


   1:  Imports System.ComponentModel
   2:   
   3:  Public Class VehicleTypeConverter
   4:      Inherits TypeConverter
   5:   
   6:      Public Overrides Function CanConvertFrom(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal sourceType As System.Type) As Boolean
   7:          If sourceType.Equals(GetType(String)) Then
   8:              Return True
   9:          Else
  10:              Return MyBase.CanConvertFrom(context, sourceType)
  11:          End If
  12:      End Function
  13:   
  14:      Public Overrides Function CanConvertTo(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal destinationType As System.Type) As Boolean
  15:          If destinationType.Equals(GetType(String)) Then
  16:              Return True
  17:          Else
  18:              Return MyBase.CanConvertTo(context, destinationType)
  19:          End If
  20:      End Function
  21:   
  22:      Public Overrides Function ConvertFrom(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object) As Object
  23:          If TypeOf value Is String Then
  24:              Try
  25:                  Return CType([Enum].Parse(GetType(Vehicle.VehicleType), value, True), Vehicle.VehicleType)
  26:              Catch
  27:                  Throw New InvalidCastException(value)
  28:              End Try
  29:          Else
  30:              Return MyBase.ConvertFrom(context, culture, value)
  31:          End If
  32:      End Function
  33:   
  34:      Public Overrides Function ConvertTo(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object, ByVal destinationType As System.Type) As Object
  35:          If destinationType.Equals(GetType(String)) Then
  36:              Return value.ToString()
  37:          Else
  38:              Return MyBase.ConvertTo(context, culture, value, destinationType)
  39:          End If
  40:      End Function
  41:  End Class

As I noted earlier, this class tells .NET that strings are allowed to be converted to our type property and we also provide the logic on how to convert the string value to the type.  Now that we have this converter defined, we can use it in our control, page, or wherever our type property is being used.  I’m using it in the vehicle control.  Here’s how we use the TypeConverter.


   1:  Imports System.ComponentModel
   2:   
   3:  Partial Public Class Vehicle
   4:      Inherits UserControl
   5:   
   6:      Public Enum VehicleType
   7:          NA = 0
   8:          Car = 1
   9:          Bus = 2
  10:          Truck = 3
  11:      End Enum
  12:   
  13:      Public Shared ReadOnly TypeProperty As DependencyProperty = DependencyProperty.Register("Type", GetType(VehicleType), GetType(Vehicle), New PropertyMetadata(VehicleType.NA, AddressOf TypeChangedHandler))
  14:   
  15:      <TypeConverter(GetType(VehicleTypeConverter))> _
  16:      Public Property Type() As VehicleType
  17:          Get
  18:              Return DirectCast(GetValue(Vehicle.TypeProperty), VehicleType)
  19:          End Get
  20:          Set(ByVal value As VehicleType)
  21:              SetValue(Vehicle.TypeProperty, value)
  22:          End Set
  23:      End Property
  24:   
  25:      Public Sub New()
  26:          InitializeComponent()
  27:      End Sub
  28:   
  29:      Private Shared Sub TypeChangedHandler(ByVal o As DependencyObject, ByVal args As DependencyPropertyChangedEventArgs)
  30:          DirectCast(o, Vehicle).OnTypeChanged(DirectCast(args.NewValue, VehicleType))
  31:      End Sub
  32:   
  33:      Private Sub OnTypeChanged(ByVal newValue As VehicleType)
  34:          Me.tbkTest.Text = "The vehicle type is a " & newValue.ToString() & "."
  35:      End Sub
  36:   
  37:  End Class

Everything is straight forward here except for how we wire in our VehicleTypeConverter.  We add attributes to our Type property to tell the property that we will handle the converting from and to the VehicleType.

Below you’ll find the entire solution if you wish to see it in action.

EnumDependencyProperty_Soln.zip (597.05 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Silverlight Custom Content Control

March 30, 2009 07:10 by wjchristenson2

As a Silverlight control developer, you may encounter a need to create a custom content control.  This type of control allows the consumers to place anything they want in certain areas of your control.  In Silverlight, you may have noticed that the Button control has a content property.  You can essentially put anything you want in a button.  I’m going to show you how you can create a control to do this.

We are going to create a control that has a header and body.  The final result will look like the image below:

 

Step 1 – Setup the Solution

The first step in creating our control is to ensure that our Visual Studio environment is setup correctly.  We’ll have our basic Silverlight Application project and Web Project to test it in.  However, we are going to add a Silverlight Class Library project and add a reference to it in our Silverlight Application project.

The next step is what gets a lot of developers.  Add a “themes” folder in our controls project (Silverlight Class Library project). Inside the “themes” folder, add a new text file and name it “generic.xaml”.  Make sure that the folder/file names are lower case!

 

Silverlight 2 does not support themes like WPF does.  However, inserting the “themes/generic.xaml” file inside our controls project does yield us the ability to define our CustomContentControl style/template.

 

Step 2 – Create the Custom Content Control

Now that our solution is ready, let’s add our CustomContentControl to our controls project.  We’ll be inheriting from the ContentControl object.  Therefore by default, we’ll already have a Content property.  However we want to create an additional Header property so that other developers can put whatever they want in the header.  Here’s our CustomContentControl code:


   1:  Public Class CustomContentControl
   2:      Inherits ContentControl
   3:   
   4:      Public Shared ReadOnly HeaderProperty As DependencyProperty = DependencyProperty.Register("Header", GetType(UIElement), GetType(CustomContentControl), Nothing)
   5:   
   6:      Public Property Header() As UIElement
   7:          Get
   8:              Return DirectCast(Me.GetValue(CustomContentControl.HeaderProperty), UIElement)
   9:          End Get
  10:          Set(ByVal value As UIElement)
  11:              Me.SetValue(CustomContentControl.HeaderProperty, value)
  12:          End Set
  13:      End Property
  14:   
  15:      Public Sub New()
  16:          MyBase.New()
  17:          Me.DefaultStyleKey = GetType(CustomContentControl)
  18:      End Sub
  19:   
  20:  End Class

Here we have our control which inherits from ContentControl and has a Header property defined.  There’s one last thing to mention about our control.  Check out line 17.  We set the DefaultStyleKey to a resource object which we are going to define in our generic.xaml file.  So let’s do that.

 

Step 3 – Create Control’s DefaultStyleKey (generic.xaml)

In step 2 we saw that after our CustomContentControl was instantiated we immediately wired up its DefaultStyleKey.  In the generic.xaml file we’ll define our style/template for our CustomContentControl.  The style will automatically be found and used for our control.  Here’s the style for our control:


   1:  <ResourceDictionary 
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:      xmlns:local="clr-namespace:ContentControlExample.Controls">
   5:   
   6:      <!-- CustomContentControl -->
   7:      <Style TargetType="local:CustomContentControl">
   8:          <Setter Property="Background" Value="Transparent" />
   9:          <Setter Property="Foreground" Value="Black" />
  10:          <Setter Property="BorderBrush" Value="Transparent" />
  11:          <Setter Property="BorderThickness" Value="0" />
  12:          <Setter Property="HorizontalAlignment" Value="Stretch" />
  13:          <Setter Property="VerticalAlignment" Value="Stretch" />
  14:          <Setter Property="HorizontalContentAlignment" Value="Left" />
  15:          <Setter Property="VerticalContentAlignment" Value="Top" />
  16:          <Setter Property="Template">
  17:              <Setter.Value>
  18:                  <ControlTemplate TargetType="local:CustomContentControl">
  19:                      <Border Background="White" BorderBrush="#87AFDA" BorderThickness="1">
  20:                          <Grid>
  21:                              <Grid.RowDefinitions>
  22:                                  <RowDefinition Height="Auto" />
  23:                                  <RowDefinition Height="*" />
  24:                              </Grid.RowDefinitions>
  25:                              
  26:                              <Border Grid.Column="0" Grid.Row="0" Background="#D4E6FC" BorderThickness="0,0,0,1" BorderBrush="#87AFDA">
  27:                                  <ContentControl Content="{TemplateBinding Header}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Foreground="#224499" FontWeight="Bold" FontFamily="Arial" FontSize="12" Margin="3,3,3,3" />
  28:                              </Border>
  29:                              <ContentControl Grid.Column="0" Grid.Row="1" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Cursor="{TemplateBinding Cursor}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" FontFamily="Arial" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" Foreground="{TemplateBinding Foreground}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" />
  30:                          </Grid>
  31:                      </Border>
  32:                  </ControlTemplate>
  33:              </Setter.Value>
  34:          </Setter>
  35:      </Style>
  36:  </ResourceDictionary>

At a quick glance take note that we have a ContentControl for both the Header and Content properties of our CustomContentControl.  When the template is bound, the Header and Content values will be placed inside our ContentControls defined here.

 

Step 4 – Use the CustomContentControl

Now that we have the solution setup, our control coded, and our default style/template defined in the generic.xaml file, we can use our control.  Here’s the page XAML that uses the control.


   1:  <UserControl x:Class="ContentControlExample.Page"
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:      xmlns:ex="clr-namespace:ContentControlExample.Controls;assembly=ContentControlExample.Controls"
   5:      Width="300" Height="200">
   6:      <Grid x:Name="LayoutRoot" Background="White">
   7:          <ex:CustomContentControl x:Name="myCustomContentControl">
   8:              <ex:CustomContentControl.Header>
   9:                  <TextBlock Text="This is the Header" />
  10:              </ex:CustomContentControl.Header>
  11:              <ex:CustomContentControl.Content>
  12:                  <StackPanel Orientation="Vertical" Margin="5">
  13:                      <TextBlock Text="This is the body or content." Margin="0,0,0,5" />
  14:                      <Button Content="Click Me!" Width="100" Height="30" />
  15:                  </StackPanel>
  16:              </ex:CustomContentControl.Content>
  17:          </ex:CustomContentControl>
  18:      </Grid>
  19:  </UserControl>

If you wish to add events to your custom content control, I've written another post which can be found here.

ContentControlExample_Soln.zip (619.31 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5