Using the Entity Framework in a Layered Architecture

Thursday, July 03 2008 - , , , , - 1 comments

My July 2008 Data Points column was just released on the MSDN Magazine web site. This month I demonstrate how to use the Entity Framework in a multi-tiered architecture passing entities through the layers via WCF. The code sample is available from their web site too.

The Entity Framework has been a much discussed topic of late. Many articles discuss and show how to build different types of models and facets of the Entity Framework. This article shows one way to integrate the Entity Framework’s models into an application that uses layers and a form of the MVP pattern.

July2008

Data Services with Silverlight 2 – New Name, Same Book

Thursday, July 03 2008 - , - 0 comments

It’s really semantics, but the title of my book has been changed slightly to now be called “Data Services with Silverlight 2”. Titles are not super important to me, but it became clear to me as the book was flowing out in Word and OneNote that the many of the topics were tending to be focused on data services. For example: using Silverlight 2 with WCF, RSS, REST, Cross Domain issues, Sockets, LINQ to XML, and so on. Dealing with data from Silverlight is the central theme of the book. This includes data binding, getting data from services, sending it back, and massaging the data. So in the end the new title just made more sense.

I’m pretty excited about where the book is heading, its really unfolding nicely so far. I cannot wait til its out later this year!

book2

My Book Has a Life of its Own

Sunday, June 29 2008 - , , - 0 comments

I set out to write a book on data access, services, and Silverlight 2 and stick to those topics faithfully. I have a sticky note on my desk that shows the main topics and the word “thin” as a reminder to myself to stick to the point and keep the book thin  … thin as in not a brick that someone could bludgeon me with if they don’t like the book :)

Data Access with Silverlight 2

When I buy an intermediate to advanced book, I love it when the book gets to the point, shows me what I need to know and skips over the 250 pages of introductory material.  Perhaps a chapter or 2 of intro material is fine, because then I can skip over it if I need to or read it if the material is indeed new to me.

My book is not an introduction to Silverlight. It is not an all encompassing book telling the reader everything there is to know about Silverlight. Rather my book explains what is needed to build data driven applications using the most appropriate tools in Silverlight to accomplish this goal.

This does cause a bit of a dilemma because I feel that you cannot build data driven applications in Silverlight without understanding Dependency Properties and the fundamentals of Silverlight’s data binding. I cover these areas, but to stay true to my sticky note, I cover these topics with a little bit of “why” and a little bit of “how” … and I don’t take 250 pages to cover them.

The bulk of the material is starting to take shape and I just looked at my original table of contents and laughed. Its 90% different at this point :) I mentioned a few weeks ago that I use OneNote to organize my thoughts and my chapters. I would be lost right now without it. I have moved ideas, chapters, created new chapters, and sliced and diced my notes so many times that I cannot imagine how I would stay focused without it. OneNote keeps me writing instead of trying to figure out how to organize myself. it is also a great tool for figuring out what you will be writing about in the next chapter. Which at this point, i am realizing that all i can promise myself is what will be in this chapter and what will follow it in the next chapter.

I am having a good time putting the material together, and other than the DataGrid (whose beta state is not fun), the rest of the material is flowing out pretty well. I am looking forward to seeing the completed work in December later this year (which means I need the bulk of it done by September!). The funny thing is that I am working harder on this this shorter book than I did on any of my books that were twice as long!

My Fall is Taking Shaping - VSLive NY in September

Saturday, June 28 2008 - , , , , , - 0 comments

I’ll be flying to New York City in September to present 2 sessions at VSLive NY at the Marriott at Brooklyn Bridge from Sep 7-10. They’ll be some great sessions there from some great presenters. Registrations are open now.

image

Even though the conference season is on break over the summer, my summer has been a bit crazy so far with writing my upcoming book on data access, devices and Silverlight 2. I’ve got a few nice breaks with some user groups that i have done and a few more I am looking forward to. Its great to get out and share with the community. In July I will be heading to Miramar Florida and to Albany NY for some great user group meetings. Head over to my events page to see my full lineup, as it unfolds.

A colleague and friend of mine, Brian Peek, who’s fame is skyrocketing lately will be presenting 2 sessions here as well. Brian is the author of the Wiimote library that has been talked about and downloaded by many people and has even been discussed in Newsweek magazine. If you plan on attending VSLive, be sure to check out Brian’s sessions.

I’ll be presenting the following sessions at VSLive in NYC:

Building Effective Data Bound Applications with WPF and Silverlight
John Papa
Monday, September 8, 4:45 p.m.
XAML makes it easy to design robust user interfaces and it provides powerful data-binding capabilities. With WPF and Silverlight, you can perform data manipulation using code, XAML, or a combination of both. You can bind to controls, public properties, XML, or objects, making data binding quick, flexible, and easier than ever. This session will demonstrate how to use these data binding features with WPF and Silverlight applications.

