Saturday, September 14, 2013

The Bridge Pattern in Action

The Bridge pattern is a structural pattern as defined by GOF (Gang-Of-Four)- to "decouple an abstraction from its implementation so that the two can vary independently" (GOF). To grasp the idea, I am going to spin up some C# code to demonstrate the concept and see the advantages that it brings along. For this we're gonna be writing some software for rovers - maybe 200 or 300 rovers ready to go :). Ok, for this demo I am gonna only make 2 rovers (MarsRover, and MoonRover). But, same apply to the rest of the different rovers. Here is the initial requirement: I need to be able to dispatch all the rovers and on the move method they should send out a message, collect some data and import it to sql database (in our case we're just using a string to show the data store type for simplicity). First, let's see how we can do this without the bridge pattern. Let's examine the below code and see what is wrong with it.
We can see that we have a common Move method and the main concern is that we are specifying the data store type inside each rover. Let's assume we did this for 300 rovers and eventually we get a new requirement to try out the Oracle database instead. Now, we can see the maintenance nightmare because we would have to change all 300 rovers to use the Oracle data store. How about yet another requirement saying we just need to do this using the File System - this means doing it all over again and changing all 300 rovers. This is where the Bridge Pattern can help solve this issue. Let's start by creating an abstract class and call it Rover:

Next we'll create the IDataCollector interface that has a single method called ImportData.

For simplicity I am including all classes in the same file to easily view on here. The below code shows the newly remodeled rovers:

I made them all override the Move method as well as abstracting the data store type through the use of IDataCollector interface. For our initial requirement we need a SQL data store, so let's create a class for that with a concrete implementation for importing data (we are just returning a string that says the type for simplicity). I am gonna also include classes for 2 other data store types (OracleDataCollector and FileSystemDataCollector):

Finally, let's take the code for s spin:

This will give us the following output:



If the requirements change, we do not have to change the rover code. For example if we just need to import data to the file system we can just replace the SQLDataCollector with the FileSystemDataCollector. Note that in real world scenario this can be done in configuration instead of instantiating a new collector inline.
In summary, let's take a look at a higher level picture of the Bridge Pattern and see where it all fit.



The abstrcation that we have created is the Rover and we have also refined that abstraction by creating MarsRover, and MoonRover. Our Implementor interface is IDataCollector and we have supplied multiple concrete implementations for that interface such as the SQLDataCollector,OracleDataCollection and so forth. Below is the UML Diagram for the rover scenario:



Cheers.

Sunday, September 8, 2013

WCF Without a Physical SVC File.

This is a cool new feature that was introduced in WCF 4.0 and I have been using it since. Basically there is no need for physical svc files and the configuration is pretty simple. Below is the configuration I am using for this simple test case: To test this out with a simple wcf service, fire up Visual Studio ( I am using Visual Studio 2013 preview but you can use 2012) and let's create a new WCF Service Application and name it WCFTestService. For best practices you would want to create a WCF Service Library to create the actual service interfaces and classes but for simplicity we are just gonna create a simple service within the same project.

After we create the project we would want to delete the default Service1.svc and IService1.cs files. Let's create a new interface file and name it ITestService: Now, let's create the test service that is going to implement that interface: We are just using a simple method that returns the id back to us. We are done with the test service, let's tweak the default configuration. Open the web config file and paste the following: After we get this hosted in IIS, we are ready to test the service. I am going to be using wcfTestClient which you can get to it thru the command line by typing wcftestclient as depicted below:

The address I specified in IIS is http://localhost:9090/SvcLessService/TestService.svc but you can specify your own address/TestService.svc. So, without the svc file I am able to download and query the wcf service method and below is the wcfTestClient result:

Sunday, May 12, 2013

Select Most Frequent Value Then Filter by Lower Value if Top Frequency Is Not Unique Using LINQ

