Archive

Posts Tagged ‘Silverlight’

eBook Giveaway

October 29, 2012 Leave a comment

Congratulations to Thomas Griffin and Chris Bordeman for winning a free copy of MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF.

Hope enjoy the book!

Advertisements
Categories: English Tags: , , , , , ,

Win a free copy of Packt’s Silverlight book

October 9, 2012 3 comments

I am pleased to announce that I have teamed up with Packt Publishing and we are organizing a give away especially for you. All you need to do is just comment below the post and win a free copy of MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF. Two lucky winners stand a chance to win an e-copy of the book. Keep reading to find out how you can be one of the Lucky One’s.

Overview of MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF

  • Build an enterprise application using Silverlight and WPF, taking advantage of the powerful MVVM pattern.
  • Customize the MVVM pattern for your projects’ needs by comparing the various implementation styles.

Read more about this book and download free Sample Chapter: http://www.packtpub.com/mvvm-survival-guide-for-enterprise-architectures-in-silverlight-and-wpf/book

How to Enter?

All you need to do is head on over to this page and look through the product description of these books and drop a line via the comments below to let us know what interests you the most about these books. It’s that simple.

In one week, I will randomly select two lucky winners.

Categories: English Tags: , , , ,

MVVM Survival Guid for Enterprise Architectures in Silverlight and WPF

August 24, 2012 1 comment

I finished just reading this book and I thought I would do a review while it is still fresh in my head.  I believe the book has good content and is a great reference for building application architectures using Silverlight or WPF.

Chapter 1 takes us through the various Presentation Patterns.  We first are introduced with a brute force monolithic approach and then look at MVC and MVP while evaluating any issues or concerns.  Its primary focus is to demonstrate the power of these patterns and enforce separation of concern (SoC).

Chapter 2 introduces us to MVVM and the benefits it offers do to Silverlight and WPF’s rich data binding.  The user is presented with strategies for sharing code between both Silverlight and WPF.  I was surprised that there is no mention of Prism or Caliburn.Micro or any other framework besides MVVM Light.  I think that MVVM Light is a great framework but I don’t agree that Microsoft leaves you without any direction as was mentioned in the book when they have an excellent guidance using Prism.

Chapter 3 uses the Northwind database as the primary data storage throughout the book.  It uses Entity Framework and also introduces Unit Tests for testing.  We are exposed to a new pattern, “Service Locator Pattern” and how it interacts with View and ViewModel.

Chapter 4 goes a step further with our Northwind database and discusses services and persistence ignorance.  It basically follows the best practices as established by Martin Fowler with regards to using a “Service Layer” to remove tight coupling.  Transaction Script, Domain-Driven Design, and Service-Oriented Architecture and presented in this chapter as well.  We then look at persistence ignorance and custom models and the pros and cons for each.

Chapter 5 is all about Commands and User Input dealing with the Northwind database.  It does a good job of demonstrating the commanding API supported in both Silverlight and WPF.  It also deals with InputBindings such as KeyBinding and MouseBinding.  We then discuss attached behaviors.  I did not see any true behaviors or actions that are also supported by both Silverilght and WPF.  Neither did I see any examples of EventAggregation which is very important when trying to communicated across projects or classes.

Chapter 6 handles hierarchical view models and inversion of control.  We are presented with master/detail scenarios and also take a look at the ObservableCollection<> object.  With IoC, we are presented again the Service Locator pattern.  Next we are presented with StructureMap.  I am again surprised in that we are not presented with Unity or MEF as these two come straight from Microsoft.  I would also like to have seen others like Ninject but we are at least presented with IoC best practices.  I do like that they introduce the Single Responsibility Principle (SRP) and give the reader a good idea of how it works works and how to use it.

Chapter 7 is all about dialogs and MVVM.  Dialogs can be a tricky part of an application architecture in that it is easy to break all the hard work we established by using MVVM.  We are presented three options for using dialogs:  Dialog Service, Mediators, and Attached behaviors.  With dialog services, we are presented with data templates and the flexibility they provide as well as some common conventions to give us one of my favorite patterns, convention over configuration.  With mediators, we are finally introduced Event Aggregation and Messaging.  Finally with attached behaviors we see a way to controls dialogs via XAML.