ASP.NET Data Binding
John Papa
Tuesday, September 9, 9:45 a.m.
Generics can enhance the implementation of a data access model. You can bind a list of objects directly to a bindable control or you can use the ADO.NET DataSet. The new data binding and data source objects in ASP.NET are a huge step forward in reducing and simplifying UI code. This session will begin by demonstrating how to use the SqlDataSource to retrieve and modify data from an OLE DB compliant database and bind it directly to an ASP.NET web form, without writing any code. The ObjectDataSource is ideal for multi layer applications as it allows data bound web controls to bind to a data source through a middle tier class library or web service. It can also be used to assist in binding either a DataSet or a list of objects using Generics. I will demonstrate these new data source tools and walk through examples of when and where each is ideal.

Refactoring a PropertyChanged Event Handler

Thursday, June 26 2008 - , , - 4 comments

Just a quick code hit I’ve been meaning to blog about … I’ve seen a lot of examples that implement the  PropertyChanged event handler of the INotifyPropertyChanged interface. Most of them are demonstrating how to deal with data binding (including my examples) and most of them simply repeat the code that does the event raising. Some go as far as creating a method that does the raising, too.What I don’t like about the examples that extract a method that does the event raising is that each class would then need to have its own extracted method. Or you could (cringe) put it in a utility class.

Another solution is to create an extension method. But  sometimes the oldies are the best ways to do things. So here is an example I chose to use in a recent project. I had already created a base class for my entities and named it EntityBase.

I made the EntityBase implement the INotifyPropertyChanged interface and implemented its single event (PropertyChangedEventHandler) as a virtual event named PropertyChanged.

Then I created a method in the abstract base class named PropertyChangedHandler (the name is up to you) and its accepts an instance of EntityBase to be used as the sender and the name of the property that is changing.  (see the code below)

[DataContract]
public abstract class EntityBase : INotifyPropertyChanged    
{
    protected void PropertyChangedHandler(EntityBase sender, string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
    }
    public virtual event PropertyChangedEventHandler PropertyChanged;  
}

 

A class can inherit from the EntityBase (mine already did anyway) and override the event.

[DataContract]
public class Product : EntityBase
{
    public override event PropertyChangedEventHandler PropertyChanged;
...
...

 

Finally, here is an example of a property accessor that calls the base class’ protected method PropertyChanged.

[DataMember]
public string CategoryName
{
    get { return _categoryName; }
    set
    {
        _categoryName = value;
        base.PropertyChangedHandler(this, "CategoryName");
    }
}

 

The nice thing about this technique is that you just have a single line of code to execute the method in the base class that raises the notification. I wish I could have made the base class’ event abstract, but nothing is perfect.

You can omit the call to the base class in the code above, too. I just left in the word “base” to make it very clear in the example here.

If anyone else has any thoughts on better ways or just different ways to handle it, I am interested in hearing your thoughts.

How Many Ways Can One Misspell a Word?

Monday, June 23 2008 - - 0 comments

I am notorious for letting my thoughts get ahead of my typing. I’ll start typing something and the words will come flying out. usually I’ll start typing the next word before I finish with the previous word. That usually results in sentences like this:

Al lo fth ecoo lkid sus eSilverlight.

Translation == All of the cool kids use Silverlight.

Sometimes I will type several sentences without realizing it. The worst part is that I actually look at the screen while I type, so I am typing it wrong, seeing that it is wrong, yet it does not register that it is wrong until the entire thought is “on paper”.

Well, I discovered another bad side effect of this tick of mine. I seem to want to try to spell Silverlight in as many variations as possible. I’ll type Silverlight mostly, then I will throw in a few of Sivlerlight’s and Sliverlight’s. It is frustrating … maybe I just can’t figure out where to put the L.

OK, so now that one of my awkward behaviors is now publicly on display, perhaps I can finally kick these horrible habits. Sometimes the best way to stop from doing something is to raise your awareness to it, put it on center stage and be done with it. So I am giving myself notice, as of this moment I wil lneve rmispel la wor dtha tbadl yagain!

Darn it!

Silverlight 2 Binding Modes Diagram

Monday, June 23 2008 - , , , - 2 comments

Here’s a tiny little nugget from my upcoming book. There are always concepts that are just natively drilled into me yet they don’t flow smoothly when I try to explain them. For example take the Silverlight 2 binding modes. You have OneTime, OneWay and TwoWay as options. OneWay is the default and many examples of XAML based binding I see of XAML in both Silverlight and WPF omit the Mode property entirely. But OneTime is not always the appropriate option, either. Read only data is better suited for OneWay while editable data is suited well for TwoWay. Data that should only be bound and displayed when the source is first bound is ideal for OneTime.

There are nuisances to the scenarios, too (aren’t there always?). For example, OneWay and TwoWay bindings rely on the INotifyPropertyChanged interface and its PropertyChanged event being raised. 

OK, so my point is that sometimes explaining these types of situations is more difficult than just showing them with code. I;ve always been more about show me the code and sprinkle a little bit of explanation around it. To me that is so much easier to comprehend than reading a dozens of pages without code or pictures.

image

So I came up with a simple diagram for to help myself explain the binding modes a little bit. Its not the only tool I use (I use code samples, other diagrams, and words too) but its one I start with. I figured I would share it for any who might be interested. You can also find a variation of this diagram in my upcoming book Data Access with Silverlight 2 published by O’Reilly (Dec 2008).

SnagIt 9 Is Released and Ready for Download

Friday, June 20 2008 - , - 3 comments

TechSmith makes 2 of my favorite applications: SnagIt and Camtasia. SnagIt 9 was just released this week and it has some great new features. You can check out the full story on the new release and what’s new from this link. You can upgrade to SnagIt 9 by clicking on this link. This page also shows the differences between the features in SnagIt 8 and 9 in a chart.

I use SnagIt just about every day for grabbing screen captures of samples for presentations, articles, my book, sending images to clients, and for blogging. It plugs right into the Office suite of products and IE, too. I usually don;t extol the virtues of a product so blatantly, but I really love this tool. They are offering the product for $49.95 or you can upgrade to SnagIt 9 for $19.95.

Notice the new ribbon bar at the top, which is more Office 2007-like. It also tracks your recent captures on the bottom, which is quite handy.

image

Tutorial: Create a Silverlight 2 User Control from a Popup Control

Thursday, June 19 2008 - , - 2 comments

I created a simple user control using the Popup control as a starting point. The end result is a nice little user control that can be used as a popup control to display a message. It has only 1 button on it (an OK button that closes the popup control). I’ll outline the basic steps of creating the User Control and how the popup control works with it. Of course, you can create a popup control without the user control, but its a much cleaner practice to create user controls.

Step 1)  Create a tester control. I called mine PopupTester.xaml. It can contain just about anything you want, in my case I put a funky looking green filled border on the control and a button, that when clicked will call the user control that we’re about to create. You can skip the code for the event handler for the button for now.

