Virtualization in Silverlight 4 RC

Published 31.03.2010 06:34 AM by Admin in Silverlight
Here is my new article about Virtualization in Silverlight 4 RC.

Currently rated 3.0 by 1 people

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

This is second part of my article where I talk about Validation in WPF using Entlib Validation Application Block. First part of my article is located on this location : http://blog.developers.ba/post/2009/07/07/WPF-Validation-using-Validation-Application-Block-41-Part-1-e28093-Server-side.aspx

There are many articles about client side validation in WPF. Most of these articles are similar and use implementation of IDataErrorInfo interface on Model class.

I have use some methods  already described in other articles just to show you how easy it is to implement client side validation in WPF using VAB.

I have model class called Customer where I have implemented IDataErrorInfo. Code looks like this :

public string Error
{
get {
StringBuilder error = new StringBuilder();
ValidationResults results = Validation.ValidateFromAttributes(this);
foreach (ValidationResult result in results)
{
error.AppendLine(result.Message);
}
return error.ToString() ;
}
}
public string this[string columnName]
{
get {
ValidationResults results = Validation.ValidateFromAttributes(this);
foreach (ValidationResult result in results)
{
if (result.Key == columnName)
{
return result.Message;
}
}
return string.Empty;
}
}

I have called ValidateFromAttributes method of Validation class that exists in VAB to get collection of ValidationResults. It is easy as that.

In Application.Resources of my WPF application I have defined some textbox error template and style to use when validation error is occurred. For this I have borrowed some code from other articles to save on time writing templates and styles.

And final in xaml on textboxes I have added following code where I have turn on Validation and defined witch error template to use :

<TextBox x:Name="txtFirstName"  Grid.Column="1"  TextWrapping="Wrap" 
Text="{Binding FirstName, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" />

References :

http://msdn.microsoft.com/en-us/magazine/cc700358.aspx

http://www.eggheadcafe.com/tutorials/aspnet/f726cd7d-cfcc-43c3-85d8-2afc75e7a08a/wpf-input-validation-with.aspx

Here is updated code in VS2010RC :ValidationServiceWCF.rar

Currently rated 5.0 by 2 people

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

WCF net.tcp protocol in Silverlight 4

Published 11.12.2009 02:54 PM by Admin in Silverlight | Workflow
Here is my new article about WCF net.tcp protocol in Silverlight 4  link

Currently rated 3.0 by 2 people

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

Skinning and Styling Silverlight Controls

Published 11.11.2009 05:45 AM by Admin in Silverlight

I have a new article on about skinning and styling Silverlight Controls on Silverlightshow. Check it out on link

Currently rated 3.0 by 2 people

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

Unit testing Facade pattern

Published 31.10.2009 01:02 PM by Admin in IOC | Patterns | Testing | Unit testing

The facade pattern is commonly used software engineering design pattern. His purpose is to provide simplified interface to a larger body of code.

It has several good uses:

- Make a software library easier to use and understand, since the facade has convenient methods for common tasks.
- Make code that uses the library more readable, for the same reason.
- Reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system.
- Wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).

Importance of this Design pattern we cannot underestimate.

In unit testing one of good practice is to put our dependencies in constructor of class. Facade pattern class however cannot have dependencies in constructor because it increase complexity of code.

In this blog post I will show you how to unit test facade pattern.

If I have 2 classes : EmailLogger and DatabaseLogger  and these two classes have same porpoise to Log same data.

These two classes have dependencies on another classes.

I want to have one class that I will call Logger with one method called Log that will be Facade for these two classes.

Class EmailLogger looks like this :

public class EmailLogger:ILogger
{
private readonly IEmailProxy _emailProxy;
public EmailLogger(IEmailProxy emailProxy)
{
_emailProxy = emailProxy;
}
public void Log(string message)
{
if(_emailProxy!=null)
{
_emailProxy.SendEmail(message);
}
else
{
throw new ArgumentNullException("_emailProxy");
}
}
}

 

This class have dependency on another class called EmailProxy and accepts interface IEmailProxy in constructor.

Class DatabaseLogger looks similar to EmailLogger :

 

public class DatabaseLogger:ILogger
{
private readonly IDatabaseMechanism _databaseMechanism;
public DatabaseLogger(IDatabaseMechanism databaseMechanism)
{
_databaseMechanism = databaseMechanism;
}
public void Log(string message)
{
if(_databaseMechanism!=null)
{
_databaseMechanism.SendLogToDatabase(message);
}
else
{
throw new ArgumentNullException("_databaseMechanism");
}
}
}

 

This class have dependency on class called DatabaseMechanism and accepts another interface IDatabaseMechanism in constructor.

And finally we have class called Logger that will be Facade for these two classes .

In this example I will use singleton implementation Unity container and Rhino Mocks.

 