Chapter 8 this chapter is a nice surprise in that it discusses Windows Work Flow and building MVVM applications.  We discuss several patterns in this chapter, “Unity of Work” and “Memento“.  Next we are shown how these patterns are supported and implemented using WF and how they support handling application flow.

Chapter 9 is all about validation and error handling.  IDataErrorInfo, INotifyDataErrorInfo, and ValidationSummary are a few of the objects presented in this chapter.  We also discuss the Enterprise Library Validation Application Block and how it interacts with both WPF and Silverilght.

Chapter 10 talks about using non MVVM third party controls.  It deals with strategies for incorporating controls such as the WebBrowser control and still achieve rich data binding using MVVM with these controls.  We look again at the power of attached behaviors and a technique such as exposing a binding reflector to help with our data binding.  Another technique is to use the adapter pattern and leverage inheritance to expose and surface the functionality we want to support MVVM as well.

Chapter 11 focus on MVVM and application performance.  For WPF applications, we look asynchronous bindings.  Another area of performance concerns with controls is the concept of virtualization and paging.  Not a lot is addressed here but at least the concepts are presented.  The BackgroundWorker object is presented to facilitate work being done on a separate thread.

Appendix A claims to evaluate other MVVM libraries but I only see a list and not much discussion as to the power or differences among them.

Appendix B is titled “Bindings at a Glance” but I really only see a glossary of terms and now real good examples of bindings or real-world examples.

All in all, this seems to be a good book.  It doesn’t answer all the questions but it does present you with enough information to give you a good direction as to where you need to go when building out your own architectures.

Microsoft Silverlight 5 Data and Services Cookbook

I wanted to continue on reviewing books related to Silverlight 5 and development.  Microsoft Silverlight 5 Data and Services Cookbook states that it has over 100 practical recipes for creating rich, data-driven, business applications in Silverlight 5.  As with my last review, I will go over each chapter and add any gut reactions towards the content it provides.

The book is broken down into 13 chapters as well as an appendix.  On the whole, the book has a lot of content to absorb.  It is broken down into a collection of tips and tricks and common scenarios for using Silverlight in building line of business applications.  I like the concept and idea behind the approach to this book but I find that a lot of corners were cut in getting the book out the door.  I wish that the book had a better quality of code snippets as well as accompanying images as the code samples lack syntax highlighting of any sort and the images are very poor in quality.

Chapter 1 is all about learning the nuts and bolts of Silverlight 5.  This chapter is necessary if you have never written a Silverlight application and need to understand what is required in order to get started using Visual Studio 2010.

Chapter 2 jumps right into covering Data Binding.  This is also a core concept to any XAML technology and I like that they cover it soon so as to get you exposed to the whole data binding programming paradigm.  You are exposed to the classical non-data binding approach and then launch into the concept of a DataContext and how the data binding mechanism works.  We exposed how to create bindings both in XAML as well as in code which is sometimes necessary.  Binding to other elements, and collections is also discussed.  Next, is introduced the interface, INotifyPropertyChanged.  This is by far one of the most important aspects of XAML programming as it facilitates two-way data binding.  We finally come to one of the first instances of a new feature of Silverlight 5, debugging data binding expression.  This is one of the coolest features of Silverlight 5 and makes developing in Silverlight 5 a joy.

