Tuesday, March 6, 2012

A survey & comparison of SSO solutions

This post provides a brief survey of existing SSO solutions including Ping Identity's PingFederate, Microsoft's Azure Access Control Service, CA CloudMinder Single Sign-On, and Intel Cloud SSO (beta).

Note: Most information used in this posted are originated from the publicly available reference materials listed in “References” section and my personal evaluation of the products. If you found me misinterpreting these materials, or if I’ve missed some supported features (i.e. the ones marked with question marks), please let me know via comments! I’ll update the post accordingly. 

API Security

As more and more services are orchestrated under SOA, more and more services are consumed by other services instead of directly invoked by human actions. Supporting API security is a very important feature for a SSO solution to succeed on cloud.

 

RESTful

STS

AD

Certificate

Form

SDK

CA ? ? ? ? ? Yes
Intel* ESG* ESG* ESG* ESG* Yes ?
Microsoft OAuth ws-Trust ADFS x.509 Yes Yes
Ping* OAuth ws-Trust LDAP x.509 ? Yes

*Both Intel and Ping provide out-of-box support of a list of popular cloud-based services such as Force.com, Google Apps, and Office 365.

*It seems API security is supported by Intel via a different product, Expressway Service Gateway.

In addition, both Microsoft and Ping Identity provides extensive support of claim-based architecture via Microsoft WIF. Claim-based architecture with WIF shields service providers from most complicities of authentication and authorization while providing maximum flexibility to federate with one ore more trusted identity providers. In my opinion, this is THE way authentication/authorization should be done for most service providers.

Automated Provisioning

There are two types of automatic provisioning: JIT provisioning or SaaS provisioning.

In a JIT (Just-in-time) provisioning solution, a service provider automatically provisions/updates a user based on incoming assertions. Note in this model, there’s an explicit trust of the IdP from SP, but the IdP can remain agnostic to the SP (of course an explicit trust may exist at security protocol level).

On the other hand, in a SaaS provisioning solution, identities are replicated from trusted IdPs to SP’s local user store so that the SP can authenticate users just as it commonly does without knowing the IdP. Note that in this model, an explicit replication exists between the IdP and the SP, but SP can remain agnostic to the IdP.

 

JIT Provisioning

SaaS Provisioning

CA FedMinder+IdentityMinder ?
Intel ? Through ECA 360 integration
Microsoft None None
Ping Identity PingFederate PingFederate+PingConnect

 

Multi-factor Authentication

Mutli-factor authentication, as the name suggests, requires users to log in using more than one set of credentials. A popular multi-factor authentication technique is the usage of software OTP (one time password) in addition to existing authentication mechanisms. OTP is usually delivered via specialized hardware, or via applications that run on mobile devices such as smart phones.

 

Built-in support

OTP

Mobile devices

CA Yes CA ArcotOTP Yes
Intel Yes Chip support Yes (Nordic)
Microsoft No* No N/A
Ping ? ? ?
*Note no built-in support doesn’t mean multifactor authentication is impossible. For instance, if an IdP requires multifactor authentication it can happen as usual.

Centralized Management

Centralized provides an unified view of identities across multiple identity providers as well as identify usages across multiple service providers. Common functionalities of such portals include user provisioning, profile management, trust configuration, usage monitoring etc. Some portals (such as IdentityMinder) provides additional workflow integration such as supporting access request-approval.

On the other hand, some solutions provides self-service model, where user can perform some identity management tasks, such as re

 

User Management Online Portal

Self-service Portal

CA IdentityMinder ?
Intel Cloud SSO Portal ?
Microsoft Azure Portal* ?
Ping ? ?

*Azure portal emphasize on federation management  instead of user management.

Monitoring, Auditing and Compliance

 

 

Auditing/Logging

Compliance enforcement

Other

CA ? ? Risk management with RiskMinder
Intel ? Cloud SSO Portal?  
Microsoft WIF tracing ?  
Ping CEF
ArcSight’s ETRM
Database
?  

 

Hosting

One of important feature of a robust SSO solution is high availability. Obviously loosing the authentication/authorization service renders all relying services unavailable. And for a multi-tenant solution, it has to be able to handle workloads from all connected parties so it doesn’t become a performance bottleneck.

 

On-premise

On-cloud