public class Logger:ILogger
{
private readonly ILogger _emailLogger;
private readonly ILogger _databaseLogger;
public Logger()
{
IContainer container = new UnityContainer();
_emailLogger = container.Resolve("EmailLogger");
_databaseLogger = container.Resolve("DatabaseLogger");
}
public void Log(string message)
{
if(_emailLogger!=null)
{
_emailLogger.Log(message);
}
else
{
throw new ArgumentNullException("_emailLogger");
}
if (_databaseLogger != null)
{
_databaseLogger.Log(message);
}
else
{
throw new ArgumentNullException("_databaseLogger");
}
}
}

 

And of course we need to have some registration in container in some BootStraper class :

 

public static class BootStraper
{
public static void SetUp()
{
IContainer container = UnityContainer.Instance();
container.RegisterType();
container.RegisterType();
container.RegisterType("EmailLogger");
container.RegisterType("DatabaseLogger");
}
}

 

Consuming this class is simple :

 

public class Consume
{
public void ConsumeLogger()
{
Bootstraper.SetUp();
ILogger logger=new Logger();
logger.Log("Some message");
}
}

 

Code is simple and understandable and we don’t need to use any container to call this class . If someone reference your dll it can use your code without any container registration or resolve . You just call  method in that class and he not see container calls and deeper logic inside this Facade class.

And finally test is very simple too :

 

[TestClass]
public class LoggerTests
{
private readonly ILogger _emailLogger;
private readonly ILogger _databaseLogger;
private readonly IContainer _container;
public LoggerTests()
{
_container = UnityContainer.Instance();
_emailLogger = MockRepository.GenerateMock();
_databaseLogger = MockRepository.GenerateMock();
_container.RegisterInstance("EmailLogger", _emailLogger);
_container.RegisterInstance("DatabaseLogger", _databaseLogger);
}
[TestMethod]
public void Log_AcceptCorrectArgs_CallsEmailLoggerLog()
{
//arrange
ILogger logger = new Logger();
//act
logger.Log("Something");
ILogger emailLogger = _container.Resolve("EmailLogger");
//assert
emailLogger.AssertWasCalled(x => x.Log("Something"));
}
}

 

We register instance of mock objects EmailLogger and DataBaseLogger in Container and resolve later in test to ensure that correct method of mock object is called.

I hope this will help you in some of your projects.

Currently rated 2.7 by 3 people

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

This summer’s biggest blockbuster technology event is coming to Redmond, WA on the 17th of September. 

Register to attend the Silverlight-3 FireStarter event on Thursday, the 17th of September. We have a stellar speaker line up from the Microsoft roster. We will have Scott Guthrie keynote the event followed by presentations from Tim Heuer, Brad Abrams, Karl Shifflett and others...

 At this event we will focus on three areas:

 What’s latest and greatest in with the latest release of Silverlight

 What’s happening in the world of Expression 3, and

 Give you a run down on .NET RIA Services, Toolkit, etc. 

 

Time

Session

Speaker

8:45 – 9:00 AM

Event Kick off

Mithun Dhar

9:00 – 10:00 AM

Keynote

Scott Guthrie

10:00 – 11:00 AM

Key Silverlight Scenarios

Tim Heuer

11:00 – 11:15 AM

Break

 

11:15 AM – 12:15 PM

Expression 3 Overview (Includes Behaviors)

Adam Kinney

12:15 – 1:00 PM

Lunch Break (Provided by Microsoft)

 

1:00 – 1:30 PM

Sketch Flow

Janete Perez

1:30 – 2:30 PM

Toolkit & Controls

Justin Angel/Shawn Oster

2:30 – 3:30 PM

RIA Services

Brad Abrams

3:30 – 3:45 PM

Break

 

3:45 – 4:30 PM

Building Silverlight UIs with XAML Power toys

Karl Shifflett

4:30 – 5:00 PM

Q & A Panel

All Speakers

 

Registrations:

Source:
http://blogs.msdn.com/mithund/archive/2009/08/12/silverlight-3-firestarter-thursday-september-17th-2009-attend-redmond-wa-or-online-must-register.aspx

Be the first to rate this post

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

VSTestHost hang on Windows 7 RTM

Published 06.09.2009 06:08 PM by Admin in Testing
Tags: ,

I have Windows 7 RTM installed and Visual Studio 2008 with SP1. After writing some simple unit test and run it I have got VSTestHost.exe not responding error.

First I have thought that is Windows 7 error. I have looked and find some hotfix and if you have some similar problems I suggest to try run sample test with no code to ensure that problem is not in your code. That hotfix is on this address : http://code.msdn.microsoft.com/970449/Release/ProjectReleases.aspx?ReleaseId=2830