In this post I need to be able to parse and query some data that is saved in a flat file. First, let's create this txt file and name it data.txt. Copy and paste the below gibberish to data.txt and create another txt file for the output (result.txt).
20,3,2,2,20,1,4,5,5,1
22,800,600,500,22,0,400,900,0,300,700,300,100,200,400,18
19,200,700,400,700,500,500,900,800,800,400,300,700,22,19
500,900,400,0,500,100,900,0,0,600,600,200,700,900,0,99

So, I would like to operate on each line to get the number that occurs the most, also if some numbers are equally occurring then just take the smallest of them. Ex: if I have 1,2,3,3,1 then the result should be 1 because in this case 3 and 1 share the same frequency position but we just want a single value based on a condition (the lower value) Let's take a look at the code. I am using a custom extension method on the IEnumerable but you can do the same using a foreach loop.
 static void Main(string[] args)
 {
    var lines = File.ReadLines("data.txt");    
    var result = new List();
    var q = lines.Select(x => x)
                 .Select(x => x.Split(',')
                 .GroupBy(i => i)
                 .Select(g => new { g.Key, Count = g.Count()}))
                 .ForEach( v =>
                 {
                    var frequency = v.Max(h => h.Count);
                    result.Add(v.Where(n => n.Count == frequency).OrderBy(i => i.Key).First().Key);
                 });
            File.WriteAllText("result.txt", string.Join("\r\n", result));
 }
The final output is:
1
0
700
0

Sunday, February 13, 2011

Entity Framework 4.0 Repository Factory Pattern

In this post I am going to show you how to write some clean code using a repository pattern and entity framework for data access. I am also using the UnitOfWork pattern and Specification pattern. One thing to note is that EF 4.0 provides us with an Out of the box UnitOfWork called ObjectContext (in my case I am using another level of abstraction on top of that). First, I need to think in terms of blue prints and how to design a well formed skeletton that is decoupled and that makes room for flexibility and testability. For demo puposes, I am just gonna pick out one scenario..So, i need a bridge class that i call a 'Pipe' which is going to act as a data bridge between the presentation layer and the repositories, and the repositories would then talk to the entity framework. Let's start by looking at how the business facade looks like where the 'Pipe' lives.

   1:  public class PhysicianPipe : IPhysicianPipe
   2:  {
   3:          IRepositoryGarden repositoryGarden;
   4:          public PhysicianPipe(IRepositoryGarden RepositoryGarden)
   5:          {
   6:              repositoryGarden = RepositoryGarden;
   7:          }
   8:   
   9:          public void AddPhysician(Domain.Entities.Physician physician)
  10:          {
  11:              repositoryGarden.PhysicianRepository.Add(physician);
  12:              repositoryGarden.SaveRepositoryChanges();
  13:          }
  14:  }

Basically I handed over the UnitOfWork responsibility to the repository garden where it gets injected in the constructor, that way i can use an IoC container (StructureMap, Unity, Ninject, etc..) and can configure it to inject a real UnitOfWork or a Fake one for testing purposes. We'll look at how the repository garden (this acts as a repository factory) class looks like later. I am also archtecting the application in a way that everything is implemented thru interfaces. I dont want the client code to be aware of how things are implemented but rather just how to use them. A real world example is a car for example, the manufacturer makes the car and to be able to drive it, we just need to know how to interact with its interfaces (streering wheel, brakes,etc..) we dont need to know how they work internally. So, all my client code need to be concerned about is how to use the interfaces i hand over to it. Now, looking at the PhysicianPipe class we can see that we can easily add some method that involve work across multiple repositories, then when we are done we can save the changes - we can have something like this:

   1:  public void DoWork(Domain.Entities.Physician physician)
   2:  {
   3:      repositoryGarden.PhysicianRepository.Add(physician);
   4:      repositoryGarden.ClinicRepository.DoSomework();
   5:      repositoryGarden.SaveRepositoryChanges();
   6:  }