Chapter 3 takes our knowledge that we learned from data binding and goes into some advanced topics.  Namely, we are presented with converters, data templates, validating.  Converters are required in most line of business applications as your data binding alone will not satisfy all of your business logic and requirements.  We are also presented TargetNullValue, StringFormat, and FallbackValue as alternatives for using converters.  Another important part of any line of business application is validating user input.  We are presented with NotifyOnValidationError and ValidatesOnExceptions.  In the UI, we are introduced the ValidationSummary control that will automatically receive any BindingValidationError events.  This is nice in that we can present all errors in one concerted location and effort back to the user.  Data Annotations are presented as a means for providing validation rules on your domain objects.  INotifyDataErrorInfo and IDataErrorInfo interfaces are introduced to show how you can validate user input without throwing exceptions.  We finally move away from validation and review data templates.  This is an important concept with any XAML technology and we find good examples of usage here.  With Silverlight 5, we get the ability to use implicit templates and this is covered as well.  For scenarios where we need to binding something different than our current element in the visual tree, we are presented with Ancestor RelativeSource binding now available in Silverlight 5.  Another powerful feature of Silverlight 5 is the ability to create custom markup extensions.  Finally, as with INotifyPropertyChanged works on a single object, we are presented with the INotifyCollectionChanged interface for dealing with change aware collections.

Chapter 4 is completed dedicated to the Data Grid.  The one aspect that I was curious about was how they demonstrated binding combo boxes to the a column in the data grid.  The sample was very primitive and would not be something you would really be able to use in most data driven scenarios.  I am hoping that as we move to MVVM, we will see better scenarios on this.

Chapter 5 is about Isolated Storage.  This chapter does a good job on covering Isolated Storage and the limitations of Silverlight applications and their security sandbox.  I also liked that they also showed how you could use the Sterling database.

Chapter 6 covers MVVM.  The chapters covers the basics of MVVM as well as introducing MVVM Light and MEF as tools to use with MVVM.  I would have like an introduction on Prism and Caliburn.Micro as well as these are two important frameworks and libraries.  With Caliburn.Micro, they could have provided a nice introduction to architecting rich user interfaces without explicit data binding in your XAML.

Chapter 7 covers services.  Most all line of business applications will require data and since you cannot create a direct connection to the database in Silveright, you will need to access a service.  You presented with services such as ASMX, WCF, REST, and RSS.  I also liked that they also had a section on socket communication in Silverlight as well.  The one complaint I have is that I wished they would have also introduced SignalR as section as this is gaining a lot of popularity in the .NET community.

Chapter 8 takes what we were introduced in the previous chapter and focuses strictly on WCF and ASMX services.  We are exposed with using services that expose data, using Bing as a service.  We get presented with performance tuning by using binary XML.  We also cover a personal favorite of mine, the infamous, “Server Not Found” exception and how to provide more information to the Silverlight client.  Integrating with ASP.NET Authentication is also covered.  Finally, we are presented with uploading files using WCF.

Chapter 9 takes us one step further in our discovery with ASMX and WCF.  Mainly, we cover duplex communication, data encryption, message-based security, using Windows Identity Foundation and, finally, using a ChannelFactory with Silverlight.  Most of these sections are very high level and don’t go any further than a quick sample.  It at least points you in the right direction for further investigation.

Chapter 10 talks about using REST and WCF Data Services.  With REST we cover both XML and JSON formats.  Another sections discusses the limitations to the Silverlight browser stack.  We are then presented with the ClientHttp stack and how we can use the common REST verbs.  Next, we are presented with using WCF Data Services.  We also get presented with Flickr and Twitter and how to use their REST services.

Chapter 11 is dedicated to presenting WCF RIA Services.  While I am not a big fan of WCF RIA Services this chapter does a good job at showing you what you can do with WCF RIA Services.  It walks you through using the class library, getting your data, using a LoadBehavior, server-side queries, sorting, filtering, paging, and finally persisting your data and dealing with transactions and concurrency.

Chapter 12 continues on the WCF RIA Services and shows us some advanced features.  We are shown how to get a user’s identity either by Windows authentication or a custom means.  Next, we are presented with using Windows Identity Foundation and WCF RIA Services.    We then move from authentication to authorization in our services.  We also review how WCF RIA Services supports data annotations and validating user input.  Finally, we are presented with exposing our data via OData endpoints as well as SOAP or a JSON/REST endpoint.

Chapter 13 introduces Windows Phone 7.  This chapter walks you through the WP7 architecture from a developer’s perspective and then concentrates on getting data to the device.  A lot of the same patterns presented in the previous chapters are applicable.  Using push notifications with the cloud is demonstrated.  Local storage using a SQL CE database is presented.  Finally, a sample on using background transfer service is covered for uploading and downloading files in the background.

