Nermin's .Net

My Thoughts on .Net and Software Development - correct spelling is optional

About the author

Author Name is someone.
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Adding Custom Themes Support to your WPF Application

The greatest thing about Windows Presentation Foundation is that when compared to Windows Forms, it finally gives us the freedom of easily designing rich UI, that differs from same old Winforms we have been seeing from Win 95 with slight re-styling. We finally have a true vector based UI, that allows us to manipulate each screen element in thousands of different ways through visual effects, animations, scaling, custom layouts etc.

But with this Great Power comes even larger responsibility. Yes we can do all these things, but we also need to assure that our UI looks consistent: If we find this really cool looking buttons library, we need to assure that the Tree Control that we render next to it is styled appropriately to match it, as well as list box, check boxes scroll bars...

We do not want our new UIs to be a mix of every color in the rainbow that look like water color painting of a kindergartner. We need a professional 21st century UIs. Unfortunately most of us developers are superbly creative when it comes to complex algorithms, while our artistic skills lack far behind. Third party controls that support custom Themes might have been a solution to this problem in Windows Forms world, but do we really have to go there in WPF? Another great thing with WPF it adds native support for custom themes. Basically you define your basic layout, drop your controls on the screen, and then similar to CSS in the web world, you define custom styles for your control in the Resources section of your XAML code. If only we had a nice library of WPF styles that we could use...

 



Well that is where "WPF Themes" Library - Open Source Project hosted on CodePlex comes in.  First it is a library of a dozen custom UI Themes for most of the standard WPF controls, allowing us to customize the look and feel of our WPF UI without touching our screens XAML.  What more the library actually comes with a Theme Manager, that allows us to dynamically load and bind our custom Themes at runtime.

How can we use these Themes?  Obviously first download WPF Themes Library project from http://www.codeplex.com/wpfthemes and include it in your WPF Solution. Then it is a matter of you deciding how do you want to select and load custom Theme at runtime.  For the purpose of this example lets presume that we want to allow our Application user to select any of these Themes at runtime in a form of the Drop Down box that we place at, lets say, top right corner of the application main screen.

So lets define this DropDown:


    
    

Ok, so if we look at the XAML above you will notice that there is a stack panel that encapulates the label and a DropDown. But wait, there is no event handler for the SelectionChanged event! How do we tell this WPF Theme library to load a theme we select from the DropDown? Well, if we take a look at the source code of the ThemeManager class that is in charge of loading Themes for us, you will notice that it defines/registers a Dependency Property called "Theme". What does that mean? It means that we can just add this propery to our root window, and bind it to the drop down selection, and that is it. Each time we change a selection in our Drop down list of available themes, ThemeManager loads that Thema and applieas it to our WPF application. The two lines of XAML that allow us to define our dependency property are listed below:



    ...


Now the last question is: How do we populate the "Available Themes" Drop Down list? We simply bind it to ThemeManager.GetThemes(), like below:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    themes.ItemsSource = ThemeManager.GetThemes();
}

And simply put - that is it, by placing the code above together with WPF.Themes project in your solution you get great set of WPF themes, that you can simply use in your app, but also customize and extend.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 1 people

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

Tags:
Categories: C# | WPF
Posted by ndibek on Monday, November 17, 2008 3:41 AM
Permalink | Comments (2213) | Post RSSRSS comment feed

CSLA.NET VB and C# Visual Studio Class Templates

As a part of upcoming CSLA.NET 3.6 beta 2 release we have added one more feature - Csla.Net Class Templates for VB.NET and C# integrated in Visual Studio 2008.  So for example, when you select "Add New Item" in Visual Studio you get following options: 

Each of the class templates from the dialog above generates a Csla object with the template selected.  So for example, for selected CommandObject template in the dialog above with the selected name CommandObject2 you get the code generated below:

