If you are interesting to learn more about Validation Application Block you can always download Hand on Labs about VAB: http://www.microsoft.com/downloads/details.aspx?FamilyID=2C34A9CB-17CF-4AEC-8DE6-EEACBBB74413&displaylang=en

In these labs you will find very good explanation about using VAB integration with WCF, but what if you are manually creating proxy instead using add service reference?

In this article I will show you how to use VAB 4.1 with WCF and manually generated proxy.

My solution structure looks like this :

Picture1

I have created one project called DataContracts where all DataContract classes and Validation rules are defined. Code for that class looks like this :

 public class Customer

    {

        [StringLengthValidator(1, 25,

           MessageTemplateResourceType = typeof(Resources),

           MessageTemplateResourceName = "FirstNameMessage")]

        [NotNullValidator]

        public string FirstName { get; set; }

        [StringLengthValidator(1, 25,

          MessageTemplateResourceType = typeof(Resources),

          MessageTemplateResourceName = "LastNameMessage")]

        [NotNullValidator]

        public string LastName { get; set; }

        public string Nickname { get; set; }

        public DateTime BirthDate { get; set; }

        [ObjectValidator]

        public Address Address { get; set; }

 

        public Customer()

        {

            this.Address=new Address();

        }

    }

 

    public class Address

    {

        [StringLengthValidator(1, 50)]

        public string StreetName { get; set; }

 

        public int Number { get; set; }

        [DomainValidator("AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY",

            MessageTemplate = "Value is not a valid US state two-letter abbreviation.")]

        public string USState { get; set; }

 

    }

I have manually created proxy class. It looks like this :

  public class CustomerClientProxy : ClientBase<ICustomerService>, ICustomerService

    {

 

        public string ProcessCustomer(DataContracts.Customer customer, string notes)

        {

            return Channel.ProcessCustomer(customer, notes);

        }

 

    }

In service contracts project I have defined interface that WCF will use. We must decorate method signature in interface with  validation attribute that define FaultContract for method.

We are using  ValidationFault class that is defined in VAB for error transporting to the client side.

  [FaultContract(typeof(ValidationFault))]

        string ProcessCustomer(

            Customer customer, [StringLengthValidator(1, 100,

                MessageTemplate = "The notes must be 1 to 100 characters long.")]

            string notes);

In web config file for WCF service we must add new behaviorConfiguration for Endpoint. ValidationElement is used to perform some validation actions on WCF before calling method on WCF.

<behaviorExtensions>
<add name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF.ValidationElement, 
        Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF, Version=4.1.0.0, Culture=neutral, 
        PublicKeyToken=31bf3856ad364e35" />
</behaviorExtensions>

On client side I have one standard WPF application with basic App.Config where is just defined ABC for WCF. (address, binding, contract)

I have bind client side textboxes on the form with my Customer class.  After that I have some code to catch exceptions throw by the server and show that exceptions in simple message box.

using (Proxy.CustomerClientProxy client = new Proxy.CustomerClientProxy())

            {

                try

                {

 

                    Customer cust=((Customer)this.DataContext);

 

                    client.ProcessCustomer(cust, "My message!!!");

                }

                catch (FaultException<ValidationFault> fex)

                {

                    StringBuilder builder = new StringBuilder();

                    builder.AppendLine("Validation error invoking service:
"
);

                    foreach (ValidationDetail result in fex.Detail.Details)

                    {

                        builder.AppendLine(

                            string.Format("{0}: {1}
"
, result.Key, result.Message));

                    }

 

                    MessageBox.Show(builder.ToString());

 

                }

 

                catch (Exception ex)

                {

                    MessageBox.Show(ex.StackTrace.ToString());

                }

            }

After I run my application and enter some incorrect values I get message box :

Picture2

 

Here is complete code :ValidationServiceWCF.rar

Reference : http://www.clariusconsulting.net/blogs/kzu/archive/2007/09/24/WhyweneedanEntLibStandaloneValidationApplicationBlock.aspx

Currently rated 4.5 by 2 people

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

I was one of presenters at Microsoft community conference Kulendayz 2009 in Beli Manastir. I have presented there .NET Ria services. Here is my powerpoints and demos:

  .Net Ria Services.pptx (768.70 kb)

  Demos.rar (7.34 mb)

Most of content I have referenced from Nikhil's and Brad's presentation from Mix this year.