Let's take a look at how I signed the repository garden class:

   1:  public class RepositoryGarden : IRepositoryGarden,IDisposable
   2:  {
   3:      IUnitOfWork _CurrentUoW;
   4:      public RepositoryGarden(IUnitOfWork unitOfWork)
   5:      {
   6:          if (unitOfWork == (IUnitOfWork)null)
   7:              throw new ArgumentNullException("unitOfWork", 
   8:                        "Can Not Be Null");
   9:                  _CurrentUoW = unitOfWork;
  10:      }
  11:      IPhysicianRepository physicianRepository = 
  12:                                        default(IPhysicianRepository);
  13:      IClinicRepository clinicRepository = default(IClinicRepository);
  14:   
  15:      public IPhysicianRepository PhysicianRepository
  16:      {
  17:          get
  18:          {
  19:              if (physicianRepository == null)
  20:              {
  21:                  physicianRepository = new PhysicianRepository(_CurrentUoW);
  22:              }
  23:              return physicianRepository;
  24:          }
  25:      }
  26:   
  27:      public IClinicRepository ClinicRepository
  28:      {
  29:          get
  30:          {
  31:              if (clinicRepository == null)
  32:              {
  33:                  clinicRepository = new ClinicRepository(_CurrentUoW);
  34:              }
  35:              return clinicRepository;
  36:          }
  37:      }
  38:   
  39:      //... More repositories
  40:   
  41:      public void SaveRepositoryChanges()
  42:      {
  43:          _CurrentUoW.Commit();
  44:      }
  45:   
  46:      public void Dispose()
  47:      {
  48:          if (_CurrentUoW != null)
  49:          {
  50:              _CurrentUoW.Dispose();
  51:          }
  52:          GC.SuppressFinalize(this);
  53:      }
  54:  }

And the signiture of IRepositoryGarden :

   1:  public interface IRepositoryGarden
   2:  {
   3:        IPhysicianRepository PhysicianRepository { get; }
   4:        IClinicRepository ClinicRepository { get; }
   5:        // More Repository interfaces.....
   6:        void SaveRepositoryChanges();
   7:  }

In this post I did not go over the details of each repository or the UnitOfWork, my goal was to show how easy we can create a central Repository Factory class that takes care of picking out desired repositories as needed then saving the changes once we're done. In my next post i will show how to use the Specification Pattern as well as using DataAnnotations to validate data in subsequent posts.

Friday, January 14, 2011

Forbidden Namespace Dependencies Wildcard

The architecture modeling project that shipped with Visual Studio 2010 has some nice features, one of which is the Layer Diagram where you can drop assemblies, namespaces, classes, and methods. There is one feature that is not supported yet and it's the ability to specify a wildcard in the Forbidden Namespace Dependencies as well as the Forbidden Namespace properties of a particular layer inside the layer diagram. The idea behind this is that i need to be able to write something like: MyRootNamespace.* and the tool I wrote would list out all namespaces under the root namespace, further i could write something like MyRootNamespace.Level1.* and get same results. So, I wrote some code to do that task for any layer diagram in a modeling project. Below is a screenshot of the properties window. Just click on a layer and hit F4 to get to it.


It's straight forward and uses LINQ to XML. So, let's see how it's done.
First, I created a method that get me some namespaces to work with.

   1:  protected static void GetWorkingNameSpaces(string AssembliesDir)
   2:  {
   3:      Namespaces = new HashSet<string>();
   4:      DirectoryInfo di = new DirectoryInfo(AssembliesDir);
   5:      var workingAssemblies = di.Exists ? 
   6:                                di.EnumerateFiles()
   7:                                  .Where(s=>s.Extension.ToLower() ==".dll" ||
   8:                                 s.Extension.ToLower() == ".exe" ) : null;
   9:      Parallel.ForEach(workingAssemblies, a =>
  10:      {
  11:          Assembly reference = Assembly.ReflectionOnlyLoadFrom(a.FullName);
  12:          try
  13:          {
  14:              HashSet<string> refernceNamespaces = 
  15:                  new HashSet<string>(reference.GetTypes()
  16:                                               .Select(f => f.Namespace)
  17:                                               .Where(n => n != null));
  18:              Namespaces.UnionWith(refernceNamespaces);
  19:          }
  20:          catch (ReflectionTypeLoadException) { }
  21:      });
  22:  }