using System;
using System.Collections.Generic;
using System.Text;
using Csla;
namespace ClassLibrary1
{
[Serializable]
public class CommandObject2 : CommandBase
{
#region Authorization Methods
public static bool CanExecuteCommand()
{
// TODO: customize to check user role
//return Csla.ApplicationContext.User.IsInRole("Role");
return true;
}
#endregion
#region Factory Methods
public static bool Execute()
{
if (!CanExecuteCommand())
throw new System.Security.SecurityException("Not authorized to execute command");
CommandObject1 cmd = new CommandObject1();
cmd.BeforeServer();
cmd = DataPortal.Execute(cmd);
cmd.AfterServer();
return cmd.Result;
}
private CommandObject1()
{ 
/* require use of factory methods */ 
}
#endregion
#region Client-side Code
// TODO: add your own fields and properties
bool _result;
public bool Result
{
get { return _result; }
}
private void BeforeServer()
{
// TODO: implement code to run on client
// before server is called
}
private void AfterServer()
{
// TODO: implement code to run on client
// after server is called
}
#endregion
#region Server-side Code
protected override void DataPortal_Execute()
{
// TODO: implement code to run on server
// and set result value(s)_result = true;
}
#endregion
}
}
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 3.3 by 6 people

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

Categories: C# | Csla.Net | Tools
Posted by ndibek on Friday, October 17, 2008 9:02 AM
Permalink | Comments (2048) | Post RSSRSS comment feed

An interesting migration problem from "Linq to Sql" to "Linq to Entities"

As you might have seen  from few of my previous posts I have been working on the MVC demo implementing Csla.  DAL layer of that demo used the Repository pattern, which is essentially just a wrapper around Linq2Sql DataContext:   

 
Then we would have one implementation of IRepository for each Linq to Sql table / DTO object, like for example SqlCustomerRepository.GetAll(), SqlOrdersRepository.GetAll(), etc.
 
All that each of the GetAll() methods would do is return (this is the implementation in SqlCustomerRepository):
 
 
where _db is an instance of the Linq DataContext.  Hiding DataContext away from our BO and abstracting it away from business layer objects makes it easier to test our business objects.  It makes it easy to replace the SqlCustomerRepository, with TestCustomerRepository that might return hard-coded list of Customers instead.
 
Then we use this inside our business object applying necessary filters - all that the method returns is IQueryable<T> so it makes it easy to use result of GetAll() in another Linq query:
  
 
One problem Rocky noticed in this design is that we are returning Linq generated DTOs.  What if our application needs to migrate to Oracle as a back end, for example.  The only option then is Linq to Entities.  But the type generated by Linq to Entities is different than type generated by Linq to Sql.  Although they might have similar signatures they are different objects.
 
One solution would be t create generic Data Transfer Objects that are neither  Linq to Sql neither Linq to Entities and then "map" the either implementations to these "shared" objects that are instead sent as DTOs.  Problem - one would have to hand code all that stuff.  
 
So for now I decided to give up on Linq to Sql in my demo and migrate it to Linq to entities.  Having 2 different database back ends would not matter in Entity Framework as either Sql Server or Oracle tables are mapped into Entities.  But that meant migrating to Linq to Entities.
 
I thought that this will present not much work at all as the queries are rather simple, and both frameworks support the same Linq syntax.  So I regenerated my Entity diagram using EF.  Everything compiled - good!.  
 
But when I ran the application - I got the following error:
 
Only parameterless constructors and initializers are supported by LINQ to Entities.
 
So although it compiled as perfectly valid Linq Query, at runtime it broke due to the fact that Linq to Entities can not evaluate expression if there are constructors with parameters, or initializers that are not an anonymous objects.  Took me a while to wrapmy head around that statement, but that essentially is what EF team states.  You can check it out in greater detail on following two sites:
 
Essentially Linq2Entities was complaining about:
 
select new OrderInfo(order)
 
part.   OrderInfo is the BO that is part of the list I am trying to populate from EF Entity - order, which is passed as a parameter to its constructor.  So essentially I had to modify the Fetch() method to following:
 
 
 
So what changed?  We are selecting the "order", which is the Linq to Entities object, and then we have to iterate through the list of those objects to map one at the time (as can be seen from use of Add() method instead of AddRange() which was used in Linq to Sql version).
 
