Blog Archives

Get the Primary Key PropertyInfo of any Linq-to-SQL Table

Easily find any table’s Primary Key property

In my search for a universal generic Get() accessor for Linq-to-SQL DataContexts, I figured I would have to dynamically find the primary key of a table.
Using Reflection and the Attributes applied to L2S tables, it is not difficult at all:

//get the primary key PropertyInfo table 'Product'
PropertyInfo info = GetPrimaryKey<Product>();

It’s just that easy, it will throw a NotSupportedException if there is no primary key, or the primary key allows NULL.
It uses the Linq-to-SQL ColumnAttribute properties to determine what the primary key is.
If there is more than one primary key, it will just use the first one it comes across.

The complete source code can be browsed at my new Utilities Library along with full documentation on CodePlex, just figured it would be easy to keep all of my utilities in one place.
Otherwise, here is the meat of the code:

public static PropertyInfo GetPrimaryKey<T>()
{
  PropertyInfo[] infos = typeof(T).GetProperties();
  PropertyInfo PKProperty = null;
  foreach (PropertyInfo info in infos)
  {
    var column = info.GetCustomAttributes(false)
     .Where(x => x.GetType() == typeof(ColumnAttribute))
     .FirstOrDefault(x =>
      ((ColumnAttribute)x).IsPrimaryKey &&
      ((ColumnAttribute)x).DbType.Contains("NOT NULL"));
  if (column != null)
  {
    PKProperty = info;
    break;
  }
  if (PKProperty == null)
  {
    throw new NotSupportedException(
      typeof(T).ToString() + " has no Primary Key");
  }
  return PKProperty;
}

And yes, I did come up with a universal generic Get() accessor for Linq-to-SQL DataContexts, that’s next post… or the code is already posted in my Utilities Library.

FileStream Save() Extension – Easily Save Your FileStreams with the Option of No-Overwrite

an extension to allow fast simple saving without worrying about overwriting a file

With these extensions, you can save a FileStream as simple as this:

fs.Save(@"C;/file.txt");

Now if you run it again, it will save another file named file[1].txt, then file[2].txt and so on.
If you want to overwrite a file, simply state true for the overwrite flag:

fs.Save(@"C;/file.txt", true);

Here is the code:

public static string Save(this FileStream file,
  string path)
{ return file.Save(path, false); }
public static string Save(this FileStream file,
  string path, bool overwrite)
{
  int count = 1;
  string folder = Path.GetDirectoryName(path);
  if (!Directory.Exists(folder))
    Directory.CreateDirectory(folder);
  int fileSize = Convert.ToInt32(file.Length);
  string fileName = Path.GetFileName(file.Name);
  Byte[] bytes = new Byte[fileSize];
  file.Read(bytes, 0, fileSize);
  string root = Path.GetDirectoryName(path) +
    "\" + Path.GetFileNameWithoutExtension(path);

  while (!overwrite && File.Exists(path))
  {
    path = root + "[" + count++.ToString() +
      "]" + Path.GetExtension(path);
  }

  File.WriteAllBytes(path, bytes);
  return Path.GetFileName(path);
}

Parsing Strings to Enums with a Simple Univeral Extension

getting an enum to a string is easy, but switching back can be a pain

If I have an enum:

public enum WhatToShow { All, Courses, Seminars };

and I want to turn a string “Courses” back into that enum Type, there are a few ways I could do it. The most basic way would be to use a switch statement; that is a pain, especially for large enums, plus it has to be re-written for each enum. Here is a simple extension you can use to convert strings back into enums:

public static T ToEnum<T>(this string strOfEnum)
{
    return (T)Enum.Parse(typeof(T), strOfEnum);
}

Now if I have a simple string, it is simple to turn it back to an enum:

string str = "Courses";
WhatToShow en = str.ToEnum<WhatToShow>();

Passing Multiple Records to a Stored Procedure in SQL Server

There are so many different ways to work with data that it can make your head spin.  Regardless of the technology, one thing I always try to do when working with databases is minimize the number of calls that are made.  I use ORM frameworks a lot so I have to make sure that my code doesn’t end up calling the database a ton and being overly “chatty”. 

My company is currently working on a large Silverlight 3 application for a customer and have a requirement to allow CSV file uploads through the application.  That’s pretty straightforward to do with Silverlight but in looking through the CSV file there can be 1000s of records and there is a lot of custom functionality around each record.  Initially I was going to handle the business rules and insertion for each row individually.  However, once I saw how many rows were involved I backed off my initial approach since that would mean a single file upload could trigger thousands and thousands of calls to the database which certainly isn’t efficient.  Instead of going that route I decided it would be better to pass all of the rows into a stored procedure and let it handle everything.  That way I can make a single database connection yet handle inserting (and updating and deleting based upon the business rules) many records. 

So how can you pass multiple records into a stored procedure?  Back in “the day” I’d pass in delimited strings and then parse them.  Although that technique probably wasn’t the most efficient, it got the job done.  With SQL Server 2005 and higher we have access to a much more efficient technique due to the availability of XQuery.  The current project I’m working on relies on SQL Server 2005 behind the scenes so that’s what I’ll focus on here.  Note that SQL Server 2008 allows .NET DataTable objects to be passed when using table value parameters as well in a stored procedure.  See www.codeproject.com/KB/database/sqlserver2008.aspx for an overview of the table value parameter functionality.

For the import I can serialize the list of records to XML and then pass them into a stored procedure.  It appears that you can pass an XmlDocument object from .NET if the stored procedure takes an XML input parameter type.  However, I never got it to work properly doing that so I pass a string containing serialized XML data and then load it into the XML data type.  The stored procedure can then use XQuery to convert the XML into actual rows.  Here’s some code that handles parsing a flat file, converting the data into a List<JobMaterialImport>, serializing the list into XML and then passing the serialized XML data to a stored procedure named ImportJobMaterials.

public List<ImportJobMaterialsResult> ImportJobMaterials(int jobID, Stream stream, string coNumber, string coDesc, string xmlMapFile)
{
    //Convert flat file to List<JobMaterialImport> using converter and XML mapping file
    //Mapping file passed from FlatFileHandler.ashx in web project
    FlatFileToObjectConverter<JobMaterialImport> converter = new FlatFileToObjectConverter<JobMaterialImport>(stream, xmlMapFile);
    List<JobMaterialImport> imports = converter.ConvertToList();
    imports = imports.Take(imports.Count - 2).ToList(); //last rows are bogus in flat-file

    //Generate XML and pass to sproc
    using (StringWriter sw = new StringWriter())
    {
        XmlSerializer xs = new XmlSerializer(typeof(List<JobMaterialImport>));
        xs.Serialize(sw, imports);
        try
        {
            //Pass materials into sproc
            string xml = sw.ToString().Replace("utf-16", "utf-8");
            return this.DataContext.ImportJobMaterials(xml, jobID, coNumber, coDesc).ToList();
        }
        catch (Exception exp)
        {
            Logger.Log("Error in JobManagementRepository.ImportJobMaterials", exp);
        }
    }
    return null;
}

 

The XML that’s generated from the code above looks like the following.  Security Note: We’ll assume that appropriate measures have been taken to clean the data and ensure it doesn’t contain any bad stuff related to injection attacks. That’s especially important if you’ll be running any dynamic SQL in your stored procedure.  I’m not, but I thought I’d be a good citizen and point it out…always sanitize your data with some Clorox before using it. :-)