So, not a whole lot going on, just newing up an instance of a HashSet and doing reflection over a list of assemblies and extracting some namespaces, and storing them in a HashSet collection so that i can work with them later.

Next, I created a method that will process the wildcard token. It takes in a namespace root or sub-n-root and returns nested namespaces.

   1:  protected static HashSet<string> ProcessWildCard(string Token)
   2:  {
   3:      HashSet<string> namespaces = new HashSet<string>();
   4:      int index = default(int);
   5:      string Name = default(string);
   6:      if (Token.Contains("."))
   7:          index = Token.LastIndexOf('.');
   8:      else return namespaces;
   9:      Name = Token.Substring(0, index).Trim();
  10:      foreach (var t in from c in Namespaces 
  11:                          where c.StartsWith(Name) 
  12:                          select c)
  13:      {
  14:          namespaces.Add(t);
  15:      }
  16:      return namespaces;
  17:  }

Now that i got this far, i need to build an update method that takes in an attribute Name and an XElement - since I am going to be updating both the Forbidden Namespace Dependencies and Forbidden Namespaces.

   1:  protected static void UpdateForiddenAttribute(ref string 
   2:                                                forbiddenAttributeName,
   3:                                                XElement t)
   4:  {
   5:      List<string> proccessed = new List<string>();
   6:      string _forbiddenAttributeValue = default(string);
   7:      if (t.Attribute(forbiddenAttributeName) != null)
   8:      {
   9:          _forbiddenAttributeValue = 
  10:                  t.Attribute(forbiddenAttributeName).Value;
  11:          string[] elements = default(string[]);
  12:          if (_forbiddenAttributeValue.Contains(";"))
  13:          {
  14:              elements = _forbiddenAttributeValue.Split(new[] { ";" },
  15:                               StringSplitOptions.RemoveEmptyEntries);
  16:          }
  17:          else
  18:          {
  19:              elements = new[] { _forbiddenAttributeValue };
  20:          }
  21:          foreach (var s in elements)
  22:          {
  23:              if (s.Contains("*") && !(s.Contains(",") || s.Contains("|")))
  24:              {
  25:                  var hash = ProcessWildCard(s);
  26:                  if (hash.Count > 0)
  27:                      foreach (var h in hash)
  28:                      {
  29:                          proccessed.Add(h);
  30:                      }
  31:                  else
  32:                  {
  33:                      proccessed.Add(s);
  34:                  }
  35:              }
  36:              else
  37:              {
  38:                  proccessed.Add(s);
  39:              }
  40:          }
  41:      }
  42:      string formattedAttributeValue = default(string);
  43:      if (proccessed.Count > 1)
  44:      {
  45:          formattedAttributeValue = String.Join(";", proccessed);
  46:      }
  47:      else
  48:      {
  49:          if (proccessed.Count == 1)
  50:              formattedAttributeValue = proccessed[0];
  51:          else
  52:              formattedAttributeValue = null;
  53:      }
  54:      t.SetAttributeValue(forbiddenAttributeName, formattedAttributeValue);
  55:  }