Yet another "feature" that any of us migrating from Linq to Sql to Linq to Entities should be aware of.
  
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

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

Categories: C# | Linq
Posted by ndibek on Monday, September 15, 2008 7:09 AM
Permalink | Comments (2315) | Post RSSRSS comment feed

RhinoMocks 3.5 AAA Model

Ayende has again proven why he is one of the most respectednames in Alt.Net community.  Besides writinga book on language based DSLs, supporting Boo, and NHibernate, having a fulltime job, and writing one of the most informative blog publications, he hasactually practically re-written RhinoMocks in this new version.  And with that RhinoMocks basically takes backthe title of simplest and most productive dynamic mocking framework out there.

Take a look at an ASP.NET MVC test written with RhinoMocks3.3: 

 

As you can see the test above uses a traditional Record& Replay model (referred to as R&P in the rest of this document), wherein Record block we generally set our expectations, and then the Replay block isused to perform actions on object being tested, allowing our Mock objects to execute and verify expectations.

Now let’s take a look at the same test written withRhinoMocks 3.5:

 



This test uses Arrange, Action and Assert model (AAA).  What you will notice first is that there areby far fewer lines needed to setup mocks.

In the AAA version there is no need to instantiateMockRepository, once you generate your Mock, or in this case Stub object, youcan setup your expectations directly on the mock instance. Lines 21 and 22 inR&P version of the test are replaced by single line of code in AAA version –line 22.

You will also notice that we are using GenerateStub()instead of DynamicMock().  Put simply thereis a difference between Mock and Stub objects and RhinoMocks recognizes thatallowing us to write tests that better state their purpose.  For some of you scratching your heads,easiest way to describe the difference is to say that Mock objects are used todefine expectations i.e: In this scenario I expect method A() to be called withsuch and such parameters.  Mocks recordand verify such expectations.  Stubs, onthe other hand have a different purpose: they do not record or verifyexpectations, but rather allow us to “replace” the behavior, state of the “fake”object in order to utilize a test scenario.

In this case the behavior we want to stub is: “WhenGetCustomers() is called return the testCustomers list.”  You can see that AA version uses a Lambda expressionto define the method being called.  Againthe line 24 in AA version replaces lines 24-30 in R&P version.

And lastly at the end of the AAA version, as we have definedour expectation directly on the mock object itself (which replaced the recordblock), there is no need to define the Playback block either.  It is assumed that it follows the recordedassumptions.  Therefore the Playbacksection of the R&P model is comparable to Action and Assert sections of theAA model.

So as you can see our tests have dropped from 13 down to 7lines of code.  Also due to a lot simplermocking portion of the block tests are now lots easier to read and maintain.  I must add that this is only the portion ofthe new features Ayende is adding to RhinoMocks, and for more details I wouldrefer you to go to RhinoMocks wiki as well as Ayende’s blog.  Personally I would like to congratulate himon making a good Dynamic Mocking tool great.

http://ayende.com/Wiki/Default.aspx?Page=Rhino%20Mocks%203.5&AspxAutoDetectCookieSupport=1#WhatsNewinRhinoMocksDF

 

 

 kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

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

Categories: C# | Mock | TDD | Unit Testing
Posted by ndibek on Friday, August 22, 2008 3:58 AM
Permalink | Comments (3432) | Post RSSRSS comment feed

Fluent Stubs

Refactoring has become a common practice amongst many developers I work with.  Why refactor?

Well, first it takes the pressure of off design phase of project in a sense.  You do not have spend ton of time upfront designing the code and assuring that you thought of every detail before you even write a single line of code.  You simply get a rough design and start coding right away, knowing that as you implement the system, get more familiar with the code, you will notice better patterns and refactor the code towards them.

We all know that, if done right, refactoring leads to simpler smaller code base that is easier to maintain.  Meantime we use Unit Tests to assure that the refactoring we performed did not change the outcome or results that our code produces.  I have been following this practice for a while and it has kept me out of trouble.