<ArrayOfJobMaterialImport xmlns:xsi="www.w3.org/2001/XMLSchema-instance" xmlns:xsd="www.w3.org/2001/XMLSchema">
  <JobMaterialImport>
    <Area>BUILDING A</Area>
    <Phase>LIGHTING</Phase>
    <WorkCode>0</WorkCode>
    <WorkCodeTitle>Manually Assigned</WorkCodeTitle>
    <Description>4x1 1/2in. SQ BOX COMB KO</Description>
    <Quantity>2</Quantity>
    <TotalHours>10.46</TotalHours>
  </JobMaterialImport>
  <JobMaterialImport>
    <Area>BUILDING A</Area>
    <Phase>LIGHTING</Phase>
    <WorkCode>0</WorkCode>
    <WorkCodeTitle>Manually Assigned</WorkCodeTitle>
    <Description>#8x   3/4 P/H SELF-TAP SCREW</Description>
    <Quantity>4</Quantity>
    <TotalHours>0.28</TotalHours>
  </JobMaterialImport>
  <JobMaterialImport>
    <Area>BUILDING A</Area>
    <Phase>LIGHTING</Phase>
    <WorkCode>605</WorkCode>
    <WorkCodeTitle>Wiring and System Devices</WorkCodeTitle>
    <Description>1G TGL SWITCH PLATE - PLASTIC IVY</Description>
    <Quantity>2</Quantity>
    <TotalHours>0.89</TotalHours>
  </JobMaterialImport>
</ArrayOfJobMaterialImport>

 

Here’s what the stored procedure looks like:

 

CREATE PROCEDURE [ImportJobMaterials]
    @JobMaterialsXml AS VARCHAR(MAX),
    @JobID AS INT,
    @ChangeOrderNumber AS VARCHAR(10) = NULL,
    @ChangeOrderDescription AS VARCHAR(100) = NULL
AS
    BEGIN
        DECLARE @XML AS XML

        DECLARE @MaterialsTable TABLE
        (
            ID INT IDENTITY(1,1),
            Area VARCHAR(250),
            Phase VARCHAR(250),
            WorkCodeID INT,
            WorkCodeTitle VARCHAR(250),
            MaterialTitle VARCHAR(250),
            Quantity DECIMAL(18,2),
            TotalHours DECIMAL(18,2)
        )

        SELECT @XML = @JobMaterialsXml

        INSERT INTO @MaterialsTable (Area, Phase, WorkCodeID, WorkCodeTitle, MaterialTitle, Quantity, TotalHours)
        SELECT M.Item.query('./Area').value('.','VARCHAR(250)') Area,
               M.Item.query('./Phase').value('.','VARCHAR(250)') WorkCode,
               M.Item.query('./WorkCodeID').value('.','INT') WorkCodeID,
               M.Item.query('./WorkCodeTitle').value('.','VARCHAR(250)') WorkCodeTitle,
               M.Item.query('./MaterialTitle').value('.','VARCHAR(250)') MaterialTitle,
               M.Item.query('./Quantity').value('.','DECIMAL(18,2)') Quantity,
               M.Item.query('./TotalHours').value('.','DECIMAL(18,2)') TotalHours
        FROM @XML.nodes('/ArrayOfJobMaterialImport/JobMaterialImport') AS M(Item)

        --Process the data        
    END