So far so good, all i did is get some attribute value, do some processing on it and update the .layerdiagram file with the newly constructed list of namespaces. So, the next step is the actual method that runs and collects data about the layerdiaram file/s in the modeling project, calls the update method and finally saves each layerdiagram file to complete the process.

   1:  static void RunTool(string layerdiagramDirectoryPath, 
   2:                      string AssembliesDirectory)
   3:  {
   4:      string forbiddenNamespaceDependenciesName = 
   5:                              "forbiddenNamespaceDependencies";
   6:      string forbiddenNamespaceName = "forbiddenNamespace";
   7:      GetWorkingNameSpaces(AssembliesDirectory);
   8:   
   9:      var q= Directory.EnumerateFiles(layerdiagramDirectoryPath, 
  10:                                      "*.layerdiagram", 
  11:                                      SearchOption.AllDirectories)  
  12:          .Select(x => new{
  13:                  s =  XDocument.Load(x),
  14:                  p = x 
  15:              })
  16:          .Where(d => d.s.Root
  17:                      .Elements()
  18:                      .Descendants()
  19:                      .Any(v => v.Attributes(
  20:                       forbiddenNamespaceDependenciesName)
  21:                      .Any())
  22:                  ||d.s.Root
  23:                      .Elements()
  24:                      .Descendants()
  25:                      .Any(v => v.Attributes(forbiddenNamespaceName)
  26:                      .Any())
  27:                  );
  28:      foreach (var x in q)
  29:      {
  30:          bool DocumentHasChanges = default(bool);
  31:          IEnumerable<XElement> xElements = 
  32:                  ( from c in x.s.Root
  33:                              .Elements()
  34:                              .Descendants()
  35:                  where c.Attributes(forbiddenNamespaceDependenciesName)
  36:                         .Any() ||
  37:                          c.Attributes(forbiddenNamespaceName).Any()
  38:                  select c
  39:                  );
  40:          Parallel.ForEach(xElements, t =>
  41:          {
  42:              if (t.Attribute(forbiddenNamespaceDependenciesName) != null)
  43:              {
  44:                  UpdateForiddenAttribute(ref 
  45:                                   forbiddenNamespaceDependenciesName, t);
  46:                  DocumentHasChanges = true;
  47:              }
  48:              if (t.Attribute(forbiddenNamespaceName) != null)
  49:              {
  50:                  UpdateForiddenAttribute(ref forbiddenNamespaceName, t);
  51:                  DocumentHasChanges = true;
  52:              }
  53:          });
  54:          if (DocumentHasChanges)
  55:          x.s.Save(x.p);
  56:      }
  57:  }

And that's all the code needed to now have an out of box wildcard functionality. To get this working just hook it up to the main entry point of your program and pass in 2 arguments (modeling project directory and assemblies directory) and wrap it up with a try catch block. Would look something like this:

   1:  #region Program Entry
   2:      public static void Main(string[] args)
   3:      {
   4:          try
   5:          {
   6:              RunTool(args[0], args[1]);
   7:          }
   8:          catch (Exception g)
   9:          {
  10:              Console.WriteLine("Error :{0} ", g.Message);
  11:          }
  12:      }
  13:  #endregion

So, to use this tool, right click on the modeling project and choose Edit project - add an MSBUILD Exec task and give it the location of batch file under your solution items or where ever you like to keep .bat files related to your solution and that's all. Next time you build the solution and if there are any broken forbidden namespace dependencies, they will show up as build errors.

Sunday, August 8, 2010

Pass Parameters from ASP.NET to Silverlight

It is very straight forward to pass parameters from an asp.net page to a silverlight application. In my case, I had an asp.net application and wanted to integrate silverlight in one of my pages. I needed to pass some values such as ID and user role. Let's look at some code. First, I created a class, in my Silverlight application, to encapsulate my values. The constructor of my class takes in an IDictionary.

public class Dashboard
{
private string _ParishId;
private bool _IsReadOnly;
private bool _IsGSTSOrSuperParish;
internal Dashboard(IDictionary<string, string> parameters)
{
_ParishId = parameters["pid"];
_IsReadOnly = Convert.ToBoolean(parameters["iro"]);
_IsGSTSOrSuperParish = Convert.ToBoolean(parameters["igs"]);
}
public string ParishId
{
get { return _ParishId; }
}
public bool IsReadOnly
{
get { return _IsReadOnly; }
}
public bool IsGSTSOrSuperParish
{
get { return _IsGSTSOrSuperParish; }
}
}

Now, in the App.xaml application start up event i new up an instance of the class i created passing in the initParams of the StartupEventArgs.
Below is the markup needed for this.

private void Application_Startup(object sender, StartupEventArgs e)
{
Dashboard db = new Dashboard(e.InitParams);
this.RootVisual = new MainPage(db.ParishId,db.IsReadOnly,db.IsGSTSOrSuperParish);
}