CA CA products Hosted by CA
Intel Intel ECA 360 Hosted by Salesforce?
Microsoft Local STS Hosted by Microsoft
Ping PingFederate ?

 

Other

Some characteristics are shared among all surveyed providers, including embracing industrial standards such as SAML and ws-Federation, extensibility, and mobile support. This post doesn’t compare these aspects in future details.

References

Saturday, March 3, 2012

Dependency Injection with ASP.Net MVC 4 ApiController

The solution presented in this post is based on this stackoverflow post.

Let’s say you have a dependency in your ASP.Net MVC 4 ApiController that you wish to resolve using Unity framework:

[Dependency]
public IHelloService HelloService { get; set; }
You may be surprised to find out that the dependency is not resolved, though you’ve set up the container and mappings correctly. The reason, quote from the post above, is because “For ApiControllers, MVC 4 uses a System.Web.Http.Dispatcher.IHttpControllerFactory and System.Web.Http.Dispatcher.IHttpControllerActivator to create the controllers. There is no static method to register what the implementation of these they are; when they are resolved, the mvc framework looks for the implementations in the dependency resolver, and if they are not found, uses the default implementations.”

To solve this, what you need to do is:

  1. Implement IServiceLocator in your dependency resolver implementation. The following is a simple example of GetInstance() implementation.
    public object GetInstance(Type serviceType)
    {
        try
        {
             if (mContainer.IsRegistered(serviceType))
                return mContainer.Resolve(serviceType);
             else
                return null;
        }
        catch (Exception ex)
        {
             return null;
        }
    }
  2. As proposed in the above post, provide an implementation of IHttpControllerActivator
    public class HttpControllerActivator : IHttpControllerActivator
    {
        private IUnityContainer mContainer;
        public HttpControllerActivator(IUnityContainer container)
        {
             mContainer = container;
        }
        public IHttpController Create(HttpControllerContext controllerContext, Type controllerType)
        {
            return (IHttpController)mContainer.Resolve(controllerType);
        }
    }
  3. Initialize Unity container as well as register the activator in Application_Start() event:
    protected void Application_Start()
    {
        ....
        var container = initContainer(); 
        System.Web.Http.GlobalConfiguration.Configuration.
        ServiceResolver.SetResolver(new RepositoryResolver(container));       
    }
    private static IUnityContainer initContainer()
    {
        var container = new UnityContainer();  
        container.RegisterType<IHelloService, HelloService>();
        container.RegisterInstance<IHttpControllerActivator>(new HttpControllerActivator(container));
        return container;
    }

Saturday, February 25, 2012

C# Expression Clock

This is what happens when I have half an hour free time at hand. This is also an experiment how far I can spread this image around. I’ll keep a log on what happens to this post. And if you the viewer happens to see this image posted somewhere else, please comment!

 

image

Friday, February 17, 2012

Amazon experience for .Net developers

Recently I took on a task to migrate an existing ASP.Net MVC 3 application to both Azure and Amazon. The application is a typical web application with ASP.Net frontend and a SQL Server database. Obviously before the migration I was expecting smooth experience with Windows Azure. The main propose of the experiment was to compare developer experience/productivity when developing to Amazon. This blog entry records some of the steps, tools, and findings during this process.

Tools

I used Visual Studio 2010 Ultimate version throughout the process. Here’s a side-by-side comparison of other tools used:

  Azure Amazon
.Net SDK Windows Azure SDK 1.6 AWS Toolkit for Visual Studio
DB Migration SQL Azure Migration Wizard v3.8.4 SQL Azure Migration Wizard v3.8.4

*I didn’t attempt to migrate my SQL Server database to Amazon RDS because I didn’t want to make any code changes, nor did I find a migration tool from SQL Server to RDS (there were tools for MySQL and Oracle). Instead, I created a separate EC2 image with SQL Server Express and used the same SQL Azure Migration Wizard to migrate my local database to the EC2 instance.

Migrate Database (to SQL Azure and Amazon)

The experience with SQL Azure Migration Wizard was a blast. I picked my local server as source, SQL Azure server/EC2 server instance as my target, and several clicks later everything was migrated with no problem – schema, tables, views, user roles – everything.

Note: SQL Azure requires all tables to have clustered indexes.