Once the XML data comes in it’s converted into an XML data type using SELECT @XML = @JobMaterialsXml syntax.  The key part of the T-SQL code is the SELECT statement that grabs each value from the XML data type and looks for specific child nodes.  If the child nodes were attributes instead then you would do something like M.Item.value(‘@attributeName’,’DBType’).  Each JobMaterialImport node in the XML is located by the @XML.nodes(‘/ArrayOfJobMaterialImport/JobMaterialImport’) AS M(Item) code.  What’s nice about this approach is that a single call can be made to the database yet 1000s of records can be processed.  Not optimal for every situation, but exactly what I needed and fairly straightforward to use.

Requiring SSL For ASP.NET MVC Controllers

There are quite a few posts out there about switching to SSL when a user visits specific areas of a website but I figure the more the merrier so here’s yet another one.

My company is in the process of rolling out an ASP.NET MVC site for a client and specific actions and controllers need to have SSL running to ensure that no sensitive information gets out such as passwords and credit cards.  If a user visits the site using http:// I need to switch them to https:// in certain parts of the website.  Fortunately, ASP.NET MVC is quite extensible so it only took about 4-5 minutes to get a simple solution in place. 

The easiest way I know of to switch to SSL for specific controllers or actions is to create an ActionFilterAttribute that handles redirecting them to an https:// address.  Classes that derive from ActionFilterAttribute can be placed immediately above actions or even controllers in cases where the filter needs to apply to all actions in the controller.  For my situation I needed entire controllers to be SSL-enabled so I placed the attribute above the controller class name.

Here’s an example of the simple RequiresSSL attribute class:

using System;
using System.Web;
using System.Web.Mvc;

namespace Helpers
{
    public class RequiresSSL : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase req = filterContext.HttpContext.Request;
            HttpResponseBase res = filterContext.HttpContext.Response;

            //Check if we're secure or not and if we're on the local box
            if (!req.IsSecureConnection && !req.IsLocal)
            {
                string url = req.Url.ToString().ToLower().Replace("http:", "https:");
                res.Redirect(url);
            }
            base.OnActionExecuting(filterContext);
        }
    }
}


A couple of people (thanks Jon and Phil) commented that the ToLower() call I had above could cause consequences with QueryString data.  I could take ToString() out but some people may type “HTTP” instead of “http” which would mess up the replace call.  For the current application I’m working on I only have integers being passed around on the QueryString so it didn’t affect me at all but it definitely could affect string data being passed.  The suggestion was to use the UriBuilder class and after thinking it through more I agree.  Here’s a different version of the RequiresSSL class that uses the UriBuilder class.

 

using System;
using System.Web;
using System.Web.Mvc;

namespace Helpers
{
    public class RequiresSSL : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase req = filterContext.HttpContext.Request;
            HttpResponseBase res = filterContext.HttpContext.Response;

            //Check if we're secure or not and if we're on the local box
            if (!req.IsSecureConnection && !req.IsLocal)
            {
                var builder = new UriBuilder(req.Url)
                {
                    Scheme = Uri.UriSchemeHttps,
                    Port = 443
                };
                res.Redirect(builder.Uri.ToString());
            }
            base.OnActionExecuting(filterContext);
        }
    }
}


The RequiresSSL attribute can then be placed above the appropriate action or controller:

[HandleError]
[RequiresSSL]
public class AccountController : Controller
{
    ...
}


If you’re running IIS7 and want to get a test SSL certificate setup for testing purposes check out my good friend Rob Bagby’s excellent post on the subject.

Creating a Silverlight DataContext Proxy to Simplify Data Binding in Nested Controls

Data binding is one of my favorite features and something that I use a lot while building Silverlight applications.  Silverlight makes it really easy to bind data to different controls and move data from controls back into the original bound object without having to write any C# or VB code in many cases.  Here’s an example of binding a ComboBox control to an object that defines a property named Branches:

<ComboBox
    ItemsSource="{Binding Branches}"
    DisplayMemberPath="Title"/>


This code binds the ItemsSource property to the DataContext object’s Branches property and displays the Branch object’s Title property in the ComboBox.  The DataContext could be assigned directly to the ComboBox through code or could be assigned to a parent object.  If it’s defined on a parent then all children have access to the object. 

This works great as long as the ComboBox has access to the Branches property as shown in Figure 1 below (note that the Page shown in the figure is a Silverlight Page class or User Control not a web page).  However, figure 2 demonstrates a problem that can occur as the ComboBox control’s DataContext is changed to something other than the ViewModel object that defines the Branches property.  In this example a DataGrid binds to the Jobs property of the ViewModel and each row’s DataContext is a Job type.  The Job type doesn’t have a Branches property (the ViewModel object does obviously) so the ComboBox no longer has access to it for data binding.  Or does it?

Figure 1 – All Systems go for binding

Figure 2 – Houston, we have a problem

image image

 

Using a Static Resource When Binding Nested Controls