Appendix.  The appendix walks you through how to find any of the dependencies mentioned in the book.

If you are looking for a book that covers a lot of scenarios in Silverlight concerning data and services than this seems like a good reference for you to have.  At times, I feel that the samples were overly verbose and cluttered but I believe this is more to be the fault of poor publishing.  It would have been nice to have a better rendering of the code snippets and a better quality of the sample images throughout the book.  All in all, I found the book to be a good reference and it will definitely go in my toolbox as a go to book when I am working on a particular scenario.

Mastering LOB Development for Silverlight 5: A Case Study in Action

May 11, 2012 1 comment

I recently picked up a copy of the Mastering LOB Development for Silverlight 5: A Case Study in Action and started going through the book.

If you have never done any development in Silverlight and would like a practical pragmatic example of how to setup your solutions in Visual Studio as well as get exposed to the different frameworks that are available, then this is an excellent choice! The book is broken up into eleven chapters and it starts from introducing you to the basics of developing in XAML and quickly builds upon this knowledge to lead you into understanding windows and controls.

Chapter 3 is about data binding but it doesn’t stress the need for separation of concerns enough. I would have rather seen examples done the right way instead of the easy way. There were no advanced examples of attached properties or use of the System.Windows.Interactivity. The title of this book implies that we will be covering Silverlight 5 but I don’t see a single mention of debugging data bindings which is brand new to Silverlight 5 nor is there any hint of ancestor relative binding, implicit data templates, custom markup extensions, etc.

Chapter 4 is on Architecture but it too is lacking in being truly comprehensive. There is no sign of Prism 4.0 nor is there any mention to Caliburn.Micro. Both of the frameworks are very powerful and more mature than either of the frameworks mentioned in the book. Although both MVVM Light Toolkit is a good tool but MEF is more of a tool for DI/IOC and not a full fledged framework that can handle messaging like event aggregation that the other frameworks provide. Another sad aspect is that there is no mention of compartmentalizing your architecture to only download XAPs on demand. Most Silverlight frameworks support this out of the box.

Chapter 5 talks about data access. The chapter focuses on RIA Services but I find it very problematic that it does not cover any authorization or authentication. It does go into good detail about using RIA Services in conjunction with Entity Framework. However, I have spent way too much time fighting RIA Services to know that it is not appropriate for enterprise level development except for smaller line of business applications. The other common issue I have with this chapter is that it doesn’t address the common scenario of “Server Not Found“. This happens when RIA Services has an exception on the server and this will happen a lot. There are techniques to solve this and it is important for you as the developer to know this.

Chapter 6 discusses Out of Browser applications and this is for the most part has good coverage of the topic.

Chapter 7 is on Testing. This is a good chapter as well but it is unfortunate that it took us until this chapter to get a mention of DI/IOC. Dependency injection and inversion of control is just as important in your architecture and design as it is in your testing projects. I wish they would have covered some of the behavior driven development libraries that are available to you such as SpecFlow. BDD really compliments and makes your development experience so much better.

Chapter 8 is on Error Control. It covers the basics but still doesn’t address how to deal with exceptions on the server.

Chapter 9 is on Integrating with other Web Applications. I personally don’t see this as an important chapter for a book on line of business applications. I would much rather have a consistent architecture and UI instead of dealing with mashups.

Chapter 10 is on Consuming Web Services. This chapter covers the basics but doesn’t go deep as learning WCF requires a book just for itself. I did like that they cover consuming a Twitter API and processing JSON.

Chapter 11 is on Security. It is here that we see our authentication and authorization for both RIA Service and WCF. We also look at what how to make cross domain calls.

This book is a great reference for building line of business applications. Although I believe that it is missing some fundamental topics in building a line of business application and is a little weak on the coverage for Silverlight 5, it is still a very good read and you will walk away armed with good knowledge for building line of business applications.

Hope the review helps…

Silverlight 5: Building Rich Enterprise Dashboards

February 15, 2012 1 comment

I am very happy to announce that the book that I co-authored has been published and is now available for purchase on Amazon!