Be the first to rate this post

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

These days everybody are using IOC container so I tried to integrate SL 3 Beta(MIX09) Sample chat application that represent how to work with polling duplex with Unity Ioc container. That sample chat application is available for download on codeplex.

After looking how to integrate Unity with Wcf I have founded few nice examples. All those examples are pretty much same.

To integrate Unity with Wcf we must create UnityServiceHostFactory and in markup of service say that service use that factory.

Polling duplex however has also DuplexServiceFactory. So how I integrate those two factories?

I have created all classes needed for UnityServiceHostFactory in UnityServiceHostFactory.cs file such as UnityServiceHost, UnityInstanceProvider and UnityServiceBehavior.

To make example more interesting I have also create IExample interface to inject this interface in service contructor like this:

public ChatService(IExample example)

        {

            examp = example;

            //Set up a stock update every 5 seconds

            this.stockTimer = new Timer(

                new TimerCallback(StockUpdate),

                null, 0, 5000);

        }

void StockUpdate(object o)

        {

            StockTickerMessage stm = new StockTickerMessage();

            //change this message to use method in interface

 

            stm.stock = "MSFT";

            stm.stock += examp.GetMessage();//calling method from injected interface

            stm.price = new System.Random().Next(20, 50);

            PushToAllClients(stm);

        }

In StockUpdate method in ChatService class in have called method GetMessage from Example class:

class Example : IExample

    {

        public string GetMessage()

        {

            return "Example";

        }

    }

In DuplexServiceFactory I have changed CreateServiceHost to use Unity container.

 protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

        {

 

            UnityServiceHost host = new UnityServiceHost(serviceType, baseAddresses);

            UnityContainer unity = new UnityContainer();

            host.Container = unity;

 

 

            unity.RegisterType<IExample, Example>();

 

 

      

 

            CustomBinding binding = new CustomBinding(

              new PollingDuplexBindingElement(),

              new BinaryMessageEncodingBindingElement(),

              new HttpTransportBindingElement());

 

            host.Description.Behaviors.Add(new ServiceMetadataBehavior());

            host.AddServiceEndpoint(typeof(IUniversalDuplexContract), binding, "");

            host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

 

            return host;

        }

Now if I run my sample application I get error:

“The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.”