Amazon SQL Server hosting is provided by a series Amazon Machine Images (AMI). I launched a separate image from  “Microsoft Windows Server 2008 R2 with SQL Server Express and IIS” to be my SQL Server host, because AWS Toolkit for Visual Studio only allowed me to choose from two predefined images that don’t have SQL Server on them. After I launched the instance, I had to a number of things:

  • Changed my security group to allow inbound traffic on port 1433.
  • Changed SQL Service to auto start. By default the service start mode was set to “Manual” and the service was not started.
  • Enabled TCP/IP protocol for SQL Server. By default it was disabled. I configured the port to be fixed to 1433.
  • Punched a hole to allow port 1433 on the machines’ firewall.

After that, I used the same SQL Azure Migration Wizard and ported all database objects over without issues.

Deploy ASP.Net to Azure

To migrate my existing ASP.Net project, I added an empty Windows Azure project, and then added my ASP.Net project as its web role. Right-clicked, deployed, no problem.

Deploy ASP.Net to Amazon

The AWS Toolkit for Visual Studio worked great. After installed the toolkit, all I needed to do was to right-click on my existing ASP.Net project, select “Build Deployment Package”, then right-click again, and select “Publish to AWS CloudFormation…”. Unbelievable pleasant experience.

Conclusion

Overall the Amazon experience was very good. The Visual Studio plugin worked flawlessly. The deployment and update was very fast – much faster than Azure deployment. The database part was rough. I had to jump through some hoops to get it working.

On the other hand, if your solutions will contain multiple web roles and worker rows it may become ugly, because the Visual Studio plugin basically deploys a single web role only. Also, if you’d still like to consume Azure services such as ACS and ESB, you’d better deploy to Azure since it doesn’t make much sense to use two cloud platforms in one project at the same time. In my case I keep my security to be handled on Azure ACS while I am running the app on Amazon (for experiment only, of course).

Appendix – Side-by-Side comparison of provided Services (Feb 2012)

*rows are sorted by Amazon service names.     *Accuracy is not guaranteed.

  Azure Amazon
Virtual Image VM Role (Windows)
Startup Tasks
RDC
CloudFormation (Windows, Linux)
RDC
Content delivery network Azure CDN CloudFront
Resource monitoring (third-party solutions available) CloudWatch
Non-SQL DB Table Storage DynamoDB
Caching Caching block ElastiCache
Application hosting (Web) Roles
(.Net, PHP, Node.js)
Elastic Beanstalk
(Java applications)
Map-reduce (Queue + Worker roles + maybe WF to achieve similar goals) Elastic MapReduce
Identity ACS IAM
Relational DB SQL Azure
(SQL Server)
RDS
(MySQL, Oracle)
DNS service ? Route 53
Massive storage Blob Storage S3
Send e-Mail third-party email service such as SendGrid or AuthSMTP SES
Push notification Windows Push Notification Service SNS
Message Queue Queue Storage
Service Bus Messaging
SQS
On-premise connection Azure Connect
Storage Gateway
(data integration/backup only)
Business Analytics SQL Azure Reporting ?
Connectivity Service Bus Connectivity ?
Virtual Network Azure Connect VPC
Load balancing/routing Traffic Manager Route 53?
High performance computing HPC cluster HPC cluster
Service marketplace Windows Azure Marketplace ?

Friday, February 10, 2012

Make Silverlight DatePicker to display selected date – the XAML way

 

Goal

Microsoft Silverlight SDK provides a rich set of UI controls, among which is the DatePicker control. One little annoyance of this control is that it always show “15” on the dropdown button:

image

Frankly I never noticed it until some of my customers complained about it and told me that was “very confusing”. Well, let’s fix it, shall we? In this post I’ll demonstrate how to customize DatePicker appearance so it will display selected date on its dropdown button, and everything is done in XAML markups.

Steps

 

1. Get a template for DatePicker

To customize the appearance of the control, we need to get to its template. Of course you can write one yourself, but that’s a LOT of work to get it perfect. Fortunately we don’t need to start from scratch. You can download prebuilt Silverlight themes from Microsoft here. Download SL4Themes-RawAssets.zip and extract the files somewhere.

The package contains a number of different themes. Here I’m picking JetPack because it has the cleanest style definitions. If you want to use a different theme the steps below will NOT apply directly to you, but you can still skip through the article to get some general ideas.

Now, after applying the templates, you should see your DatePicker having a new look. And the default “15” changes to “16” – quite an improvement!

image

2. Dive into the template