While the ComboBox can’t bind to the Branches property using the standard {Binding Branches} syntax when it’s nested in something like a DataGrid (or ListBox or another items control) it can still get to the ViewModel object’s Branches property with a few minor changes.  The first way that this little dilemma can be solved is to write code that assigns the ViewModel object’s Branches collection to each ComboBox in the LoadingRow event of the DataGrid.  This works but who wants to write code when you don’t have to?  The second way is to create a mini ViewModel class that each row binds to that references the Branches collection.  That’s also an option, but there’s a “codeless” way to do it as well that’s quite easy.  If the ViewModel object is defined in the Resources section of the Page or UserControl you can get to it using its key name directly in XAML.  Here’s an example of defining a the ViewModel object declaratively in XAML:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:JobPlan.ViewModel;assembly=JobPlan.ViewModel"
    x:Class="JobPlan.View.UserControls.JobEdit">
    <UserControl.Resources>
        <vm:ViewModel x:Key="ViewModel" />
    </UserControl.Resources>

    ...

</UserControl>


A ComboBox control within a DataGrid row (or nested in another type of control) can get to the ViewModel object’s Branches property using the following binding syntax:

<ComboBox
    ItemsSource="{Binding Source={StaticResource ViewModel},Path=Branches}"
    DisplayMemberPath="Title"/>


This XAML code tells the ComboBox control to access a statically defined resource with a key of “ViewModel” and then find a property of that resource object named Branches.  Pretty cool because you don’t have to write any C# or VB code at all by using this solution which is great if you’re dealing with a lot of nested ComboBox controls.  For developers that don’t like defining their ViewModel objects in XAML you can always use an intermediary ViewModel lookup object when things need to be as loosely coupled as possible.

Now that you see how nested objects can get to properties defined at higher levels I can cover the main point of this post.  Everything mentioned to this point works great out of the box especially if you want to avoid writing code as much as possible.  However, there’s one final problem where the StaticResource binding trick won’t work.  Take a look at the figure below to get an idea of the problem:

image


If the DataGrid and nested ComboBox controls are moved into a User Control you can’t use the StaticResource keyword to get to the ViewModel object.  Why?  Because the ViewModel object is defined in the Resources of the parent not in the actual User Control itself.  You could of course write code to get to it and then bind the data (writing code is always an option but can quickly get out of control in larger applications with a lot of controls), but what if you want to bind everything declaratively in XAML?  I don’t know of a built-in way to do that (and I’ve asked many people and have yet to hear an answer that didn’t involve mini ViewModels for each row or writing code) so I ended up creating a fairly simple solution to address the problem. 

The DataContextProxy Class

When I first tried to solve this problem I figured I could define the ViewModel again up in the Resources of the nested User Control.  Try this and you’ll quickly realize that it doesn’t work because it’ll cause a new ViewModel object to be created and two will now be in memory (one for the parent and one for the child User Control).  I needed a way to get to the DataContext from the parent but couldn’t do it using Resources it seemed…without writing code anyway (on a side note, I’m not opposed to writing code at all but the application I’m working on encounters the problem defined here frequently and the code started to get ridiculous).  I started thinking about how the ScriptManagerProxy class works in ASP.NET AJAX and played around with something I now call the “DataContextProxy”.  I needed a way to get to the parent’s DataContext and came up with the following class that does just that:

 

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace JobPlan.Controls
{
    public class DataContextProxy : FrameworkElement
    {
        public DataContextProxy()
        {
            this.Loaded += new RoutedEventHandler(DataContextProxy_Loaded);
        }

        void DataContextProxy_Loaded(object sender, RoutedEventArgs e)
        {
            Binding binding = new Binding();
            if (!String.IsNullOrEmpty(BindingPropertyName))
            {
                binding.Path = new PropertyPath(BindingPropertyName);
            }
            binding.Source = this.DataContext;
            binding.Mode = BindingMode;
            this.SetBinding(DataContextProxy.DataSourceProperty, binding);
        }

        public Object DataSource
        {
            get { return (Object)GetValue(DataSourceProperty); }
            set { SetValue(DataSourceProperty, value); }
        }

        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.Register("DataSource", typeof(Object), typeof(DataContextProxy), null);

        public string BindingPropertyName { get; set; }

        public BindingMode BindingMode { get; set; }

    }
}


The DataContextProxy class grabs the parent DataContext that flows down to the child User Control and binds it to a dependency property named DataSourceProperty.  The DataContextProxy object can be defined in the User Control’s Resource section as shown next:

<UserControl.Resources>
    <controls:DataContextProxy x:Key="DataContextProxy" />
</UserControl.Resources>


This allows the ViewModel defined in the parent to be accessed using XAML in the child User Control.  For example, a ComboBox control nested in a DataGrid can easily get to the Branches property using the following binding syntax:

 

<ComboBox
    DisplayMemberPath="Title"
    ItemsSource="{Binding Source={StaticResource DataContextProxy},Path=DataSource.Branches}" />


The binding syntax tells the ComboBox to bind to the statically defined DataContextProxy object’s DataSource property.  This allows the control to get to the original ViewModel object originally defined in the parent’s Resources section.  The syntax then says to bind to the Branches property of the ViewModel by using the Path property.

Wrapping it Up

Silverlight has a lot of nice data binding features but there will be times when you’ll run into a few road blocks as you’re developing applications.  In this post you’ve seen different techniques that can be used when binding nested controls to data objects and seen how the DataContextProxy object can be used.  Hopefully this will help some of you out down the road when you’re working with a lot of nested controls.

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com.

Building Line of Business Applications with Silverlight 3 – Pros and Cons