Now that i have things set up for the mainPage.xaml, all i have to do is get those values on mainPage. And that's it on the silverlight side. I still have to set up how to get the actual values from ASP.NET. Below is the code for the mainPage.xaml.

public partial class MainPage : UserControl
{
private string _id;
private bool _IsReadOnly;
private bool _IsGSTSOrSuperParish;
public MainPage(string id, bool isReadOnly, bool isGSTSOrSuperParish)
{
InitializeComponent();
_id = id;
_IsReadOnly = isReadOnly;
_IsGSTSOrSuperParish = isGSTSOrSuperParish;
Loaded += new RoutedEventHandler(Page_Loaded);
}
...

Finally, I added a parameter (to the asp.net user control where my silverlight reference is) and called it initParam and gave it an ID of 'prm' so I can use it in code behind of this user control. First, let's take a look at the HTML.

<div id="silverlightControlHost">
<object id="tempSil" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="../ClientBin/DB.Silverlight.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50401.0" />
<param name="autoUpgrade" value="true" />
<param name="initParams" runat="server" id="prm" />
<param name="windowless" value="true" />
 
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>

And here is the code behind and is pretty straight forward..just passing in values.

public partial class UserControls_VE_db : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
using (var proxy = new CapitalAreaService.ServiceClient())
{
this.prm.Attributes["value"] = string.Format("pid={0},iro={1},igs={2}", 
proxy.GetParishId(SystemRole.GetParisAbbreviation()),SystemRole.IsReadOnly(),
SystemRole.IsGSTSOrSuperParish());
}
}
}

That's all it take to pass values from ASP.NET to Silverlight as needed.

Saturday, August 7, 2010

Silverlight Form Flip Animation

In my recent project I had a datagrid and needed to have a search option where the user can do a basic search or an advanced search, so I thought about implementing this using a form flip animation. Basic search on one side and advanced search on the other. This saved me space and all i had to do is add a search button above the grid and upon click pop up the search form. Below is a screen shots of what this looks like.



When the user clicks the search icon on the first screen shot, it pops up the basic search form and upon clicking Advanced search the form flips and shows the advanced search form. Now, let's look at some code.

First I am going to add a stack panel for the search icon then right underneath that I am addding a popup control in mainpage.xaml.

<StackPanel Orientation="Horizontal">
<Button Height="23"  
HorizontalAlignment="Left"   
Name="btnLaunchSearch" VerticalAlignment="Top"  
Click="btnLaunchSearch_Click">
<Button.Content>
<Image Source="./images/search.jpg"   ToolTipService.ToolTip="Search" />
</Button.Content>
</Button>
</StackPanel>
<Popup x:Name="SearchFormPopup" VerticalOffset="100" HorizontalOffset="100">
</Popup>
Now, I am going to add a view for the search form. I created a folder called UserControls then added a Search.xaml user control. I put the styles in a separate file - used a resource dictionary.