After better looking in my code I have found that problem is in my own code. I have had recursive call to a method inside unit test so test method is never finishing and VSTestHost is hang out after few seconds with unknown error.

Hopefully this post will help someone struggling with similar issues…

Be the first to rate this post

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

Screenshot your WPF application

Published 03.09.2009 06:17 AM by Admin in WPF
Tags: ,

Often we need a way to capture picture of UI. For example if error occurs in our application we can take picture of UI and send this picture in error report.

Usual way in windows forms is calling Graphic.CopyFromScreen method. This way is not work very well in WPF. If we have some transparent controls on form this method will save image under transparent control.

So in WPF we will use GDI+ to take picture of UI. We have internal class NativeMethods:

 internal class NativeMethods

    {

        [DllImport("user32.dll")]

        public extern static IntPtr GetDesktopWindow();

 

        [System.Runtime.InteropServices.DllImport("user32.dll")]

        public static extern IntPtr GetWindowDC(IntPtr hwnd);

 

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]

        public static extern IntPtr GetForegroundWindow();

 

        [System.Runtime.InteropServices.DllImport("gdi32.dll")]

        public static extern UInt64 BitBlt

             (IntPtr hDestDC,

             int x,

             int y,

             int nWidth,

             int nHeight,

             IntPtr hSrcDC,

             int xSrc,

             int ySrc,

             System.Int32 dwRop);

    }

And we take picture UI by calling this method :

 public void SaveScreen()

        {

            Bitmap myImage = new Bitmap(Screen.PrimaryScreen.WorkingArea.Width,

            Screen.PrimaryScreen.WorkingArea.Height);

 

            Graphics gr1 = Graphics.FromImage(myImage);

            IntPtr dc1 = gr1.GetHdc();

 

            IntPtr dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow());

 

 

            NativeMethods.BitBlt(dc1, Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, Screen.PrimaryScreen.Bounds.Width,

                 Screen.PrimaryScreen.Bounds.Height, dc2, 0, 0, 13369376);

            gr1.ReleaseHdc(dc1);

            myImage.Save("screen.png", ImageFormat.Png);

        }

 

You can download Demo application :

ScreenShotWPF.rar (38.14 kb)

Currently rated 2.5 by 4 people

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

1) DomainContext class changed significantly

One of improvements is adding support for Asynchronous Domain Operations. DomainContext supports three kinds of domain operations : Query, Submit and Invoke .

I have example where I call Load method of DomainContext and the asynchronous Load call returns a LoadOperation instance immediately or you can add your custom code on load completed:

 LoadOperation<Customers> load=this.context.Load(this.context.GetCustomersQuery());

          load.Completed += new EventHandler(load_Completed);

          this.dgGrid.ItemsSource = load.Entities;

 

2) DomainDataSource API Changes

Don’t break designer anymore. Minor paging problems are also solved.

Previously :

_domainDataSource.LoadMethodName = "GetCustomers";

 _domainDataSource.LoadParameters =new System.Windows.Data.ParameterCollection();

Now :

_domainDataSource.QueryName = "GetCustomers";

 _domainDataSource.QueryParameters =new System.Windows.Data.ParameterCollection();

 

Silverlight 3 databinding improvements with ElementName allows developers to bind one UIElement to another in XAML instead of having to write event handlers.

So now I bind DomainDataSource with my DataPager like this :

 Source="{Binding Data, ElementName=_domainDataSource}"

 I have attached some demo project bellow to show this.

 

3) New project type called .NET RIA Services Class Library

This project is used to simplify creation of N-Tier RIA services applications.

Picture1

When you choose to create .NET RIA Services Class Library it generates to class library projects

one for server and and for client side. Client side middle tier project you reference from your Silverlight app and server side middle tier you reference from your server side project. Project structure looks like this :

Picture2

 

When you add Entity context and DomainContext to .NET RIA Services Class Library project for server side and build project, MS Build will generate client side proxy for you in generated code folder on client side class library project.

Advantages of  middle tier class libraries are that they can be reused in other applications but shared code (specifically *.shared.cs ) in the class libraries is not propagated to the silverlight client during code generation.

 

4) No more need for add [Shared] metadata attribute

and much more changes….

Demo for paging with new DomainDataSource looks like this :

 


RiaServicesPagingDemo.rar

Currently rated 4.0 by 1 people

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

Launch event Silverlight 3 and Expression

Published 10.07.2009 04:59 AM by Admin in Silverlight

Watch http://www.seethelight.com/ for launch of Silverlight 3 RTW and Expression Blend 3 RC.

For download infomation about Silverlight 3 and Blend visit :

http://geekswithblogs.net/tkokke/archive/2009/07/09/silverlight-3-downloads.aspx

Be the first to rate this post

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

Radenko Zec Blog

Silverlight, C#, WCF, WPF,NET...