imageI’ve been hearing a lot of people talk about how Silverlight 3 can or can’t do various things lately throughout the blogosphere and Twitter.  The sad part is that some of the people giving their two cents about what Silverlight can’t do haven’t built a “real world” application so I’m not sure how their opinion carries any weight (I know because I’ve asked a few of them). Their list of cons are typically based on what they heard on Twitter or various rumors floating around.  As with any technology there are pros and cons and Silverlight is no exception.  The goal of this post is to talk through some of the pros and cons I’ve personally encountered while building a “real world”, enterprise-scale timesheet and job management application for a large electrical contracting company.  I’ll point out what has worked really well and what hasn’t so that people looking to move applications to Silverlight 3 can get an honest assessment on what can be done and what can’t be done.

The application my company is building has a lot of different screens (30+), integrates with the backend database using WCF, uses reporting services for reports and leverages many of the key features Silverlight 3 has to offer.  The existing application used by the client was written using Access Forms and is being ported to Silverlight 3 along with a bunch of new functionality.

Let’s start by going through what I personally feel are the pros and cons that Silverlight brings to the table for Line of Business (LOB) applications.

Silverlight 3 Pros

Here are some of the pros I’ve found as I’ve worked through the application:

  1. Excellent data binding support – my favorite feature.  This changes how you look at building applications and allows you to write data-centric code instead of control-centric code as with normal Web applications.  There’s a lot I could cover here but I wrote up a post awhile back that gives additional details about what I like.  Read it here.
  2. Server code and client code can written in the same language.  Business and validation rules can be shared between the client and server code base which definitely makes applications more maintainable into the future.
  3. A rich set of controls – I really like the controls available with the Silverlight SDK as well as those in the Silverlight toolkit.  There are a few (mentioned below) that can test your patience when you’re building a more involved application and not a simple demo.
  4. Support for just about any type of animation or effect you want.  Don’t need that in a LOB app?  I beg to differ.  You can get quite creative with how data is displayed with Silverlight and not be limited to simple slide, sizing or opacity animations.  I’ll show an example of what I call the “card flow” interface later in this post and show how it allows managers to get to timecards faster and easier than before.
  5. Excellent designer support through Expression Blend 3 – Visual Studio 2008 is great for coding but doesn’t provide any design-time features for Silverlight 3.  Not a big deal….you can use Expression Blend 3 which provides a great interface for designing your applications.  The new SketchFlow application can even be used to prototype applications upfront and get customer feedback more quickly and easily than in the past.
  6. Easy to integrate distributed data using WCF, ASMX, REST, ADO.NET Data Services, .NET RIA Services, etc.  The application that I’m working on leverages WCF as well as some dynamic code on the client-side to make calls to the service.  It works great and FaultExceptions can even be handled now with Silverlight 3.
  7. Desktop-style application with a web deployment model – Get the responsiveness of a desktop application that can be deployed right through the browser and even run on Macs.
  8. Support for styling of controls.  Silverlight 3 now allows styles to be changed on the fly and styles to be based on other styles.  If you don’t like how a control currently looks you can completely change it by using styles and control templates. 
  9. Out of browser support – This was a key reason why my client choose Silverlight 3.  They have a lot of remote workers that don’t always have access to the Internet and needed to be able to enter timesheets even when disconnected and then sync them later once a given employee has connectivity.
  10. Support for behaviorsBehaviors are very, very useful in Silverlight applications.  I needed to add mouse wheel scroll capabilities to a ScrollViewer control to simplify scrolling in a screen and did it within minutes by using a behavior (thanks to Andrea Boschin who created the behavior).
  11. Manipulate pixels using WriteableBitmap.  This can be used to create some very cool effects (some which may not be applicable to LOB applications…but they’re still cool).  I’m using it mainly to fill the printing hole mentioned below.
  12. Support for storing local data through isolated storage – By using isolated storage you can cache data, store data when no network connectivity is available plus more.
  13. Support for navigation – Silverlight 3 has a new navigation application template in Visual Studio that makes creating an application with multiple pages quite easy.  Each “page” can be linked to directly through deep linking and has built-in support for history.  If the client hits the back or forward button in the browser they’re taken to the appropriate Silverlight application page.  The navigation framework allows code to be placed into separate pages (or user controls) and then loaded as a particular link or menu item is clicked.  It’s a great feature that can really reduce the amount of code you have to write especially compared to Silverlight 2.

Silverlight 3 Cons