Here is a link to my publisher:

PactPub

Here is the link on Amazon:

Amazon

I have been busy these past several months but it has been worth it!

Categories: English Tags: , , ,

Gofer – Silverlight

January 4, 2012 9 comments

In our last post, we used Gofer in a Console application and got data from a SQL Server database as well as creating the database from our domain model. Today, we are going to be doing the same thing but we will be doing this with Silverlight.

First, start by create a new Silverlight 5 application.

Make sure that you do NOT enable WCF RIA Services!

Next, we are going to setup of the web project first and then move over to the Silverlight project once we are done. Let’s start with getting Gofer from NuGet. Right-click on your References folder and select Manage NuGet Packages. Next, type in “Gofer” as your search criteria. Select Gofer.Sample as your choice. This package comes with the Gofer library as well as with some helper files to make testing this easier.

Gofer.Sample has a dependency on SwitchBlade and ValueInjecter.

SwitchBlade is another package that I wrote that allows you to host Razor templates outside of ASP.NET and IIS. I will be covering SwitchBlade in a future post.

ValueInjecter is a package like AutoMapper but much more convention-based and easier.

We are also going to need to use Ninject as our DI/IOC container. We will use NuGet to install this package as well:

Finally, we will need the WCF Web API from NuGet as well:

Moving on from adding all of our packages, you will also notice that you have two new template folders for your CRUD and DDL operations. You can modify these templates to shape how you want your SQL code to look when it is used by Gofer.

You will also notice two new files:

Domain.cs – This file represents a sample domain model. It is very similar to what you would see from a Northwind with some slight modifications.

TestDriver.cs – This file is a test driver class that allows us to test Gofer. We will be using a Silverlight version of this file instead. DELETE this file from the project as we do not need it.

Next, let’s add a Global.asax file to the project and modify as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Web.Routing;
using Microsoft.ApplicationServer.Http;
using Ninject;
using Domain;
using Gofer;

namespace GoferSilverlight.Web
{
    public class Global : System.Web.HttpApplication
    {
        public const string NAMESPACE = "Domain";
        public Func<Type,bool> PREDICATE = x => x.Namespace == NAMESPACE;

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.SetDefaultHttpConfiguration(new WebApiConfiguration()
            {
                CreateInstance = (serviceType, context, request) => CreateInstance(serviceType),
                EnableTestClient = true
            });

            RouteTable.Routes.MapServiceRouteForAssemblyOf<Customers>(PREDICATE);
        }

        private object CreateInstance(Type serviceType)
        {
            object result = null;
            IKernel kernel = new StandardKernel();
            try
            {
                // The following is a sample entry for using the MapServiceRoute method:
                // RouteTable.Routes.MapServiceRoute<GoferService<Customers>>("Customer");
                // Hence the reason we need to pull the generic type from the GoferService.
                var genericType = serviceType.GetGenericArguments().FirstOrDefault();
                SchemaRules rules = GetRules(genericType);
                kernel.Bind(serviceType).ToSelf().WithConstructorArgument("rules", rules);
                result = kernel.Get(serviceType);
            }
            catch { }

            return result;
        }

        #region Rules

        private SchemaRules GetRules(Type type)
        {
            var result = new SchemaRules();
            result.AssemblyOf(type)
                .ShouldMap(PREDICATE)
                .GetSchema();

            result.PerformMigration = true;
            result.ForceNewMigration = false;

            return result;
        }

        #endregion

    };
}

UPDATE: I added a Fun<Type,bool> predicate so you could easily add your own logic for both the “RouteTable.Routes.MapServiceRouteForAssemblyOf<Customers>(PREDICATE)” and the .ShouldMap(PREDICATE) calls.

If you are curious as to what is going on here, please refer to my post Building a Generic Service using WCF Web API – Part II as it walks you through all of these steps.

One thing to point out here is that we are using the same SchemaRules class.

SchemaRules – This tells the Gofer engine what conventions to use for its data access. There is a ton that you can override with this class and we will take a look at that in a later post but this is the bare minimum that you need to get going. Also, you will see two properties that tell the engine whether or not to perform a migration as well as force the migration, meaning that it will drop the database and recreate it if necessary.