The PopupTester control is the default control that will be loaded when the Silverlight application is started. (Set this in App.xaml.cs)

Here is how the PopupTester control looks in Expression Blend. (It has no background color, which is why it appears gray.)

image

Step 2)  Create a new User Control and name it MyPopupControl.  The complete XAML for the control is shown a little further down. Remove the background, width, and height from the Layout Grid control so it only has a name property of LayoutRoot..

Step 3)  Slap a Popup control in the main layout Grid. Name the popup control popMessage.

Step 4)  Create a Grid inside of the Popup control. Create 3 rows and 3 columns in the Grid. Make the 2nd row and the 2nd column (the middle ones) have a Width = Auto. This creates a nice little grid that we can use to center the popup control contents. There are other ways to do this, but let’s swing with it.

Step 5) Add a Border to the Grid inside of the Popup control. Style the border however you wish, but make sure you give it a background color of some sort so it gets filled in. I gave mine a gradient background color from top to bottom and set the opacity to make it slightly transparent.

Step 6) Next,  add a StackPanel inside of the Border, and stick a TextBlock and a Button inside of the Stackpanel. The TextBlock contain the message and the Button will be used to close the popup control. Name the TextBlock tbPopupMessage and the Button btnClose.

The XAML should look something like this:

<UserControl x:Class="SLPopupDemo.MyPopupControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot">
        <Popup x:Name="popMessage">
            <Grid x:Name="theBack" Background="#80000000">
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition Height="Auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Border BorderBrush="#7F4895DE" BorderThickness="1,1,1,1" Width="400" 
                    Height="200" Padding="10,10,10,10" CornerRadius="25,25,25,25" 
                    Grid.Column="1" Grid.Row="1">
                    <Border.Background>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                            <GradientStop Color="#FF000000"/>
                            <GradientStop Color="#CC4895DE" Offset="0.844"/>
                            <GradientStop Color="#FF346592" Offset="0.393"/>
                            <GradientStop Color="#FFFFFFFF" Offset="1"/>
                        </LinearGradientBrush>
                    </Border.Background>
                    <StackPanel Height="Auto" Width="Auto" Orientation="Vertical" >
                        <TextBlock  x:Name="tbPopupMessage" Height="143" Width="Auto" 
                            Text="Message Goes Here" FontFamily="Trebuchet MS" FontSize="24" 
                            HorizontalAlignment="Center" VerticalAlignment="Center" 
                            Foreground="#7FFFFFFF" TextWrapping="Wrap" TextAlignment="Center"/>
                        <Button x:Name="btnClosePopup" Height="30" Width="80" Content="Close"/>
                       </StackPanel>
                </Border>
            </Grid>
        </Popup>
    </Grid>
