Resources

Inside Windows Communication Foundation by Justin Smith

Paul Ballard

12 Oct , 2013  

Dig into Windows Communication Foundation internals—and uncover the power of service-oriented design. This practical guide delivers in-depth insights and plenty of code samples to help you master the intricacies of developing and implementing connected applications.
Read more

Wintellect Blogs

Data Contracts and Behaviors over the Wire

Jeremy Likness

6 Sep , 2011  

One feature I employ often in Silverlight projects is the ability to share a model between the client and the server. When you expose a model using a WCF service, you can consume it on the Silverlight side and indicate you want to reuse types in a referenced assembly, rather than having the proxy types generated. At first glance this seems ideal because you can truly project behavior such as validation to the client without maintaining separate copies of the type in question. Upon further inspection, however, there can be some unexpected side effects.

Consider the following class that is defined in a standalone Silverlight assembly but shared on the server by adding it as a linked file:

[DataContract]
public class SimpleModel
{
    public SimpleModel()
    {
        NonMemberProperty = "This was initialized within the constructor.";
    }

    private string _field = "This is an initialized field.";

    public string NonMemberProperty { get; set; }
        
    [DataMember]
    public string MemberProperty { get; set; }
        
    public string Field
    {
        get { return _field; }
    }
}

I’ve purposefully packed a few different examples to help illustrate what is happening. It should be very clear what will happen when you instantiate the class. The field will be initialized to expose a value, the non-member will be given a value, and the member property (the one tagged as a data member) is initialized to the default value of null.… Read more

,

Wintellect Blogs

Silverlight 5 RC – Using the Task Parallel Library (TPL)

Jeremy Likness

1 Sep , 2011  

One enhancement that quietly slipped into the Silverlight 5 RC is the inclusion of Tasks. This is not the full-blown Task Parallel Library (TPL) to my knowledge (as it lacks the Parallel class and extensions) but it does provide Task, its related factories, and the functionality to chain and monitor tasks. The purpose of the library is to simplify asynchronous methods.

This post will show you an example of using the library. I’m not presenting this as a best practice, but only as a thought exercise to show you the use of the Task library in a visual way. The program computes the factorials of several numbers, but uses task continuation to ensure only one web service call is made at a time (thus simulating a sequential asynchronous workflow). You can modify the example to fire all threads simultaneously.

First, a simple service in the web project to compute the factorial:

[ServiceContract(Namespace = "http://jeremylikness.com/examples/")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SimpleService
{
    [OperationContract]
    public long Factorial(int value)
    {
        long result = value;
        while (--value 0)
        {
            result *= value;
        }
        return result;
    }       
}

Add the service reference to the Silverlight project. Next, create a simple class in the Silverlight project to hold the value and the result that implements property change notifications:

public class Factorial : INotifyPropertyChanged 
{
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            _value = value;
            RaisePropertyChange("Value");
        }
    }

    private long _result;
    public long Result
    {
        get { return _result; }
        set
        {
            _result = value;
            RaisePropertyChange("Result");
        }
    }

    protected void RaisePropertyChange(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

The main page holds a button to fire off the calls and a list box to show the results:

<Grid x:Name="LayoutRoot" Background="White"<Grid.RowDefinitions<RowDefinition Height="Auto"/<RowDefinition Height="Auto"/</Grid.RowDefinitions<ListBox Grid.Row="1" x:Name="FactorialList"<ListBox.ItemTemplate<DataTemplate<StackPanel Orientation="Horizontal"<TextBlock Text="{Binding Value}"/<TextBlock Text="!="/<TextBlock Text="{Binding Result}"/</StackPanel</DataTemplate</ListBox.ItemTemplate</ListBox<Button Click="_BtnFactorClick" x:Name="btnFactor" IsEnabled="False" 
            Content="Factor" HorizontalAlignment="Left"
            VerticalAlignment="Top" Margin="10"/</Grid

In the code-behind for the main page, hold a list of the Factorial objects:

private readonly List<Factorial_factorials;

Then populate it with the numbers 1 through 20 and bind it to the list box – at this point you can run the application and see the list of numbers to be factored:

public MainPage()
{
    InitializeComponent();

    _factorials = new List<Factorial();
            
    for (var x = 0; x < 20; x++)
    {
        _factorials.Add(new Factorial {Value = x + 1});
    }

    FactorialList.ItemsSource = _factorials;
}

Add the code to create a channel for the service.… Read more

, ,

Wintellect Blogs

Entity Framework 4.1 Code First, Silverlight, and Shared Models with REST+JSON

Jeremy Likness

25 May , 2011  

It’s a debate that has existed for decades. The database architects insist that data is golden and the most efficient way to build software is to generate it from the database schema, while the object-oriented code junkies swear that a nice “domain model” is the way to go and that persistence is a side effect of making those objects stick around longer. Of course, if you’ve worked on enterprise projects long enough you’ll find the answer is often somewhere in the middle: some projects benefit from a database-centric approach, others from a model-centric approach, but many require a outward in approach. Design the schemas for the database to do what it does best with relationships, design the domain model to encapsulate the data and behavior of the class, and translate one to the other (hence the ORM, or object-relational mapper).

For a very light example, consider a conference event that has speakers and sessions. Speakers may “own” several sessions they speak at, while sessions may “have” several speakers when the session is co-hosted.

The Database

In SQL this relationship would be expressed through foreign keys, often with a “link” table to facilitate the many-to-many relationship, like this:

You can easily generate this database with the following T-SQL statements:

CREATE TABLE [dbo].[tblSession] (
    [Id]          INT           IDENTITY (1, 1) NOT NULL,
    [SessionName] NVARCHAR (50) NOT NULL
);
GO
ALTER TABLE [dbo].[tblSession]
    ADD CONSTRAINT [PK_tblSession] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
GO
CREATE TABLE [dbo].[tblSessionSpeaker] (
    [Id]        INT IDENTITY (1, 1) NOT NULL,
    [SessionId] INT NOT NULL,
    [SpeakerId] INT NOT NULL
);
GO
ALTER TABLE [dbo].[tblSessionSpeaker]
    ADD CONSTRAINT [PK_tblSessionSpeaker] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
GO
CREATE TABLE [dbo].[tblSpeaker] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) NOT NULL
);
GO
ALTER TABLE [dbo].[tblSpeaker]
    ADD CONSTRAINT [PK_tblSpeaker] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