So everything’s all peachy right? Both the client and I are very happy with how things are going with the application but there have been some challenges along the way.  At the beginning of this post I said I’d mention the cons as well and I’m going to be brutally honest here with some of the areas where Silverlight 3 is missing the mark when it comes to Line of Business applications.

  1. No printing support.  Microsoft is working hard on this for future versions of Silverlight but if you can’t wait until then it’s definitely something to be aware of.  We knew about this going into the project so it was supposed to be a non issue since we could pop-up HTML overlays or open new browser windows that could be printed.  But, for one particular screen the lack of printing support is proving to be a challenge since it turns out the end user always prints the screen as they’re doing payroll work and the screen is quite complex.  I’ve come up with a work around using Silverlight 3’s WriteableBitmap but am currently sending bytes up to the server, converting them into a JPEG and then displaying the image in the browser.  Definitely a hack solution.  We’re now looking at generating dynamic Excel files on the fly at the client with a snapshot image of the Silverlight data since Excel will print the image properly and the browser doesn’t (still researching this option). If that doesn’t work we’ll just use reporting services to generate the same screen…not my preference though.
  2. Binding data to controls such as a ComboBox that is nested in other controls is harder than it should be.  I use a lot of ComboBox controls that are nested in DataGrid or ListBox rows in the application.  While I have it working fine now (after beating my head against the monitor a few times), the ComboBox control itself really needs a SelectedValue and ValueMember property for some situations and a way to more easily bind its ItemsSource to collections that may be defined outside of the current DataContext. All of this can be done via code but if you want to handle the majority of it declaratively in XAML it can be challenging in some cases especially once you start breaking parts of a page into user controls.  I ended up enhancing some code Rocky Lhotka blogged about and created my own ComboBox control that simplifies things a lot.
  3. Lack of built-in support for commanding.  What’s “commanding”?  In a nutshell it’s the ability to call a method within an object directly from XAML as an event fires instead of going through a code-behind file.  For example, when a button is clicked the click event can call directly into a ViewModel object that acts on the event.  By using commanding you can make your applications more testable. Frameworks such as Prism (and many others that have popped up) support simple button commanding and provide a code framework that can be used to build other types of commands.  The application I’m working on handles just about every event in the book (click, mouseenter, mouseleave, rowloaded, lostfocus, gotfocus, plus others) though and writing custom code just to handle events got old (so we simplified things and handle the event in the code-behind which notifies the ViewModel via events).  If you want to handle events directly in the code-behind file this is a non-issue for you, but if you want to handle them in another class it can be more challenging than it should be.
  4. Learning curve – There is certainly a learning curve associated with building Silverlight applications especially if you’re coming from building standard Web applications.  However, I think that’s the case with any technology.  I had already built several demo applications with Silverlight, co-authored a book and several articles on it and still ran into a few challenges with architecture choices along the way (we’re following the MVVM pattern).  I think it boils down to experience though so I list this one simply so that people know they will spend some time learning.  If you’re one of those people who doesn’t like to learn new things then Silverlight probably isn’t for you.  If you enjoy learning new things then I think you’ll love Silverlight once you get the hang of it.
  5. No built-in support for displaying Reporting Services reports within Silverlight – This isn’t a huge issue in my opinion since a report can be brought up in a separate browser window or displayed using an HTML overlay.  However, if you need to display the report directly in Silverlight there isn’t any built-in way to do that in Silverlight 3.  3rd party vendors to the rescue though.  Perpetuum Software now has a product that can integrate reports directly into Silverlight.
  6. The client has to have the Silverlight plugin installed.  I personally don’t view this as much of a con for internal enterprise LOB applications since it’s fairly easy for a PC manager to push out Silverlight to client PCs in many environments.  If the application will be run externally then installation of the plugin on each client has to be considered though.
  7. Sharing service types between proxy objects needs to be enhanced – When the project was initially started I wanted to use ADO.NET Data Services for some things and WCF for others.  The problem is that if both types of services reference the same type (such as Customer) then both generated proxy objects will contain a copy of that type which ultimately bloats the XAP size and leads to having to reference types by namespace down in the code versus a using statement at the top.  Although proxies can share code libraries from other projects (that's an option in the proxy generation wizard), my Model entities use .NET language features not available in Silverlight class libraries so type sharing won't work there.  It's something to keep in mind as you decide how you'll get data into your application.

There are definitely more pros than I’ve listed and probably a few more cons although I honestly can’t think of many more that I’ve had to deal with.  The bottom line is that all of the pieces are there (aside from printing) to build powerful Line of Business applications that are built using existing .NET languages.  You can make the applications look however you’d like and not have to worry if they’ll look good across different browsers.  Here’s a picture of a payroll screen in the early stages of development:

Makeover

Here’s what the screen looks like after applying a few styles to the controls and adding support for things like inline editing of data:

image

Some of the more “fun” features in Silverlight 3 can also be put to good use in Line of Business applications.  I needed to create a way for warehouse managers to easily manage multiple time cards for employees.  I ended up going with what I call a “card flow” interface (similar to cover flow in iTunes) to display the time cards.  The end user can use the mouse wheel to quickly navigate through different cards.  The selected card will slide to the middle with a cool animation and the others are angled using perspective 3D.  Here’s what the “card flow” interface looks like (I need to give credit to Jose Fajardo for blogging about the concept):

image

 

To Wrap It Up

So is Silverlight 3 ready for prime time, enterprise level Line of Business applications?  Having worked with the framework nearly every day for the past 3 months in a “real world” scenario my short answer is a big “YES”!  I don’t say this because I’ve been drinking the Kool-Aid though.  Anyone who knows me understands that I use what I feel works best for a given application (unless the client wants something specific of course).  I truly enjoy working with the framework and think it can do a lot of powerful things.

Every company is unique though so the answer really depends on what features your application needs.  Our previous client’s application was built using ASP.NET MVC and jQuery and it did everything they wanted it to do (I really like ASP.NET MVC and jQuery by the way).  However, Silverlight provides a more consistent way to develop enterprise applications that doesn’t require learning JavaScript, additional libraries like jQuery, CSS, HTML and other Web technologies.  With Silverlight you can write code using your favorite .NET language on both the client and server, debug applications like any normal .NET application, bind data in flexible ways, retrieve data from remote services, animate objects as needed, round corners and work with gradients without ever creating a .gif, .jpg or .png and have a ton of controls right at your finger tips.  I’m a big fan.

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com.

So What’s a Silverlight Value Converter Anyway?

Silverlight has an excellent data binding engine that allows data to be bound through XAML or programmatically with code.  My number one reason for using Silverlight on client projects is the data binding support.  Once you get into it and understand how it works it can save a lot of time when building applications.

When you’re binding data to controls there will be times when the data needs to be modified or tweaked some on the way into a control or as the data leaves a control and goes back to the source property (during a TwoWay binding for example).  Sure, you can always write code to change a given value, but in many cases it’s much easier to write a simple value converter instead that can be re-used.  In this post I’ll walk through creating a value converter and then show the code for a few of the value converters I find myself using fairly frequently.

Creating a Value Converter

Let’s look at a simple example of creating a value converter to get started.  Many applications work with DateTime objects but don’t want the time displayed or want the date formatted a specific way.  If you bind a DateTime property to something like a TextBlock in Silverlight you’ll get the standard output based upon the current culture:

clip_image002[11]

In the case of a birthday you want to show the date but don’t need the time of course.  You’d want something like the following:

clip_image002[13]

Although a separate property could be created in the source object being bound that handles formatting the date, a value converter can be created and re-used over and over anytime a specific date format needs to be created.  To create a value converter you’ll need to add a Silverlight class into your project and implement an interface named IValueConverter (located in the System.Windows.Data namespace).  This interface defines two members including Convert and ConvertBack. Convert is used to modify data as its bound from the source object to the control. ConvertBack works the other way. As a user changes data in a control such as a TextBox the data can be "converted back" to the original data type in the source object by using ConvertBack.

Both Convert and ConvertBack accept the same parameters including the data being bound, the type of the data being bound, any parameter data passed in that can be used in the data conversion process as well as the target culture that the entire process is running under (English, Spanish, French, etc.). Here’s what the method signatures look like:

object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);