</UserControl>

 

Step 7) Now we need to ad some code to the MyPopupControl user control to create its event handlers. We’ll need events for the Button’s close event and to resize the control when the application resizes. So add the following constructor code to your code behind:

public MyPopupControl()
{
    // Required to initialize variables
    InitializeComponent();
    btnClosePopup.Click += new System.Windows.RoutedEventHandler(btnClosePopup_Click);
    App.Current.Host.Content.Resized += (s, e) =>
    {
        theBack.Width = App.Current.Host.Content.ActualWidth;
        theBack.Height = App.Current.Host.Content.ActualHeight;
    };
}

Using Visual Studio the event handlers are automatically created for the button. I used an anonymous delegate with lambda styling to for the resizing code just for fun. We could have simply created an event handler for it, though (like for the button). (Shawn WIldermuth inspired me to be creative with this technique after reading a post he wrote on creating a popup dialog, too. originally I had created an event handler for this, which is probably what I would od in a real application since I think its easier to debug & read.)

Step 8) Add the code to the button to close the popup control.

private void btnClosePopup_Click(object sender, System.Windows.RoutedEventArgs e)
{
    this.Close();
}

Step 9) Create a public property on the user control to get & set the Message in the control.

public string Message
{
    get { return tbPopupMessage.Text; }
    set { tbPopupMessage.Text = value; }
}

Step 10) Create a public method to open the control and one to close the control. 

public void Close()
{
    popMessage.IsOpen = false;
    this.Visibility = System.Windows.Visibility.Collapsed;
}
 
public void Show()
{
    popMessage.IsOpen = true;
    this.Visibility = System.Windows.Visibility.Visible;
    btnClosePopup.Focus();
}

The code in the Show method sets the IsOpen property of the popup control, which makes the control open up. We also toggle Visibility. The Close method does the opposite.

Step 11) Go to the XAML of the PopupTester control and add the MyPopupControl user control as the last element just before the layout Grid closes.

<SLPopupDemo:MyPopupControl x:Name="myPopup" Visibility="Collapsed"/>

Step 12) Once you add this XAML, you will have to add a reference to the namespace at the top of the user control, too, like this

xmlns:SLPopupDemo="clr-namespace:SLPopupDemo" 

Step 13) Go to the PopupTester control’s codebehind and add the following code.

public PopupTester()
{
    InitializeComponent();
    showButton.Click += new RoutedEventHandler(showButton_Click);
}
 
void showButton_Click(object sender, RoutedEventArgs e)
{
    myPopup.Show();
}

This code adds the event handler for the button that will open the MyPopupControl instance. The event handler simply calls the popup control’s Show method, that we created in the previous step.

Step 14) Now compile the app and run it. When you click on the button it the popup control will appear to be in front of the entire PopupTester control (because of its gray slightly transparent and stretched background. Like this:

image

No magic, just pretty simple code and layouts.

Here is the source code …. Enjoy!

Silverlight Presentations On the Horizon

Thursday, June 19 2008 - , , , - 2 comments

I am sitting down writing about WCF interaction with Silverlight, cross domain issues, and other fun communication stuff. As I am drumming through these examples for the book and for some articles and presentations (phew) I am running into minor issues that really cause me to think differently about how to tackle them. For example, I wanted to produce a model popup window in Silverlight. Sure, no problem, I’ll just use the … wait … there is no modal popup control. There is a popup control, but its not modal. And it lacks a bit of refinement. I see from my friend Mr Google that others have tackled this issue in various ways … such as …

- Creating an abstract class that derives from the ContentControl and implementing methods that render the popup

- Creating a popup control inline in code, and restricting keyboard and mouse movement beyond the popup control

For now, since I could not find an elegant solution that I could fall in love with, I decided to create a popup control in a user control and expose custom properties on the user control so I could tweak the popup control and simulate modality. The user control has a canvas that stretches out over the base Silverlight control with a 50% opacity. This simulates a graying out of the background when the popup control appears and prevents mouse interaction. It does not prevent tabbing back into the originating Silverlight application, but that;s next on my list.  It ain’t perfect, but it works good enough for now. I have to think that there will be an easier way to simulate modality in the future, at least by RTM.

Anyway … this and other issues like it got me to thinking that it might be a good thing to present some of these issues I am running into on my blog in narrative form like this post, in code samples, and in camtasia vdeos. I’ve got plenty to share … the only catch is finding the time between my main job, my speaking schedule, and my writing schedule and leave time for the family. The same ol’ battle :) But I think I will have some time to do some quick videos and postings on these topics so here’s my vow to share some of my Silverlight adventures, both successful and unsuccessful, in the coming weeks and months. The first will likely be on the modal popup that I described in this post. My hopes are that this sharing process will help refine some of these bumps in the road for Silverlight junkies like me.