There is one last change that you need to put in place before we can test our service. We will need to modify the Web.config. The following is a sample Web.config that you can pattern against for yourself:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="DB_NAME" value="Example" />

    <add key="DDL_ConnectionString" value="Provider=SQLOLEDB;Server=(local);Database=master;Integrated Security=SSPI;" />
    <add key="DDL_DatabaseType" value="4" />

    <add key="ConnectionString" value="Data Source=(local);Initial Catalog=Example;Integrated Security=SSPI;" />
    <add key="DatabaseType" value="3" />

    <add key="TemplatePath" value="C:\Users\Matt\Documents\visual studio 2010\Projects\GoferSilverlight\GoferSilverlight.Web\CRUD_Templates" />
    <add key="DDL_TemplatePath" value="C:\Users\Matt\Documents\visual studio 2010\Projects\GoferSilverlight\GoferSilverlight.Web\DDL_Templates" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration>

If we run the application, you will see a blank screen but we can still test our service:

I am using the database that I tested with the previous post. Therefore, I knew I had at least one record in the Customers table. Based on the results of the service, I can see that I am getting back a good JSON response.

Ok, our service is ready, now let’s shift gears and see what we must do to test this on the Silverlight side.

We want to share our domain for both the client and server. Right-click your Silverlight project and select “Add | Existing Item…”. Navigate to the web project and select the Domain.cs file and click the down arrow to “Add As Link”. This will give us the domain model definition in our Silverlight project.

Next, let’s add our Gofer.Silverlight package from NuGet. Right-click on the References folder and select Manage NuGet Packages. Next, type in “Gofer” as your search criteria. Select Gofer.Silverlight as your choice.

Gofer.Silverlight has a dependency on Async CTP and HTTP Contrib which are provided as part of the install.

Async CTP is a library that helps make asynchronous programming easier.

Http Contrib is a library that helps make calling the WCF Web API easier from clients such as Silverlight.

You will also notice that a “readme.txt” file added to the project. If you open the file, you will see the you need to add the following code snippet to the constructor of your App.xaml.cs file:

HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
HttpWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

I wrote a blog post here when I ran into some strange issues trying to test my services for PUT and DELETE behaviors.

Okay, let’s add the following TestDriver.cs class to the Silverlight project:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Gofer.DataAccess;
using Domain;

namespace GoferSilverlight
{
    public class TestDriver
    {
        public void Run()
        {
            var repo = new SilverlightRepository("Customers");
            var cust = new Customers()
            {
                CompanyName = "Bubba's Repair",
                ContactName = "Billy Bob",
                ContactTitle = "Owner",
                Address = "100 Pecan Street",
                City = "Columbia",
                PostalCode = "29661",
                Country = "USA",
                Phone = "(803) 836-1212",
                Fax = "(803) 836-1213"
            };
            repo.Create<Customers>(cust,
                (item) =>
                {
                    if (item == null)
                    {
                        // Handle data here....
                    }
                },
                (error) =>
                {
                    if (error == null)
                    {
                        // Handle error here....
                    }
                }
            );            
        }
    };
}

As you can see, this is very similar to what we used in the Console application but all calls are asynchronous and I also wanted to have a unique callback for success and errors. If the database did not exist, you could run this just like the Console code and a new database would be created as long as you had the PerformMigration property set to “true” in your Global.asax.cs file.

The final step to get this to work is to add the following code to the constructor of your MainPage.xaml.cs file:

TestDriver td = new TestDriver();
td.Run();

If you add a couple breakpoints as shown below, you should be ready to run the application:

When the debugger hits your breakpoint, you should see something similar to the following:

That’s it! This may seem like a lot of moving pieces to get this working but once you get in the groove, you will see that this is so much easier than dealing with proxies and hidden code generated files from Visual Studio. I personally really like this approach and I look forward to getting your response as well.

In the next couple of posts, I will be digging deeper into to Gofer as a whole to show you everything that you can do.