Now open the SDKStyles.xaml. There are two templates are of our interests: “DateDropDownButtonTemplate” and the one with TargetType set to “sdk:DatePicker". The first template is the template for the dropdown button, while the second one is the overall style. Expand “DateDropDownButtonTemplate”, and you’ll see where the text “16” is displayed:

<TextBlock Text="16" FontSize="14" Foreground="#FF292D2F" FontWeight="Bold" FontFamily="Arial" Margin="0,6,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" />

Instead of hard-coded “16”, we’d like to bind it to “SelectedDate” property of the control. Unfortunately the TextBlock is two levels down from the root control and Silverlight doesn’t support FindAncestor. So, we have to do a double-hop – first we bind this text to its template parent – the dropdown button; then we’ll bind the button content to SelectedDate property of its data context. The first binding change is easy:

<TextBlock x:Name="CoolTextBox" Text="{TemplateBinding Content}" FontSize="14" Foreground="#FF292D2F" FontWeight="Bold" FontFamily="Arial" Margin="0,6,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" />
                                      

The second binding change happens in the main template. Look for a Button with name “Button” – this is the dropdown button. Add a Content binding to it:

<Button x:Name="Button" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" 
 Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedDate, Converter={StaticResource DateToDayStringConverter}}"
Foreground="{TemplateBinding Foreground}" Grid.Column="1" Margin="4,2,2,0" Template="{StaticResource DropDownButtonTemplate}" Width="26" />

Notice we have to use a value converter here because SelectedDate is a nullable property, we can’t directly bind to it. The converter is very easy to write, as I’ll show it next.

3. Value converter

Add a new class to your project named DateToDayStringConverter.cs with the following code:

public class DateToDayStringConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DateTime? date = (DateTime?)value;
        return date.HasValue ? date.Value.Day.ToString() : "16";
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Very simple code. it checks the nullable DateTime value and display the day as a string (it defaults to “16” for a null value, but of course you can pick other texts).

Now add the converter reference to SDKStyles.xaml, recompile and you’ll have a DatePicker that shows selected date in its dropdown button!

image

Friday, December 16, 2011

Tutorial: knockoutjs MVVM for XAML programmers – sprint 1

The goal of this series of posts is to help XAML programmers to transit to HTML + JavaScript world, while carrying best practices such as MVVM pattern over to the new world. In this series, we’ll build a simple but fully functional website that manage customers from different countries. We’ll also build CRUD operations on customer orders.

Series prerequisites:

  • Know basic MVVM pattern concepts.
  • Know basics of knockoutjs. I’ll go through some “recipes” of using knockoutjs, but you should have at least browsed through the wonderful tutorials they provided.
  • Know basics of writing JavaScript in OO style.
  • Know basics of HTML markups.
  • Know basics of CSS.
  • Know jQuery.
  • Know a server side technology that serve JSON objects, such as ASP.Net MVC, PHP, etc. We won’t need it until the last sprint.

Sprint 1 backlog:

  • Get organized! We don’t want to create a big JavaScript file that does everything. Instead, we’ll create a folder structure to holder smaller scripts for different purposes. This will also improve code-reuse as we go along.
  • Create a simple county repository that serves up list of countries (id and name)
  • Create initial view model
  • Create initial view with only one dropdown box to display list of countries.

Tools required for Sprint 1:

  • knockoutjs
  • A text editor such as Notepad
  • A browser

Without further ado, let’s roll! (Link to download source of sprint 1 is at the end of this post)

1-1 Create folder structure

The following picture and table show the folder structure I’m going to use. Obviously this is not the only way to get things organized. But if you’d like to follow along, I recommend you use the same folder structure to avoid confusions. And if you are familiar with ASP.Net MVC, you may find this folder structure has some resemblances with ASP.Net MVC folder structure – this is intentional so that later on it will be easier for us to merge this into a ASP.Net MVC project (if we choose to, of course).

image

Picture 1-1: Folder structure

Folder Purpose
Content Hold static assets such as style sheets and images.
Scripts Hold various JavaScript files for example jQuery files and knockoutjs files will be under this folder.
Scripts
\Formatters
Scripts that are used to format data. Think them as IValueConverter implementations in you XAML project.
Scripts
\Repositories
Scripts that serve as client-side repositories. Client-side repositories hide service-invocation details. In the initial sprints we’ll use a mock repository that is not connected to any services at all. Later on we’ll switch to a real repository without impacting any other client code.
Scripts
\SharedTemplates
Data templates. Think them as your XAML user controls, control templates and data templates.
Scripts
\ViewModels
View models. No surprises here. They correspond to VM classes you would create with C# (or VB).
Views HTML files.