Reason for this is because my Polling duplex class is decorated as singleton class

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

    public abstract class DuplexService : IUniversalDuplexContract

    { 

and ServiceDescription.CreateImplementation and is hard-coded to look for a parameterless constructor.

But I want to make contructor injection so my service class must have contructor with parameter.

I have been remove [ServiceBehavior(InstanceContextMode=InstanceContextMode.SIngle)] and let Unity to return singleton instance of DuplexService class.

So I have put in web config file some code that Unity will use to return Singleton instance of DuplexService.

<section name="unity"
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
                  Microsoft.Practices.Unity.Configuration" />
<unity>
<containers>
<container>
<types>
<type type="Microsoft.Silverlight.Cdf.Samples.Duplex.IUniversalDuplexContract,ChatWebApp"
mapTo="Microsoft.Silverlight.Cdf.Samples.Chat.ChatService,ChatWebApp"
>
<lifetime type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
    Microsoft.Practices.Unity" />
type>
types>
container>
containers>
unity>

After that I have consumed code from web config in my application.

  UnityServiceHost host = new UnityServiceHost(serviceType, baseAddresses);

            UnityContainer unity = new UnityContainer();

            host.Container = unity;

 

 

            unity.RegisterType<IExample, Example>();

 

 

            UnityConfigurationSection section;

            section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            section.Containers.Default.Configure(unity);

I have tested this by calling IUniversalDuplexContract cont1 = unity.Resolve() twice and comparing hash of two instances.

Hash was exactly same.That means that  Unity returns singleton instance of ChatService class.

I hope this will help.

Demo project : DuplexWithUnity.rar

Be the first to rate this post

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

Today I have take a look on Single responsibility principle.

It states that every object should have a single responsibility.

It looks very logic and nice but does it mean that I can have only one method per class? Does it mean that every interface that I create need to have only one method for implement?

I am not quite sure that I understand this principle.What do you think?

Currently rated 4.0 by 1 people

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

Unit testing private methods yes or no?

Published 12.04.2009 05:01 PM by Admin in Testing
Tags:

I am beginner at field TDD. Recently I have conversation with Dror Helper  should I test my private methods or not. After I have talked with him and little reconsider I thing we don’t need to test private methods.

If we need to test private methods we can do this trough public methods that call those private methods.

For example if we have one public method that calls one or several other private methods like this:

public static bool LogIn(string userName, string password)

        {

            var user = new User(userName, password);

 

            if (verifyThatUserIsValid(user))

            {

 

                return true;

            }

            else

            {

                return false;

            }

        }

 

 

 

        private static bool verifyThatUserIsValid(User user)

        {

            throw new NotImplementedException();

        }

 

So if I want to make unit tests for method verifyThatUserIsValid I can easily make unit tests for method LogIn to test that method. What do you think about this?

Be the first to rate this post

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

ItemClick event on Silverlight ItemsControl

Published 16.03.2009 05:21 PM by Admin in C# | Silverlight

Recently I have been playing with Rik Robinson’s project called Silverlight 2 Scroller. You can read more about this control on this address :

http://www.wintellect.com/CS/blogs/rrobinson/archive/2009/01/22/yngwie-malmsteen-syndrome-silverlight-2-scroller-revisited.aspx

After looking at ItemsControl I have realize that you probobly want to implement click event when user click on your item in ItemsControl.ItemsControl is widely used in Silverlight.I have little modify project above to implement that click event.

Proccess is simple.I have created delegate that reference to method witch have ItemControlEventArgs parameter.I have also created ItemControlEventArgs class that inherits from EventArgs class and inside this class I have add property that represents Item data that is shown inside my  user control.

 public delegate void ItemClickDelegate(ItemControlEventArgs e);

        public class ItemControlEventArgs:EventArgs

        {

            public Employee ItemEmployee{get;set;}   

        }

        public event ItemClickDelegate ItemClicked;

One problem is that PresentationFrameworkCollection class does not have string indexer implemented, so we can’t write something like this :

(sender as Grid).Children["NameOfControl"]

If you have your own user control that use ItemsControl you probably have grid or stackPanel as your container control.I have implement on Grid_MouseLeftButtonDown event some code that iterate trough collection controls and find controls with particular names.

        private void Grid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)

        {

            //clicked Employee

            Employee emp = new Employee();

            //iterate trough collection of children controls in grid to get emp info

            foreach (UIElement element in

            (sender as Grid).Children)

            {

                if (element != null)

                {

                    if (element.GetType() == typeof(System.Windows.Controls.StackPanel))

                    {

                        foreach (UIElement childrenElement in (element as StackPanel).Children)

                        {

                            Type childType = childrenElement.GetType();

                            if (childType == typeof(System.Windows.Controls.TextBlock))

                            {

                                if ((childrenElement as TextBlock).Name == "FullName")

                                {

                                    emp.FullName = (childrenElement as TextBlock).Text;

                                }

                                else if ((childrenElement as TextBlock).Name == "Title")

                                {

                                    emp.Title = (childrenElement as TextBlock).Text;

                                }

                                else if ((childrenElement as TextBlock).Name == "Age")

                                {

                                    emp.Age = Convert.ToInt32((childrenElement as TextBlock).Text);

                                }

                            }                 

                        }

                    }

 

                    //image property we don't use for anything

                        emp.ImagePath = "";

                }

 

            }

            ItemControlEventArgs args=new ItemControlEventArgs();

            args.ItemEmployee=emp;

            ItemClicked(args);

        }

After that on page where I use my user control I have event ItemClicked

 SilverlightScroller:ScrollerControl x:Name="theScrollerControl" 

            Margin="0,50,0,0" HorizontalAlignment="Center" VerticalAlignment="Top"

            ScrollTime="250" Width="940" Height="620" ItemClicked="item_Clicked"

and on codebehind I can get my itemData:

 private void item_Clicked(ScrollerControl.ItemControlEventArgs e)

        {

            MessageBox.Show(

            e.ItemEmployee.FullName + " " + e.ItemEmployee.Title + " " +

            e.ItemEmployee.Age.ToString() + " " + e.ItemEmployee.ImagePath);

        }

You can look picture bellow.

Proba1

Currently rated 5.0 by 3 people

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

Recently I have been playing with silverlight and I came into a situation where MouseLeftButtonDown event is not triggered every time.It is only triggered when I click on child control inside container.