<UserControl x:Class="DB.Silverlight.UserControls.Search"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="200" d:DesignWidth="500">
<UserControl.Resources>
<ResourceDictionary x:Key="SD">
<ResourceDictionary.MergedDictionaries >
<ResourceDictionary  Source="../Dictionaries/SearchDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary> 
<Storyboard x:Name="StartingPosition">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="FormBack"
Storyboard.TargetProperty="(UIElement.RenderTransform).TransformGroup.Children[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="5000" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Name="AdvancedSearch">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="PanelProjection"
Storyboard.TargetProperty="RotationY">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="0" />
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="90" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="FormFront"
Storyboard.TargetProperty="(UIElement.RenderTransform).TransformGroup.Children[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="0" />
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="0" />
<SplineDoubleKeyFrame KeyTime="00:00:01.01"
Value="5000" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="FormBack"
Storyboard.TargetProperty="(UIElement.RenderTransform).TransformGroup.Children[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="5000" />
<SplineDoubleKeyFrame KeyTime="00:00:00.99"
Value="5000" />
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="0" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="BackPanelProjection"
Storyboard.TargetProperty="RotationY">
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="270" />
<SplineDoubleKeyFrame KeyTime="00:00:02"
Value="360" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Name="BasicSearch">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="FormBack"
Storyboard.TargetProperty="(UIElement.RenderTransform).TransformGroup.Children[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="0" />
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="0" />
<SplineDoubleKeyFrame KeyTime="00:00:01.01"
Value="5000" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="BackPanelProjection"
Storyboard.TargetProperty="RotationY">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="0" />
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="-90" />
</DoubleAnimationUsingKeyFrames>
 
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="PanelProjection"
Storyboard.TargetProperty="RotationY">
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="-270" />
<SplineDoubleKeyFrame KeyTime="00:00:02"
Value="-360" />
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="FormFront"
Storyboard.TargetProperty="(UIElement.RenderTransform).TransformGroup.Children[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:00"
Value="5000" />
<SplineDoubleKeyFrame KeyTime="00:00:00.99"
Value="5000" />
<SplineDoubleKeyFrame KeyTime="00:00:01"
Value="0" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<Canvas>
<StackPanel x:Name="FormFront">
<StackPanel.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform />
<TranslateTransform />
</TransformGroup>
</StackPanel.RenderTransform>
<StackPanel.Projection>
<PlaneProjection x:Name="PanelProjection"
RotationX="0"
RotationY="0"
RotationZ="0" />
</StackPanel.Projection>
<Border Name="mainBorder" Style="{StaticResource ModalDialogBorder}" > 
<Grid x:Name="LayoutRoot" Width="399" Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="70" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.Row="0" >
<TextBlock Margin="20" Text="Note:Search by user's first name, last name, or by business name."></TextBlock>
</StackPanel>
<TextBox TabIndex="0" Name="txtSearch" Grid.Row="1" Height="30" Width="260" Margin="0,5,0,20"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.Row="2" Margin="89,0,89,55">
<Button x:Name="SearchButton" Height="30" Width="100"  Content="Search"/>
<Button x:Name="CancelButton" Height="30" Width="100"  Content="Cancel"/>
</StackPanel>
<Button x:Name="Advanced"
Content="Advanced Search"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Width="Auto"
Background="DarkGreen"
FontFamily="Georgia"
FontSize="10"
Grid.Row="5"
Margin="10,0"
Grid.Column="0" />
</Grid>
</Border>
</StackPanel>
<StackPanel x:Name="FormBack">
<StackPanel.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform />
<TranslateTransform />
</TransformGroup>
</StackPanel.RenderTransform>
<StackPanel.Projection>
<PlaneProjection x:Name="BackPanelProjection"
RotationX="0"
RotationY="0"
RotationZ="0" />
</StackPanel.Projection>
<Border Style="{StaticResource ModalDialogBorder}" >
<Grid x:Name="theForm" Width="399">
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Placard Type"
Grid.Row="0"
Grid.Column="0"
Style="{StaticResource Prompt}" />
<ComboBox  
Name="cbPlacardType"   
Grid.Row="0"
Grid.Column="1" 
Style="{StaticResource EntryDrop}" />
<TextBlock Text="Status"
Grid.Row="1"
Grid.Column="0"
Style="{StaticResource Prompt}" />
<ComboBox  
Name="cbStatus"   
Grid.Row="1"
Grid.Column="1" 
Style="{StaticResource EntryDrop}" />
<TextBlock Text="Date Entered"
Grid.Row="2"
Grid.Column="0"
Style="{StaticResource Prompt}" />
 
 
<TextBlock Text="From" Margin="8,0,231,0"
Grid.Row="2"
Grid.Column="1" Width="30" />  
<TextBox x:Name="txtFrom"
Grid.Row="2"
Grid.Column="1"
Width="80" Margin="37,0,162,0" />
<TextBlock Text="To" Width="30"
Grid.Row="2"
Grid.Column="1" Margin="116,0,123,0" />
<TextBox x:Name="txtTo"
Grid.Row="2"
Grid.Column="1"
Width="80" Margin="150,0,49,0" />
<TextBlock Text="Placard Id"
Grid.Row="3"
Grid.Column="0"
Style="{StaticResource Prompt}" />
<TextBox x:Name="txtPlacardId"
Grid.Row="3"
Grid.Column="1"
Style="{StaticResource Entry}"  />
<TextBlock Text="Business Name"
Grid.Row="4"
Grid.Column="0"
Style="{StaticResource Prompt}" />
<TextBox x:Name="txtBusinessName"
Grid.Row="4"
Grid.Column="1"
Style="{StaticResource Entry}" />
<TextBlock Text="Contact First Name"
Grid.Row="5"
Grid.Column="0"
Style="{StaticResource Prompt}" />
<TextBox x:Name="txtContactFirstName"
Grid.Row="5"
Grid.Column="1"
Style="{StaticResource Entry}" />
<TextBlock Text="Contact Last Name"
Grid.Row="6"
Grid.Column="0"
Style="{StaticResource Prompt}" />
<TextBox x:Name="txtContactLastName"
Grid.Row="6"
Grid.Column="1"
Style="{StaticResource Entry}" />
<Button x:Name="btnAdvancedSearch"
Content=" Search "
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Width="95"
Background="DarkGreen"
FontFamily="Georgia"
FontSize="12"
Grid.Row="7"
Margin="30,0,0,10" />
<Button x:Name="btnAdvancedSearchCancel"
Content=" Cancel "
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Width="95"
Background="DarkGreen"
FontFamily="Georgia"
FontSize="12"
Grid.Row="7"
Margin="10,10"
Grid.Column="1" />
<Button x:Name="Basic"
Content="Switch to Basic Search"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Width="112"
Background="DarkGreen"
FontFamily="Georgia"
FontSize="10"
Grid.Row="8"
Margin="0,0,12,5"
Grid.Column="1" />
</Grid>
</Border>
</StackPanel>
</Canvas>
</UserControl>