GO
ALTER TABLE [dbo].[tblSessionSpeaker] WITH NOCHECK
    ADD CONSTRAINT [FK_tblSessionSpeaker_tblSession] FOREIGN KEY ([SessionId]) REFERENCES [dbo].[tblSession] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
ALTER TABLE [dbo].[tblSessionSpeaker] WITH NOCHECK
    ADD CONSTRAINT [FK_tblSessionSpeaker_tblSpeaker] FOREIGN KEY ([SpeakerId]) REFERENCES [dbo].[tblSpeaker] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;

The Application

However, moving over the application side, the “link table” just doesn’t make sense.… Read more

, ,

Wintellect Blogs

Silverlight and WCF Service Consumption: Event vs. APM

Jeremy Likness

29 Nov , 2010  

I’ve blogged several times about how I like to handle services in Silverlight. For two key posts, take a look at:

In this post we’ll explore the difference between using the actual contract for a WCF service in Silverlight versus using the generated client. The difference is subtle but important, and involves not only the event-based model and the Asynchronous Programming Model (APM) but also some nuances with threads.

There is no code project for this because the nuance is in the way you call the service, not the example itself, but there should be enough code in this post for you to recreate the example if you want to test it yourself.

Here’s the rub: let’s create a simple service that adds two integers and returns the result. The contract is simply:

[ServiceContract(Namespace = "http://jeremylikness.com/silverlight/")]
public interface IAddService
{
    [OperationContract]
    int Add(int x, int y);
}

Now we can implement it – just add the numbers and return the value:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AddService : IAddService
{        
    public int Add(int x, int y)
    {
        return x + y;
    }        
}

So that’s easy enough (and we’ve jumped through our first Silverlight hoop by flagging the service with the compatibility attribute).… Read more

, ,

Wintellect Blogs

Simplifying Asynchronous Calls in Silverlight using Action

Jeremy Likness

9 Dec , 2009  

This post explores a way to encapsulate web service calls from Silverlight in a way that is easy to use and understand.

As anyone who works with Silverlight knows, Silverlight forces web service calls to be asynchronous. There is a good reason for this, which I won’t get into with this post. What I would like to do is demonstrate an approach that advocates a clean separation of the internals of the service from the application that is consuming it.

First, I am assuming you understand web services and WCF. I assume you’ve called services from Silverlight, and are aware of the nuances of configuring the endpoint, etc. I am also going to assume you are familiar with some frameworks such as Prism, MEF, Caliburn, etc that advocate clean separation of concerns and modular design.

Let’s assume I have a service on my web page that is a calculator (oh, where did I get that idea?) It looks something like this:


[ServiceContract(Namespace = "http://www.wintellect.com/sample")]    
public interface ICalculatorService
{
    [OperationContract]
    long Multiply(int x, int y);
}

Simple, correct? The first thing I’m going to do is to create a similar interface on my Silverlight client. This interface will hide the details of how the service is connected and wired.… Read more

,

Wintellect Blogs

Host WCF as Windows Service without Installing

Jeremy Likness

5 Dec , 2009  

I am working on a project that involves a centralized UI that then coordinates with agents to send out instructions. The agents will be WCF endpoints and to ease deployment/minimize the install footprint, they will install as windows services with a nice installer rather than hanging onto an IIS webspace directly.