However what I realized over time is that the Unit Tests themselves become more complex, with too much duplication, and too hard to read.

Take for example this problem I had recently at the client I am working for.  We inherited a “failed” project (story of my life – I always end up coming in to fix someone else’s mess, but enough about that), a project that  another consulting company has given up on after complicating the matter a bit first.

No, they did not use code refactoring, they did not have unit tests, instead they have used code generation tool to “save time”.  It is just that their code generation templates were not really thought through.  Now we have a complex system, with a lot of bugs to clean and lot of code to refactor.  And yes, in order to refactor we had to start writing unit tests to support it.

Well all of their Business Objects are initialized by making a DB call in their constructor that uses Datasets as the DTOs that transfer that data from the DAL (I know what you are going to say now – but sometimes you have to work with what you have – we have to bring this site online!).

But lets start with an example.  Lets say I had a bussiness object called ShoppingCart and that it contained a list Product sand a list of Options for eaach product.  In the constructor of the ShoppingCart, they would have an instance of a ShoppingCartData object that would have a method callled ExecuteDataSet() which although the name does not state it returns all Products and their options that belong to this shopping cart.  Then the code inside of the dataset woule lop through the tables and populate both object lists, something like:

ShoppingCartData _shoppingCartData = new ShoppingCartData();

public ShoppingCart()