One way to fix this is to set background color of container to something.In my example I set my background color of grid control to transparent.

<Grid Height="100" Width="Auto" MouseLeftButtonDown="Grid_MouseLeftButtonDown" Background="Transparent">

Now if you click anywhere inside grid control MouseLeftButtonDown event is triggered.

Currently rated 5.0 by 2 people

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

SqlException class does'nt have public constructor

Published 08.03.2009 07:43 AM by Admin in C# | Sql | Testing
Tags: , ,

I am currently preparing ado.net 3.5 course so I try to throw SqlException in one of my examples and realize that SqlException class is sealed and has no public constructor.

I have found solution on Rido blog http://blogs.msdn.com/rido how to create SqlException using reflection.

        public static SqlException CreateSqlException(string errorMessage, int errorNumber)

        {

 

            SqlErrorCollection collection = GetErrorCollection();

            SqlError error = GetError(errorNumber, errorMessage);

            MethodInfo addMethod = collection.GetType().

            GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);

            addMethod.Invoke(collection, new object[] { error });

            Type[] types = new Type[] { typeof(string), typeof(SqlErrorCollection) };

            object[] parameters = new object[] { errorMessage, collection };

            ConstructorInfo constructor = typeof(SqlException).

            GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);

            SqlException exception = (SqlException)constructor.Invoke(parameters);

            return exception;

        }

        private static SqlError GetError(int errorCode, string message)

        {

            object[] parameters = new object[] {

            errorCode, (byte)0, (byte)10, "server", message, "procedure", 0 };

            Type[] types = new Type[] {

            typeof(int), typeof(byte), typeof(byte), typeof(string), typeof(string),

            typeof(string), typeof(int) };

            ConstructorInfo constructor = typeof(SqlError).

             GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);

            SqlError error = (SqlError)constructor.Invoke(parameters);

            return error;

        }

 

        private static SqlErrorCollection GetErrorCollection()

        {

            ConstructorInfo constructor = typeof(SqlErrorCollection).

            GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);

            SqlErrorCollection collection = (SqlErrorCollection)constructor.Invoke(new object[] { });

            return collection;

        }

Currently rated 3.0 by 2 people

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

How do I prism 2 videos for Silverlight

Published 28.02.2009 08:15 AM by Admin in Silverlight

Bob and Erwin put together a series of videos that tell how to modular Silverlight Application. For more information see Bobs blog.

 

Creating a solution and adding a module (10 minutes)


Composing views (10 minutes)
 

Implementing a view and using services (22 minutes)
 

Communicating between views (24 minutes)

 

Be the first to rate this post

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

Last week I have been started to read about full duplex wcf and his implementation in silverlight applications.I have read tons of articles on MSDN and tons of blog and forum posts.

Recently I have found solution for chat application on this blog http://silverbling.blogspot.com/2009/01/using-pollingduplexhttpbinding-for.html 

so I have little modified that application but it is basically same application.This application is based on this blog post of Dan Wahlin :

http://weblogs.asp.net/dwahlin/archive/2008/06/16/pushing-data-to-a-silverlight-client-with-wcf-duplex-service-part-i.aspx

Everything that you need to know about building wcf full duplex application for silverlight you can find on msdn :

http://msdn.microsoft.com/en-us/library/cc645027(VS.95).aspx

and for accessing wcf duplex from silverlight client:

http://msdn.microsoft.com/en-us/library/cc645028(VS.95).aspx 

This application is also based on same articles above.This is simple chat application that has no chat rooms.Same concept you can use for developing multiplayer online silverlight games.

If you want to modify this application to add rooms you can look some useful pattern for that  List-Based Publish-Subscribe  :

http://msdn.microsoft.com/en-us/library/ms752254.aspx

What I have get when I have finished project looks like this :

Ielook1

Only thing that you need to do to make this project work for you is to change url of your wcf web service in page.xaml.cs .

this.pusher = new PushDataReceiver(

                this.processor,

                "http://localhost.:5433/SilverlightChatDuplexService.svc",

                "Silverlight/ISilverlightChatDuplexService/InitiateDuplex",    // The Wcf function or action.

                "");

 

Demo project : SilverlightChatSource

 

 

Currently rated 3.5 by 2 people

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

Radenko Zec Blog

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