1-2 Prepare the folder

  1. Drop knockoutjs scripts to Scripts folder. I’m using 1.3.0 beta version for this series, but other versions should also work.
  2. Create a new Index.html file under Views folder. This will be our view for now.

1-3 Create mock country repository

  1. Create a countryRepository.js file under Scripts\Repositories folder. The mock repository defines one method: ListAllCountries, which returns a fixed set of countries:
    function MockCountryRepository(){
        this.ListAllCountries = function () {
            return [{"id":1, "name": "Belgium"},
                    {"id":2, "name": "Canada"},
                    {"id":3, "name": "China"},
                    {"id":4, "name": "United States"}];
        }
    };
  2. Test the repository. We’ll modify the Index.html code to add some testing logics for now. This is to make sure there’s no errors before we move forward. The code creates a new instance of MockCountryRepository, invokes its ListAllCountries method, and append result to a div (“#testCanvas”):
    <html>
        <head>
            <title>KOMVVM</title>
            <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
            <script src="../Scripts/knockout-1.3.0beta.js" type="text/javascript"></script>
            <script src="../Scripts/Repositories/MockCountryRepository.js" language="javascript" type="text/javascript"></script>
        </head>
        <body>
            <div id="testCanvas" />
            <script type="text/javascript">
                var countryRepository = new MockCountryRepository();
                var countries = countryRepository.ListAllCountries();
                for (var i = 0; i < countries.length; i++)
                    $("#testCanvas").append(countries[i].id).append(":").append(countries[i].name).append("<br/>");
            </script>
    </body>
    </html>
  3. Open Index.html in browser. If you see a warning of blocked content, allow blocked content (JavaScript) to execute. if everything is fine, you should see an output similar to this:image

OK, repository is working! Now let’s create the view model.

1-4 Create view model

Create a IndexPageViewModel.js under Scripts\ViewModels folder. This will be our main View Model for the page.

function IndexPageViewModel(countryRepository) {
    this.countryRepository = countryRepository;
    this.Countries = ko.observableArray([]);
    this.CurrentCountry = ko.observable("");
    var self = this;
    this.initialize = function () {
        var def = $.Deferred();
        $.when(countryRepository.ListAllCountries())
        .done(function (countries) {
            self.Countries(countries);
            def.resolve();
        });
        return def;
    };
}

OK, I admit it, there’s quite a jump here. What happened here are several things:

  • the view model takes a country repository in constructor. In other words here we are injecting a country repository implementation. You’ll see later on how swapping repository implementation allows us to connect to real services without needing to worry about code changes in any view models or views.
  • the view model has a Countries property, which is a knockoutjs observableArray type – think it as ObservableCollection in your XAML/C# world.
  • the view mdoel has a CurrentCountry property, which is a knockoutjs observable type – think it implements INotifyPropertyChanged interface from C# world.
  • the view model has an initialize method, which return a jQuery.Deferred() object. This is not necessary for now. But later on when we invoke multiple web requests to initialize, we need this promise mechanism so that data binding occurs only when we tell knockoujs that we are ready (by calling def.resolve()).

1-5 Modify the view

Now we add a dropdown list to the view and bind it to list of countries:

<html>
    <head>
        <title>KOMVVM</title>
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
        <script src="../Scripts/knockout-1.3.0beta.js" type="text/javascript"></script>
        <script src="../Scripts/Repositories/MockCountryRepository.js" language="javascript" type="text/javascript"></script>
        <script src="../Scripts/ViewModels/IndexPageViewModel.js" language="javascript" type="text/javascript"></script>
    </head>
    <body>
        <div id="testCanvas" />
        <select data-bind="options: Countries(), value:CurrentCountry, optionsText: 'name'">
        </select>
        <script type="text/javascript">
            var viewModel = new IndexPageViewModel(new MockCountryRepository());
            viewModel.initialize().done(ko.applyBindings(viewModel));
        </script>
</body>
</html>

First let’s see what’s happening in the <script> element: we created a new instance of IndexPageViewModel, providing a new instance of MockCountryRepository. Then we invoke initialize method on the view model, and when it’s finished we tell knockoutjs to perform data-binding (ko.applyBindings() call).

Under our test <div> we added a <select> element, which is bound to Countries property of the view model – no surprise here. If you don’t understand the syntax, read about knockoutjs again.

After the changes, reload the view and you should see something like this.

image

This concludes sprint 1! If you’d like to get source code of this sprint, you can download here.

Tuesday, December 13, 2011

ASP.NET MVVM with ASP.NET MVC 3 and knockout.js

There’s continuously increasing attention to separating presentation layer (HTML + javascript) and business layer (ASP.NET, PHP, etc.) in web development. More and more developers are seeking for supports of MVVM pattern in their web projects.  Among various offerings that exist today, knockoutjs is one of the most promising ones. It’s simple, it’s clean, and it has many core concepts of MVVM covered. On the server side, ASP.NET MVC 3 (and soon MVC 4) has gained great popularity in .Net communities. The purpose of this article is to explore a possible architecture that combines benefits of ASP.NET MVC 3 and knockoutjs and to provide a MVVM design pattern for common web project.

MVVM –> Entities + Views + View Models + (Repositories) + Services –> EVVMRS pattern

Before we go further, let’s reflect on what VM means in the MVVM pattern. In theory VM is an abstracted View, however in reality we often see VM contains other things such as business entities, entity repositories, and logics to invoke services. So here I’d like to make an explicit distinction: to get repositories and services out of VM and make them separate entities in the architecture. And here are the roles under this EVVM(R)S pattern:

  • E: Business entities. These are the entities you manage. Note the entities don’t contain business logics (well, maybe some basic data validations can be allowed).
  • V: Views. These are the UI presentations.
  • VM: View Models. These are the logical views that handles view interactions such as commanding, notifications, etc.
  • R: Repositories. These are where VMs get business entities. Repositories can also serve as the abstraction layer between VMs and Services.
  • S: Services. These are where business logics are encapsulated. Note the Services can be either local or remote. Repository layer provides a location-agnostic abstraction to VMs.

With this pattern, the architecture of a common web-based application can be illustrated as:

image

Where are Business Entities? Business Entities flow through this diagram and transform into different forms as they go. Specifically:

  1. From Database to Service: Services need to interact with databases with database-specific APIs. It can be ADO.Net, Entity framework, cloud storage, or other data-access APIs. Services convert these records into Business Entities. And all business logics should be built on top of these entities.
  2. From Services to Repositories: in the case that Services are local, Repositories can share the same Business Entity types with the Services. For remote Services, however, Repositories often don’t have direct access to Business Entity types defined on the Services. Instead, they’ll use some proxy types (such as the types you get when you add service references by using service metadata), or they’ll use totally different presentations such as XML or JSON objects (often seen in REST-ful calls). Although there are frameworks and tools that allow you to “share contracts” between your clients and servers, but the entities types on each side are still different physical types.
  3. From Repository to View Modes. Usually View Modes share the same Business Entity types with Repositories.
  4. From View Models to Views. View Models annotate Business Entities with change notification properties and supply annotated entities for UI binding to Views.

How to fit ASP.NET MVC 3 and knockoutjs into above pattern

Component Role
HTML View: screen markups and templates that knockoutjs can bind View Models to.
javascript “class” View Models: knockoutjs defines View Models as javascript classes.
javascript Repository: this part is up to you to define & construct. Repositories should encapsulate Service invocations.
JSON objects Business Entities: JSON are used when Services return data to client/Repositories.
C# objects Business Entities: These can be POCO types or Entity Framework types that are used in Service layer.
ASP.Net MVC Controller Services: REST-ful services that return JSON objects.

Under this pattern, MVC Controller will also provide “hook-up” for Views – they return Views to browser. However under this pattern they’ll simply return “untyped” views:

public ActionResult Index()
{
   return View();
}

In parallel MVC Controller provides Service APIs to client. For example, to supply Business Entities as JSON objects:

public JsonResult lisCustomers()
{
      return Json(dataContext.ListCustomers(), JsonRequestBehavior.AllowGet);
}

The corresponding view (.cshtml if you are using razor) contains standard HTML and javascripts only. You’ll not use @model directive anymore. (Of course in the future Microsoft may as well get everything combined!) Instead, you’ll use knockoutjs and jQuery template syntax to create views and binding templates. I won’t go into details here as there are abundant resources on the web.

Friday, December 2, 2011

Entity Framework TPT Performance Quick Tips

  1. When using model-first, choose TPH over TPT when possible.
  2. When using database-first, remove navigation properties from corresponding entities. Obviously there’s a tradeoff here, but to get TPT to a reasonable performance the sacrifice is necessary.
  3. Create views of corresponding tables and create entities on the views.

Sunday, October 30, 2011

Azure Toss!

Visit CodePlex page today: http://toss.codeplex.com/

Overview

With the booming of personal devices (such as iPad and Windows 8 tablets) and cloud-based services (such as Azure and iCloud), we are entering an era of highly connected yet very loosely coupled applications and services. As ISVs and application developers, you’ll find your applications need to communicate with many other applications and services in a “non-binding” way - there are no hard commitments among the applications and services to work together. Instead, services and features are discovered and consumed on an “as needed” basis. Azure Toss provides an integration platform that allows your services and applications to work together more easily and more reliably without any binding contracts. There are three levels of “tossing” under Azure Toss, which I shall explain one-by-one:

Level 1 – Simple Toss.

In case you haven’t noticed, there’s a universal application integration mechanism on virtually all platforms – the clipboard. By allowing simple Ctrl + C and Ctrl + V (or Command C and Command V for Mac) key strokes, many applications are able to share information among them without even knowing each other. There’s no data contract negotiation, there’s no fixed binding, applications simply try to work with the data they get through clipboard. Azure Toss Level 1 gives you a cloud-based clipboard with additional features such as publish-subscribe pattern, access control and multi-cast. Your applications and services will be able to “toss” information over the cloud to other parties without any committed contracts.

Level 2- Semantic Fields.

Let’s consider a very simple integration scenario among applications – to send a picture to another application. This was not a problem in the old days when your application only needed to talk to a handful of other applications. You need to study the APIs provided by the other applications and to code for these interfaces. However, imagine you’ll need to interact with hundreds of application, many of which are not written yet! To satisfy the needs to all those interface requirements is just infeasible. The problem is that traditional data contracts and APIs define only syntax of data, not semantics of data. The picture APIs don’t say “I need a picture, in .png or .jpg format” (although the names of functions may suggest that to humans)”. Instead, what they are really saying is “I need a byte array with an associated utf-8 encoded string”. Without a business context, that contract can mean anything. Azure Toss semantic fields allow you to describe your data and API needs with actual semantic meanings. Your application will be able to say, “Hey, I can give you a .png image if you want.” And other applications can still reliably integrated with your application because they will clearly know what they are going to get is indeed a png image.

Level 3 – Semantic service discovery and consumption

Imagine you are writing a chat client that automatically translates chat messages to different languages of the participants, and you want to use an online translation service for the purpose. What you need to do nowadays is to search around for such services, study their licensing, pricing, capabilities and APIs, and pick a service to work with. This is a one-way commitment – you are committed to the service but the service is not committed to you (or even knows you). When the service changes, your application breaks. Azure Toss will help you to avoid making such commitment. You application will simply say, “I need A translation service that translates between English and Chinese.” And Azure Toss will take care of the rest. Of course you can be much more specific on your needs: “I need a translation service that is free, with a rating higher than 4, within my trusted service providers”. Yet you still don’t need to worry about any details, Azure Toss will find the service for you. And if you chose to, Azure Toss can even invoke the service for you and return you the result. With the help of semantic fields, Azure Toss will be able to tell you, “Your request of translating text from English to Chinese has been fulfilled, and here’s the result text, in Chinese language”.

Monday, July 25, 2011

Silverlight Quick Tip: High CPU usage of Bing map control running in OOB

If you are experiencing high CPU usage when using Bing map control in an OOB Silverlight application, try to disable GPU acceleration. In my case changing the setting brought CPU usage from 70% to 2%.

p.s. To quickly identify which UI part is causing the most rendering cycles, enable redraw regions:

Application.Current.Host.Settings.EnableRedrawRegions = true;

This will make your screen blink a lot. The most flashing areas are the ones that hogging CPU cycles.

Also, with VS 2010 SP1, you can use Analyze->Launch Performance Wizard to profile your Silverlight application to identify high CPU users.