Once IValueConverter is added to your class you can right-click it in Visual Studio and select Implement Interface from the menu to automatically fill in the Convert and ConvertBack methods. If you're using Visual Basic you can simply hit enter after the interface name to accomplish the same thing.  Here’s an example of a date value converter that allows dates to be formatted:

using System;
using System.Windows;
using System.Windows.Data;
using System.Globalization;

namespace View.Converters
{
   public class DateConverter : IValueConverter
    {

        #region IValueConverter Members

        //Called when binding from an object property to a control property
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || (DateTime)value == DateTime.MinValue) return null;
            DateTime dt = (DateTime)value;
            return dt.ToString((string)parameter, culture);
        }

        //Called with two-way data binding as value is pulled out of control and put back into the property
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = (string)value;
            DateTime outDate;
            if (DateTime.TryParse(val, culture, DateTimeStyles.None, out outDate))
            {
                return outDate;
            }
            return DependencyProperty.UnsetValue;

        }

        #endregion
    }
}

To use a value converter you’ll need to first reference the class’s namespace (and assembly if the class is in a separate project).  This can be done in the XAML file where the value converter will be used, in App.xaml or in a merged resource dictionary file.  An example of defining a namespace in a resource dictionary file named Styles.xaml is shown next:

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:converters="clr-namespace:View.Converters"
>



</ResourceDictionary> 

Once the namespace is defined you need to define the converter using XAML and give it a key that can be used to reference the value converter (similar to an ID in ASP.NET):

<converters:DateConverter x:Key="DateConverter" />

Now that the converter is defined you can use it in any data binding that handles a DateTime object using the Binding object’s Converter and ConverterParameter properties.  Looking at the code below you can see that the converter is referenced using the StaticResource keyword (since it’s defined as a resource within your Silverlight project) which locates the appropriate key for the converter.

<TextBox x:Name="txtBirthday"
         Text="{Binding Birthday, Mode=TwoWay, Converter={StaticResource DateConverter},ConverterParameter=d}"
         FontFamily="Arial"
         Width="200"
         Height="20"
         Margin="5"  />

This automatically routes all in and out data binding operations (since it’s a TwoWay binding) through the value converter.  If data is being bound to a control such as a TextBox the parameter passed (“d” in this example) is used to format the DateTime object data.  If data is updated in the control it’ll automatically be converted from a string back into a DateTime object.

Value Converter Examples

I have quite a few value converters that I use from time to time in client applications and have listed some of them below.  If you have a favorite one you’re willing to share with others please add a comment to this post with your name, a description of the value converter as well as the code and I’ll update the blog (and give you credit of course) so that a nice library of value converters built-up over time. Update: Shawn Wildermuth let me know that the Silverlight Contrib project has some similar value converters as well as others so check that out as well if you get a chance.

BoolToVisibilityConverter

Handles converting boolean values into Visibility enumeration values.  This is useful when controls need to be shown and hidden based upon the value of a boolean property.  The Inverse parameter value can be passed when you want to hide a control when the property being bound is true or show the control when the value is false.

using System;
using System.Windows;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class BoolToVisibilityConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter == null)
            {
                return ((bool)value == true) ? Visibility.Visible : Visibility.Collapsed;
            }
            else if (parameter.ToString() == "Inverse")
            {
                return ((bool)value == true) ? Visibility.Collapsed : Visibility.Visible;
            }
            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}


DecimalFormatterConverter
 

Converts decimal values into different formats.