{

     DataSet ds = _shoppingCartData.ExecuteDataSet();

     foreach(DataRowView in ds.Tables[0].Rows){

}

So in order to write tests against these objects I had to mock the DAL call and replace the DataSet that the DB would return with my own.   As you can see ShoppingCartData was not injected, nor did it have an interface so for mocking part I had to bring the big guns – TypeMock. 

Mock data = MockManager.Mock(typeof(ShoppingCartData));

cartData.ExpectAndReturn("ExecuteDataSet",cartDataSetStub); 

So mocking the Db call and taking DB out of eqation was easy.  Even generating the stub data for the tests was not the problem.  You might have read one of my previos blogs where I wrote about this little code generation tool that helped me generate DataTable Stub objects just by runnig the sql :

http://www.nermins.net/post/2007/07/Mock-ADONET-with-ease-using-IDataReader-Stub-objects.aspx

In that previous example I take advantage of DataTable CreateReader() method to generate IDataReader Stubs.  However in this case my Stub objects are DataSets, so I can use these table Stubs directly.

I also have the code for that tool available on the google code site:

http://code.google.com/p/data-stub-generator/

So, if setting up mocking and setting up Stub data was not the problem then what was? I had to write a number of tests against each of the BO including Shopping Cart.  That meant setting up the data for the cartTadaSetsTub DataSet.  I also wanted my code genaration tool to generate tables with one and couple of tests records that represent the dafault /valid data, and then explicitly set the values/cells that were needed for the test in the test itself.

For example let’s say that we have the rule that says that shopping cart can not check out if there is at least on item that has been discontinued since we placed it on the shopping cart.  That means that my table returning Products data would have to have one record that has “Discountinued” column set to true.  So let’s take a look at the code needeed for that:

DataSet cartDataSetStub = new DataSet();

DataTable products = new ShoppingCartProductsStub();

products.AddDefaultRow();

products.Rows[0][“Discountinued”] = true;

DataTable options = new ShoppingCartOptionsStub();

cartDataSetStub.Tables.Add(products);

cartDataSetStub.Tables.Add(options);

 

Mock cartData = MockManager.Mock(typeof(ShoppingCartData));

//Assure that _shoppingCartData.ExecuteDataSet()

//returns our cartDataSetStub instead of calling DB

cartData.ExpectAndReturn("ExecuteDataSet",cartDataSetStub); 

ShoppingCart cart = new ShoppingCart(); 

Assert.That(cart.CanCheckOut, Is.EqualTo(false));  

First 7 lines of code are there just to simply setup “fake” output from the database.  There is more code in the part that sets up the data for the test than the actual test.  And actually it could have been worse if I have not used the generated table stub objects ShoppingCartProductsStub and ShoppingCartOptionsStub.  All that code crowds the test and doesn’t really expresss my intention – it is hard to read.  So what did I do to solve that?

Fluent Interfaces to the rescue!  How about this for a change:

Mock cartData = MockManager.Mock(typeof(ShoppingCartData));

cartData.ExpectAndReturn(

    "ExecuteDataSet",

     Stub.GetDataSet(

         ShoppingCartProductsStub.Empty().AddDefaultRow()

            .AtRow(0)

            .InCell(“Discountinued”)

            .SetValue(true),

         ShoppingCartOptionsStub.Empty())); 

 

ShoppingCart cart = new ShoppingCart(); 

Assert.That(cart.CanCheckOut, Is.EqualTo(false)); 

Four statements above are functionaly equivalent to that code mesh in previous example.  And as you can see you can simply read the code to figure what it does!  We are generating DataSet with two tables where on the first table we add the default row of data and then set the cell “Discontinued” to false.  Second table is empty.  And that is it.

So how do these fluent interfaces work?  What is the logic behind them?  Well simply put, lest take a look at the methods that we use to manipulate an object  (StubTable in this case).  In the example above those methods are:  Empty(), AddDefaultRow(), AtRow(int rowNo), InCell(string cellName), SetValue(object value).  Generaly these methods would return void.  In fluent programing they return the object itself or better an interface that implements these other methods.  So first I created the object called StubTable:

public class StubTable : DataTable

{

    private int _currRow = 0;

    private string _currCell = string.Empty;

    protected StubTable(){}

    public static StubTable Empty()

    {

        return new StubTable();

    }

    public StubTable AtRow(int rowNo)

    {

        _currRow = rowNo;

        return this;

    }

    public StubTable InCell(string cellName)

    {

        _currCell = cellName;

        return this;

    }

    public StubTable SetValue(object value)

    {

        Rows[_currRow][_currCell] = value;

        return this;

    }

    public StubTable AddRow(params object[] values)

    {

        Rows.Add(values);

        return this;

    } 

}

  

Then the generated SoppingCartProducts and ShoppingCartOptions DataTables inherit from Stub table and are modified to look like this:

public class ShoppingCartProductsStub : StubTable

{

    public new static ShoppingCartProductsStub Empty()

    {

        return new ShoppingCartProductsStub();

    }

    protected ShoppingCartProductsStub()

    {

        InitColumns();

    }

    private void InitColumns()

    {

        Columns.Add("ShopingCartID", typeof(Int32));

        Columns.Add("ProductID", typeof(Int32));

        Columns.Add("ProductName", typeof(String));

        Columns.Add("ProductNumber", typeof(String));

        Columns.Add("ProductQty", typeof(Int32));

        Columns.Add("Price", typeof(Decimal));

        Columns.Add("PromotionPrice", typeof(Decimal));

        Columns.Add("Discontinued", typeof(Boolean));

       

    }

    public StubTable AddDefaultProduct()

    {

        Rows.Add(705582, 1, "Round Cook-N-Dine Built-in Cook Top", "MO-60", 5,

          decimal.Parse("1200.9400000000000"), decimal.Parse("1200.9400000000000"),false);

        return this;

    }

}

And Finaly Our Stb class that builds and returns the DataSet DTO:

public class Stub

{

    public static DataSet GetDataSet(params DataTable[] tables)

    {

        DataSet ds = new DataSet();

        foreach (DataTable table in tables)

            ds.Tables.Add(table);

        return ds;

    }

} 

The conclusion I would draw from this is that with a little thinking upfront, and a little refactoring we can make our tests a lot more readable.  We always have to keep in mind that our tests might be the first thing that the next developer is going to look at.  Making the test little bit more readible helps them figure out easier on how the actual object being tested is used and what are the expectations set for it.

 

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

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

Posted by ndibek on Thursday, February 07, 2008 5:20 AM
Permalink | Comments (980) | Post RSSRSS comment feed