Now, in the code behind of the search form I added the mecanics to do the flip animation.

public partial class Search : UserControl
{
public Search()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Search_Loaded);
Advanced.Click += new RoutedEventHandler(Advanced_Click);
Basic.Click += new RoutedEventHandler(Basic_Click);
}
void Search_Loaded(object sender, RoutedEventArgs e)
{
StartingPosition.Begin();
//TODO: Load comboboxes..
}
void Advanced_Click(object sender, RoutedEventArgs e)
{
AdvancedSearch.Begin();
}
void Basic_Click(object sender, RoutedEventArgs e)
{
BasicSearch.Begin();
}
}

All i have left now is the code to handle the search button in mainpage.xaml and it's pretty simple - i just have to new up an instance of the popup control that i created in mainpage and also new up an instance of the search form user control and ofcourse code to handle my data. Since my data code involves WCF and is a bit lengthy I am just gonna leave that up to you to add your own data handling here. Below is the code needed in mainpage.

private void btnLaunchSearch_Click(object sender, RoutedEventArgs e)
{
SearchFormPopup = new Popup();
form = new Search();
form.CancelButton.Click += new RoutedEventHandler(CancelButton_Click);
form.SearchButton.Click += new RoutedEventHandler(SearchButton_Click);
form.btnAdvancedSearchCancel.Click += new RoutedEventHandler(CancelButton_Click);
form.btnAdvancedSearch.Click += new RoutedEventHandler(AdvancedSearchButton_Click);
SearchFormPopup.Child = form;
SearchFormPopup.IsOpen = true;
}
private void AdvancedSearchButton_Click(object sender, RoutedEventArgs e)
{
LoadFilterdDataboardDataAdvancedSearch();
SearchFormPopup.IsOpen = false;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
SearchFormPopup.IsOpen = false;
}
private void SearchButton_Click(object sender, RoutedEventArgs e)
{
LoadFilteredDashBoardDataSearch();
SearchFormPopup.IsOpen = false;
}

And that's it. If you have any comments or better ways to do this, let me know.