using System;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class DecimalFormatterConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string format = (parameter == null) ? "#.##" : parameter.ToString();
            return (value == null) ? String.Empty : decimal.Parse(value.ToString()).ToString(format);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                if (value != null && value.ToString() != String.Empty)
                {
                    return decimal.Parse(value.ToString());
                }
            }
            catch { }
            return null;
        }

        #endregion
    }
}

ListCountVisibilityConverter

Handles showing and hiding controls such as ListBox based upon the number of items in the collection the control is bound to.  For example if there is only one item in a collection you may not want to show a ListBox control due to the data being shown with other controls in the UI.  You could pass a value of 1 for the ConverterParameter and the ListBox would automatically be hidden.

using System;
using System.Windows;
using System.Windows.Data;
using System.Collections;

namespace JobPlan.View.Converters
{
    public class ListCountVisibilityConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                IList list = value as IList;
                if (list != null)
                {
                    int minCount = int.Parse(parameter.ToString());
                    return (list.Count > minCount) ? Visibility.Visible : Visibility.Collapsed;
                }

            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

NullToVisibilityConverter

Handles showing and hiding a control based upon a value being null or not.

using System;
using System.Windows;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class NullToVisibilityConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter == null) //Not invert parameter passed
            {
                return (value == null) ? Visibility.Collapsed : Visibility.Visible;
            }
            else if (parameter.ToString() == "Inverse")
            {
                return (value == null) ? Visibility.Visible : Visibility.Collapsed;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

StringTruncateConverter

Trims a string down to a specific length for display in the user interface.

using System;
using System.Windows.Data;

namespace JobPlan.View.Converters
{
    public class StringTruncateConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int maxLength;
            if (int.TryParse(parameter.ToString(), out maxLength))
            {
                string val = (value == null) ? null : value.ToString();
                if (val != null && val.Length > maxLength)
                {
                    return val.Substring(0, maxLength) + "..";
                }
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

Getting a Random Number

If you need to generate a random number within your iPhone application, you have to push aside Objective-C, as there is not a class with a method for generating random numbers (as in Java). The alternative is to use C, among the functions available are: rand(), srand(), random(), srandom() and arc4random().

arc4random() tends to be preferred as it does not require seeding, the function automatically initializes itself.

// Get random value between 0 and 99
int x = arc4random() % 100;
 
// Get random number between 500 and 1000
int y =  (arc4random() % 501) + 500);

Encrypting Data in .NET Applications

I’ve had several people ask me lately about encrypting data in .NET.  I’m not sure why the question has come up a lot recently, but it’s definitely something good to know if you have any sensitive data that needs to be stored.  .NET provides two main encryption roads that you can travel down including symmetric encryption and asymmetric encryption.  Symmetric encryption relies upon a private key to encrypt and decrypt while asymmetric encryption relies upon a public key to encrypt and a private key to decrypt.  Symmetric encryption provides the best performance while asymmetric encryption provides the best security in situations where keys need to be exchanged between different parties.  If you need to encrypt and decrypt data directly within an application symmetric encryption works fine as long as other prying eyes can’t get their hands on the private key (or your source code). 

I have a fairly straightforward encryption/decryption class named Encryptor that I use when I need to perform symmetric encryption in my web applications.  The class relies upon a symmetric algorithm called Rijndael that can be used to encrypt and decrypt data. 

While I’m not going to provide a detailed discussion of what the class does I’m happy to post it here for anyone who needs that type of functionality.  Keep in mind that you’ll need to update the password and salt values to whatever you need to use in your applications and should consider dynamically grabbing the password from a secured data store as opposed to hard-coding it in the source code (especially if you’ll be shipping the assembly…people can disassemble it using tools like Reflector).  The salt acts as a type of junk data that is used in constructing the password and can also be used to pad encrypted data with bogus bytes so that hackers don’t know which part of the data is valid and which part is junk.

using System;
using System.IO;
using System.Security.Cryptography;

namespace YourApp.Model.Helpers {

    internal class Encryptor
    {
        internal static string Decrypt(string cipherText)
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
            byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return System.Text.Encoding.Unicode.GetString(decryptedData);
        } 

        private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) {
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = null;
            try {
                Rijndael alg = Rijndael.Create();
                alg.Key = Key;
                alg.IV = IV;
                cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(cipherData, 0, cipherData.Length);
                cs.FlushFinalBlock();
                return ms.ToArray();
            }
            catch {
                return null;
            }
            finally {
                cs.Close();
            }
        }

        public static string Encrypt(string clearText)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return Convert.ToBase64String(encryptedData);
        }

        private static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = null;
            try
            {
                Rijndael alg = Rijndael.Create();
                alg.Key = Key;
                alg.IV = IV;
                cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(clearData, 0, clearData.Length);
                cs.FlushFinalBlock();
                return ms.ToArray();
            }
            catch
            {
                return null;
            }
            finally
            {
                cs.Close();
            }
        }

        static string _Pwd = "Your_Password_Goes_Here"; //Be careful storing this in code unless it’s secured and not distributed
        static byte[] _Salt = new byte[] {0x45, 0xF1, 0x61, 0x6e, 0x20, 0x00,  0x65, 0x64, 0x76, 0x65, 0x64, 0x03, 0x76};
    }
}

To use the class to encrypt data (and get back a Base64 encoded string) the following code can be written:

string creditCardNumber = Encryptor.Encrypt(cust.CreditCardNumber);

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

WP Like Button Plugin by Free WordPress Templates