In this post I want to walk you through the process of creating that WCF host programmatically, as well as a small little tweak that will allow you to run and test without having to install the service. It’s actually quite easy to do but it’s one of those things that can produce an “ah-hah!” moment if you haven’t done it before.

To start with, let’s create a simple service and operation contract. Create a new interface, call it IHelloWorldService, and add a method, like this:


[ServiceContract(Namespace="http://wintellect.com/sample")]
public interface IHelloWorldService
{
    [OperationContract]
    [FaultContract(typeof(Exception))]
    string Hi();
}

You’ll have to add references and usings for System.ServiceModel.

Next, implement the interface:


public class HelloWorldService : IHelloWorldService
{
    const string REPLY = "Hello, world."; 

    public string Hi()
    {
        return REPLY; 
    }

}

That’s all it takes to make your WCF service. Now we just need a way to host it. Add another reference to System.ServiceProcess.… Read more

Wintellect Blogs

Silverlight Communication: Three Ways to Connect

Jeremy Likness

3 Nov , 2009  

Silverlight has myriad ways to connect to other systems and retrieve information for your applications. It is a common question people ask (“How do I get my data from the database to Silverlight?”) and each method has its own pros and cons. The purpose of this project, “Silverlight Communicator,” is to provide a simple, easy reference project that demonstrates three sample methods for communication in Silverlight 3. While these certainly aren’t all of the ways Silverlight can obtain data, it does summarize more commonly used methods.

Download Source Now (44 Kb)

Silverlight Communicator

The main page is straightforward and uses the MVVM (Model-View-ViewModel) pattern to bind to the selections (no code-behind). I kept it simple and sweet: just a grid with two listboxes, which are bound to the view model that is instantiated as a static resource.

<UserControl x:Class="SilverlightCommunication.MainPage"
    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" 
    xmlns:local="clr-namespace:SilverlightCommunication"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"<UserControl.Resources<local:ViewModel x:Key="ViewModel"/</UserControl.Resources<Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}"<Grid.ColumnDefinitions<ColumnDefinition Width="1*"/<ColumnDefinition Width="1*"/</Grid.ColumnDefinitions<ListBox Grid.Column="0" ItemsSource="{Binding CommunicationTypes}" DisplayMemberPath="Name"
                 SelectedItem="{Binding Path=Communication,Mode=TwoWay}"/<ListBox Grid.Column="1" ItemsSource="{Binding Months}" DisplayMemberPath="Name"/</Grid</UserControl

The view model exposes a collection of CommunicationType. This could probably be an enum but for the contrived example, it is loaded up and wired in the view model constructor and maps to the options for choices of the communication type.… Read more

, ,

Wintellect Blogs

Security Implications Of Services Impersonating Callers

Paul Mehner

23 Dec , 2007  

In my last post (Caller Impersonation for WCF Services Hosted Under IIS Appears Broken), I laid out my rationale for why I felt that the security of services impersonating a caller when hosted under IIS was broken. To be responsible, I feel it necessary to follow-up my previous assertion by noting that such a configuration is not a best-practice, even though many corporate staff developers may be tempted to secure their intranet services this way.

Allowing a service to impersonate the caller’s identity requires that the caller have a high degree of trust in the service that he or she is interacting with. Of course it’s very unusual for a user to be aware of the services their applications interact with, so this is a completely unrealistic expectation. When a service is configured to impersonate its callers, it could potentially perform clandestine operations within a network using authorizations granted to the caller’s identity without the caller being aware.

To further illuminate the security vulnerabilities of callers trusting services to impersonate their identities, it’s important to note that most services are focused on a specific area of business while application users typically have much broader and deeper sets of authorizations.… Read more

Wintellect Blogs

Caller Impersonation for WCF Services Hosted Under IIS Appears Broken

Paul Mehner

16 Dec , 2007  

There is a security feature of WCF services hosted under IIS that I find poorly implemented. In all honesty, it appears to be broken and non-compliant with its intended purpose. If you’re developing services for use in the intranet environment, then it’s quite reasonable for you to expect that a service can impersonate your Windows identity while it performs its work. After all, security personnel have no doubt already established your intranet authentication and authorization policies for corporate assets, and internal service security should be able to fit within this established paradigm.

Unfortunately, WCF will throw an erroneously worded exception about your attempt to use anonymous access when the IIS hosted service that performs caller impersonation is set to require a Windows identity (presumably a bug of assuming that “not equal to 1” identity means “equal to 0” identities). The reason why you likely had to read the first sentence more than once is that the error message complains about your use of Anonymous when you turn Windows security on, but turning Windows off and Anonymous on makes the error about using Anonymous go away! Confused by the apparent contradiction? Well, so was I when I first encountered it.

In my opinion, the recommendations from Microsoft for working around this limitation are completely idealized and wholly unrealistic.Read more