Welcome to WindowsClient.net | Sign in | Join

Cennest Technologies!

Our learnings as we experiment with Technology! www.cennest.com

Sponsors





  • advertise here

Blogs i read!!

Useful Sites

Azure Tip!:- Exposing TableService Entities as DataContracts in a WCF Web role!

If you are working with a WCF Web Role + Azure Table Storage with the need to expose the Table Entities as data contracts, the using the TableServiceEntity base class creates issues in serialization and the service does not run.

Instead use the following pattern to create your data- model

[DataContract]
[DataServiceKey("PartitionKey", "RowKey")]
  public class Test
 
{
       public string PartitionKey { get; set; }
       // PostedDate
       public string RowKey { get; set; }
      ----
      ----
  }

Basically

  1. Use the DataServiceKey attribute instead of the TableServiceEntity base class,
  2. Create two specific properties called PartitionKey and Row Key and
  3. Set the DataContract attribute!

This small tip will save you a couple of hours of hair pullingSmile

Cennest!

Azure Tip:- WCF WebRole Accessing Table Storage:- SetPublisherAccess error

If you are using a WCF Web Role to access table storage you might come across the following error

SetConfigurationSettingPublisher needs to be called before FromConfigurationSetting can be used

The following steps can help you

1. Ensure you have the Cloud project set up as the start up project

2. Ensure you are using the service reference of the Dev Environment web role and not your local IIS port( Another post on that incase you are facing an Add Service reference issue here but for now just replace the port in the web.config with http://127.0.0.1:81/yourservice.svc).

3. If you are using Azure SDK 1.2 then add the following code to your WebRole.cs OnStart method

CloudStorageAccount.SetConfigurationSettingPublisher((configName,configSettingPublisher) =>
   {
    var connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
    configSettingPublisher(connectionString);
   });

4. If you are using Azure SDK 1.3 then add a Global.asax to your WebService Web Role and add the following code

protected void Application_Start(object sender, EventArgs e)
       {
           CloudStorageAccount.SetConfigurationSettingPublisher(
       (configName, configSettingPublisher) =>
       {
           var connectionString =
               RoleEnvironment.GetConfigurationSettingValue(configName);
           configSettingPublisher(connectionString);
       } );
        
       }

5. Ensure you have WCF Http Activation On ( in control panel—> Windows Features)

Watch this space for lots more Azure tips!

Cennest!

 
Bulb Flash:- Azure Development Quick Tip!!

Recently we were stumped with the following error while working on an Azure project

Error 1 The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. C:\Program Files\MSBuild\Microsoft\Cloud Service\1.0\Visual Studio 10.0\Microsoft.CloudService.targets 202 5 OrderManagement

After a lot of head-banging, a simple Quick-Fix was to move the project to a root directory like a C: or a D: (Basically reduce the path of the project)

Hope you get to this quick-fix before you get to the head-bangingSmile

Cennest!

Bulb Flash:-SQL Azure tip; Firewall rules: allow all incoming IPs during testing and Development!

Before we even show you how , do note that this should be done only during testing of non-critical data which will cause no issues if accessed from unintended applications..

SQL Azure tracks the IP address for the purpose of security . However sometimes during development( and co-development) when you don’t have a static IP, it becomes quite a pain to keep checking the Firewall rules every time the app starts misbehaving…so during testing and development you can see the firewall rules to allow all connections by giving it the following settings..

 

image

Hope this saves you some time and headache…do remember to change these during production and when testing with critical data!

Until next time!

Cennest

Thinking of moving to the Cloud?

Cennest Technologies is a Microsoft Cloud Essentials Partner with focus on developing new applications/Migrating existing applications to the Cloud.

With in-depth knowledge of the framework and practical experience of custom development and live migrations we are aware of the usual bottlenecks you would face while trying to achieve an optimized deployment on Azure

Optimized on the Cloud= Performance+ Cost Optimization and Cennest has the knowledge you need to take the right decisions.

So get in touch with us at anshulee@cennest.com and lets reach for the clouds together!

Anshulee Asthana                                                                                              Founder:- Cennest Technologies                                                                                    We will move you to the Cloud!

Microsoft Azure App-Fabric Caching Service Explained!

MIX always comes with a mix of feelings…excitement at the prospect of trying out the new releases and the heartache that comes with trying to understand  “in depth” the new technologies being released…and so starts the “googling..oops binging”,,,blogs,,,videos etc…What does it mean?? How does it impact me??

One such very important release at MIX 2011 is the AppFabric Caching ServiceAt Cennest we do a lot of Azure development and Migration work and this feature caught our immediate attention as something which will have a high impact on the architecture, cost and performance of new applications and Migrations .

So we collated information from various sources (references below ) and here is an attempt is simplify the explanation for you!

What is caching?

The Caching service is a distributed, in-memory, application cache service that accelerates the performance of Windows Azure and SQL Azure applications by allowing you to keep data in-memory and saving you the need to retrieve that data from storage or database.(Implicit Cost Benefit? Well depends on the costing of Cache service…yet to be released..)

Basically it’s a layer that sits between the Database and the application and which can be used to “store” data prevent frequent trips to the database thereby reducing latency and improving performance

image_thumb1

How does this work?

Think of the Caching service as Microsoft running a large set of cache clusters for you, heavily optimized for performance, uptime, resiliency and scale out and just exposed as a simple network service with an endpoint for you to call. The Caching service is a highly available multitenant service with no management overhead for its users

As a user, what you get is a secure Windows Communication Foundation (WCF) endpoint to talk to and the amount of usable memory you need for your application and APIs for the cache client to call in to store and retrieve data.

image_thumb3

The Caching service does the job of pooling in memory from the distributed cluster of machines it’s running and managing to provide the amount of usable memory you need. As a result, it also automatically provides the flexibility to scale up or down based on your cache needs with a simple change in the configuration.

Are there any variations in the types of Cache’s available?

Yes, apart from using the cache on the Caching service there is also the ability to cache a subset of the data that resides in the distributed cache servers, directly on the client—the Web server running your website. This feature is popularly referred to as the local cache, and it’s enabled with a simple configuration setting that allows you to specify the number of objects you wish to store and the timeout settings to invalidate the cache.

image_thumb5

What can I cache?

You can pretty much keep any object in the cache: text, data, blobs, CLR objects and so on. There’s no restriction on the size of the object, either. Hence, whether you’re storing explicit objects in cache or storing session state, the object size is not a consideration to choose whether you can use the Caching service in your application.

However, the cache is not a database! —a SQL database is optimized for a different set of patterns than the cache tier is designed for. In most cases, both are needed and can be paired to provide the best performance and access patterns while keeping the costs low.

How can I use it?

  • For explicit programming against the cache APIs, include the cache client assembly in your application from the SDK and you can start making GET/PUT calls to store and retrieve data from the cache.
  • For higher-level scenarios that in turn use the cache, you need to include the ASP.NET session state provider for the Caching service and interact with the session state APIs instead of interacting with the caching APIs. The session state provider does the heavy lifting of calling the appropriate caching APIs to maintain the session state in the cache tier. This is a good way for you to store information like user preferences, shopping cart, game-browsing history and so on in the session state without writing a single line of cache code.

image_thumb7

When should I use it?

A common problem that application developers and architects have to deal with is the lack of guarantee that a client will always be routed to the same server that served the previous request.

When these sessions can’t be sticky, you’ll need to decide what to store in session state and how to bounce requests between servers to work around the lack of sticky sessions. The cache offers a compelling alternative to storing any shared state across multiple compute nodes. (These nodes would be Web servers in this example, but the same issues apply to any shared compute tier scenario.) The shared state is consistently maintained automatically by the cache tier for access by all clients, and at the same time there’s no overhead or latency of having to write it to a disk (database or files).

How long does the cache store content?

Both the Azure and the Windows Server AppFabric Caching Service use various techniques to remove data from the cache automatically: expiration and eviction. A cache has a default timeout associated with it after which an item expires and is removed automatically from the cache.

This default timeout may be overridden when items are added to the cache. The local cache similarly has an expiration timeout. 

Eviction refers to the process of removing items because the cache is running out of memory. A least-recently used algorithm is used to remove items when cache memory comes under pressure – this eviction is independent of timeout.

What does it mean to me as a Developer?

One thing to note about the Caching service is that it’s an explicit cache that you write to and have full control over. It’s not a transparent cache layer on top of your database or storage. This has the benefit of providing full control over what data gets stored and managed in the cache, but also means you have to program against the cache as a separate data store using the cache APIs.

This pattern is typically referred to as the cache-aside, where you first load data into the cache and then check if it exists there for retrieving and, only when it’s not available there, you explicitly read the data from the data tier. So, as a developer, you need to learn the cache programming model, the APIs, and common tips and tricks to make your usage of cache efficient.

What does it mean to me as an Architect?

What data should you put in the cache? The answer varies significantly with the overall design of your application. When we talk about data for caching scenarios, usually we break it into the data types and access patterns

  • Reference Data( Shared Read Data):-Reference data is a great candidate for keeping in the local cache or co-located with the client

image_thumb9

  • Activity Data( Exclusive Write):- Data relevant to the current session between the user and the application.

Take for example a shopping cart!During the buying session, the shopping cart is cached and updated with selected products. The shopping cart is visible and available only to the buying transaction. Upon checkout, as soon as the payment is applied, the shopping cart is retired from the cache to a data source application for additional processing.

Such an collection of data would be best stored in the Cache Server providing access to all the distributed servers which can send updates to the shopping cart . If this cache were stored at the local cache then it would get lost.

image_thumb11

 

  • Shared Data(Multiple Read and Write):-There is also data that is shared, concurrently read and written into, and accessed by lots of transactions. Such data is known as resource data.

Depending upon the situation, Caching shared data on a single computer can provide some performance improvements but for large-scale auctions, a single cache cannot provide the required scale or availability. For this purpose, some types of data can be partitioned and replicated in multiple caches across the distributed cacheimage

Be sure to spend enough time in capacity planning for your cache. Number of objects, size of each object, frequency of access of each object and pattern for accessing these objects are all critical in not only determining how much cache you need for your application, but also on which layers to optimize for (local cache, network, cache tier, using regions and tags, and so on).

If you have a large number of small objects, and you don’t optimize for how frequently and how many objects you fetch, you can easily get your app to be network-bound.

Also Microsoft will soon release the pricing for using the caching service so obviously you need to ensure usage of the Caching service is “Optimized” and when it comes to the cloud “Optimized= Performance +Cost”!!

Hope this helps you understand this new term better wrt Azure.

Until Next Time

Cennest!                                                                                                                                                                                           We can help you move to the cloud!”

References:

Bulb Flash:- Firing a Complex SQL Query using Entity Framework4.0

In one of our recent projects, we decided to swap SQL Express with SQL Compact to ensure easy installation on client machines…Though the move was smooth there was one hitch….SQL Compact does not support Stored Procedures!!!

And here we were with lots of  medium  complexity SPs with Joins and GroupBys ,OrderBy and Min Max functions!

For Example

select top(@number) p.ProjectName as ProjectName, p.ProjectID as ProjectID,c.Client_Name as ClientName,Max(pl.EndTimeStamp) as LastTimeWorked
from Projects as p join ProgramLog as pl
on
p.ProjectID  =pl.fk_ClientCode
join Clients c
on pl.fk_ClientCode = c.ClientID

Group By p.ClientProjectID, p.ProjectName ,c.Client_Name
Order by MAX (pl.EndTimeStamp) desc

We clearly had two options

1. Replace the stored proc logic with LINQ to Entity queries. We gave that a shot but realized its not easy to write a LINQ query with all the Joins, GroupBys and Max statements etc

2. Fire the SQL query from Entity Framework…We knew this could be done using LINQ to SQL  very easily but hadn’t tried it with the EF yet. Searching online brought us to the “ObjectQuery” feature . You can read more about it here.

Am not going to get into the details because this didn’t work for us also. Although ObjectQuery works well for simple statements( even parameterized), it didn’t work for us for using “Joins”. We tried many options including those given here but to no avail..

What worked!!

What did work for us was this really simple and beautiful feature provided in EF 4.0 called ExecuteStoreQuery<>

So the solution was as simple as

string query = @"select top(@number ) p.ProjectName as ProjectName,
 p.ClientProjectID as ProjectID,c.Client_Name as ClientName,Max(pl.EndTimeStamp)as LastTimeWorked
 from Projects as p join ProgramLog as pl 
 on
 p.ClientProjectID  =pl.fk_ClientCode
 join Clients c
 on pl.fk_ClientCode = c.ClientID

 Group By p.ClientProjectID, p.ProjectName ,c.Client_Name 
 Order by MAX (pl.EndTimeStamp) desc";
 var args = new DbParameter[] { new SqlParameter { ParameterName = "number", Value = count } };
 var result = entityContext.ExecuteStoreQuery<MostRecentProjects_Result>(query, args);
 List<MostRecentProjects_Result> resultList = result.ToList();
If you’ve been following closely you will notice I have the ExecuteStoreQuery method returning a list of MostRecentProjects…Since my query does not return a previously generated “entity” but involves a join statement returning a mix of values , this is not an edmx generated class but a simple custom class I created which has one property for each value returned by the query and the ExecuteStoreQuery method was nice enough to fill it for me!!(This was of course trial and error and are we glad it worked!!!)

This is what the class looks like

public partial class MostRecentProjects
  {
      public int ProjectID { get; set; }
      public string ProjectName { get; set; }
      public string ClientName { get; set; }
      public DateTime LastTimeWorked { get; set; }

  }

Hope this helps!

Until Next Time!

Cennest!

Bulb Flash:- Some practical WPF MVVMLight tips!

One of our major projects recently used WPF 4.0 with MVVM pattern.We used the MVVM Light Toolkit for implementing the MVVM Pattern.

The MVVM Light Toolkit definitely has a lot to offer to make your life easier but the documentation is not exemplary!

Few things we learnt down the road as we came to a close on the project are

1. You are better off using the ViewModalLocator. We didn’t use it initially and realized that our ViewModels are not getting Disposed, multiple view models are getting created especially when using the “Commanding” feature!

2. When using Commands , if you are not using the ViewModalLocator, try not to set the IsDataSource property as it will change the DataContext of your screen to the new ViewModel and there will be inconsistency during commanding as previously set variables will not be available in the new VM. Or if you do need to set the IsDataSource property send all data needed by the command handler as arguments( because previously set data will not be available to the new VM)

3. You need a default empty constructor in all your ViewModels or your XAML screens commands won’t work(They instantiate the empty construtor)

4. You can pass event args parameters in commands using PassEventArgsToCommand="True" in your EventToCommand XAML

5. When using messaging use the method overload Send<TMessage>(TMessage message, object token).Using the token to register and send messages ensures it is delivered only to valid subscribers!

6. Every time you register for an event using the Messenger.Default.Register….ensure you Unregister also using the Messenger.Default.Unregister or else you might have memory leaks!!

Will try to write more elaborate posts detailing out these and more issues .Meanwhile drop a note at anshulee@cennest.com if you have any queries/ need more tips related to MVVM…

Until then!

Cennest!

Posted: Mar 29 2011, 12:42 PM by Anshulee | with no comments
Filed under: ,
EF 4.0 Bulb Flash!:- Load only what you need!!

A small tip for those working with Entity Framework 4.0:- We all know the concept of Lazy Loading in the Entity Framework: With lazy loading enabled, related objects are loaded when they are accessed through a navigation property.

With lazy loading a drawback is that an object retrieved from the database comes loaded with all its navigable Objects so you may be querying an “Order” class but it comes loaded with the Order.Customer object . While you may want this in some cases, it makes sense to disable this feature in performance oriented applications and load only what you need!

As against what is written in MSDN , our experience is that when an entity context object gets created, its LazyLoadingEnabled property is defaulted to true!… This is also a reported issue with microsoft

So first step would be to disable the LazyLoadingEnabled!

ProgramEntities entityContext = new ProgramEntities(); entityContext.ContextOptions.LazyLoadingEnabled = false;

List<Order> orderList= entityContext.Orders.ToList();

Next, load what you need!

orderList.ForEach(p => entityContext.LoadProperty(p, "Customer"));

Now you can access the Customer as Order.Customer while ensuring you did not load other related  navigable properties like Order.Contents etc etc.

Hope this helps “lighten” up your code a bit!!

Anshulee!

Cennest Technologies

Introducing Amazon Web Services to a Windows Azure developer

If you have been working on Windows Azure and have now decided to ramp up on Amazon Web Services, this note can help you map Amazon and Azure and understand where one stands wrt the other..

Just like the Azure platform  is broken up into SQL Azure, AppFabric (Service Bus and Access Control) and Windows Azure (Tables, Blobs and Queues), Web and Worker roles, Azure CDN etc etc  and you had to ramp up on all those terms when you started up on Azure, Amazon doesn’t make life easier either:-)

The MAIN difference between Amazon and Azure is of course the IAAS vs PAAS and if you haven’t read an earlier blog on this then i suggest you read it now..

What i am attempting to do here is introduce you to the different aspects of Amazon Web Services(AWS) and at the same time i will mention how it is similar(note “similar” and not compulsorily “same”) to a feature available in Azure..

Lets start with the most frequently heard term..

  • Amazon EC2…

So you keep reading about Amazon EC2 and at least i used to think each machine in that data centre is called an Amazon EC2..nope..Amazon EC2 is a web service that enables you to launch and manage server instances in Amazon's data centers using APIs or available tools and utilities .

So what you launch is a “service instance” also called as Amazon Machine Images( AMI) and you launch and manage them using EC2. These AMIs are also called EC2 Instances but you must be clear that EC2 is a webservice and not the instance itself!!

  • Amazon Elastic Block Store(EBS) :(Azure Counter part:- None)

Amazon Elastic Block Store (Amazon EBS) offers persistent storage for Amazon EC2 instances.(Something we sorely miss in Azure and leads to lot of heartache!!!) Amazon EBS volumes provide off-instance storage that persists independently from the life of an instance. Amazon EBS volumes offer greatly improved durability over local Amazon EC2 instance stores, as Amazon
EBS volumes are automatically replicated on the backend (in a single Availability Zone).

Elastic IP addresses are static IP addresses designed for dynamic cloud computing. An Elastic IP address is associated with your account, not a particular instance, and you control that address until you choose to explicitly release it. Unlike traditional static IP addresses, however, Elastic IP addresses allow you to mask instance or Availability Zone failures by programmatically remapping your public IP addresses to any instance in your account.

  • Auto Scaling :- (Azure Counterpart:- None)

Auto Scaling allows you to automatically scale your Amazon EC2 capacity up or down according to conditions you define. With Auto Scaling, you can ensure that the number of Amazon EC2 instances you’re using scales up seamlessly during demand spikes to maintain performance, and scales down automatically during demand lulls to minimize costs. Auto Scaling is enabled by Amazon CloudWatch and available at no additional charge beyond Amazon CloudWatch fees

Though Auto Scaling is possible in Azure it is left to the developer to implement autoscaling algorithms for the same. The option of setting trigger conditions and creating Auto- Scale groups etc that Amazon offers is every Azure developer’s dream!!

  • Amazon Virtual Private Cloud :- (Azure Counterpart:- None)

Amazon VPC enables enterprises to connect their existing infrastructure to a set of isolated
AWS compute resources via a Virtual Private Network (VPN) connection

Not applicable to Azure since its a PAAS offering

  • Amazon CloudWatch :-(Azure Counterpart:- IIS Logs)

Amazon CloudWatch is a web service that provides monitoring for AWS cloud resources, starting with Amazon EC2. It provides you with visibility into resource utilization, operational performance, and overall demand patterns—including metrics such as CPU utilization, disk reads and writes, and network traffic 

Azure IIS Logs don’t really come close to the functionality provided by CloudWatch and needs to be configured in code, moved to blobs and then pulled down.

  • Amazon Cloud Front :- (Azure Counterpart:- Azure CDN)

Amazon CloudFront is a web service for content delivery. It integrates with other Amazon Web Services to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no commitments.

Requests for your objects are automatically routed to the nearest edge location, so content is delivered with the best possible performance

Being a typical CDN its pretty comparable to Azure CDN

  • Amazon SimpleDB :- (Azure Counterpart:- Windows Azure Table Storage)

Amazon SimpleDB is a highly available, scalable, and flexible non-relational data store.Unbound by the strict requirements of a relational database, Amazon SimpleDB is optimized to provide high availability, ease of scalability, and flexibility with little or no administrative burden

Pretty comparable to Azure Table Storage, though it will be interesting to see which one performs better in times of “stress” and partitioning requirements..

  • Amazon RDS :- (Azure Counterpart:- SQL Azure)

Amazon Relational Database Service (Amazon RDS) is a web service that makes it easy to set up, operate, and scale a relational database in the cloud. It provides cost-efficient and resizable capacity while managing time-consuming database administration tasks

Amazon RDS gives you access to the full capabilities of a familiar MySQL database. This means the code, applications, and tools you already use today with your existing MySQL databases work seamlessly with Amazon RDS

Amazon RDS is MySQL on the Cloud and SQLAzure is SQL server on the Cloud!! 

  • Amazon Simple Queue Service (Amazon SQS):-(Azure Counterpart:-Windows Azure Queues)

Amazon Simple Queue Service (Amazon SQS) offers a reliable, highly scalable, hosted queue for storing messages as they travel between computers. By using Amazon SQS, developers can simply move data between distributed components of their applications that perform different tasks, without losing messages or requiring each component to be always available

Again quite comparable to the functionality delivered by Azure Queues

  • Amazon Simple Notification Service (Amazon SNS):- (Azure Counterpart:- Azure Service Bus eventing and subscription Model)

Amazon Simple Notification Service (Amazon SNS) is a web service that makes it easy to set up, operate, and send notifications from the cloud. It provides developers with a highly scalable, flexible, and cost-effective capability to publish messages from an application and immediately deliver them to subscribers or other applications. It is designed to make web-scale computing easier for developers.

Directly comparable to the Evening and Subscription model available in Azure App Fabric Service Bus..The service namespace coupled with message buffers make powerful publish-subscribe models.

  • Elastic Load Balancing(Azure Counterpart:- Inbuilt in the Azure fabric)

Elastic Load Balancing automatically distributes incoming application traffic across multiple Amazon EC2 instances. It enables you to achieve even greater fault tolerance in your applications, seamlessly providing the amount of load balancing capacity needed in response to incoming application traffic.

This is of course inbuilt in the Azure framework.

  • Amazon Simple Storage Service (Amazon S3):-(Azure Counterpart:- Windows Azure Blob Storage)

Amazon S3 provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web. It gives any developer access to the same highly scalable, reliable, secure, fast, inexpensive infrastructure that Amazon uses to run its own global network of web sites.

Similar to Blob functionality

Hope this helps clear up the air a bit …coming up next..a deep dive into Amazon EC2 Instances…oops AMIs:-)

Till then!

Anshulee

.NET Developer Exploring Amazon WS as an Alternative to Microsoft Azure

With all the various Cloud options available out there ,an extremely confused section of the population is us “developers” :-). Every time we hear of a new platform the “engineer” in us would question:-“what would it take to deploy an application there?” and being a Microsoft developer i always wonder if i can deploy a .NET app there.

After being confused for a LONG time i decided to check out at least the biggest names to understand if i can work with anything other than AZURE with .NET…and the platform which came to my rescue was none other than Amazon Web Services( Called AWS).

Unlike Azure, AWS is a IAAS offering meaning you provision a Virtual Machine( called Amazon Machine Image or AMI) , set it up with all that you need to get your application to work and you are up and running. If you are reading this blog and understand the restriction that the Azure VM instance have you will realize that this  a HUGE advantage over Azure.

Unlike Amazon Azure is an PAAS offering  meaning it offers a “pre-provisioned Platform” as a service. You can deploy anything on the platform “as long as” the platform supports it. This places a lot of restrictions on the application:- like i cannot write to the registry, cannot have a dependency on another pre-deployed component etc. Amazon on the other hand gives you a blank machine, lets you set it up as you like and enables you to do whatever it takes to let your application run!!

You can provision the AMIs(Amazon machine images) with any of the following OSs

image

Did you notice Windows Server 2003/2008 there?? And with a Windows Instance you can even provision an IIS and SQL Server….practically the basics of any of our deployments!!

Great!!…so one should just go with AWS then…why bother with Azure..Because Azure comes with its own advantage set!!….Ease of use!!

While the AWS IAAS model offers a great deal of flexibility, it takes its toll on the developer..You're responsible for that virtual machine the same way you're responsible for a server sitting under your desk. You're responsible for turning it on. You're responsible for turning it off. You're responsible for applying a patch or an update. If Microsoft applies a Server patch, and you have a Server VM running on Amazon, you have to apply that patch yourself. They won't do that for you

Azure’s "Platform-as-a-service " has a definite advantage:- All of that stuff is completely abstracted away, it's a friction-free development, you basically code up an application, you hit deploy and it'll go run on the platform that's supplied by those runtimes.

So where Azure loses in Flexibility it gains in ease of use, and where AWS loses in ease of use it gains in flexibility!!…But, together both platforms will make it possible to set up any kind of .NET application on the cloud.

But in the industry leader’s fight to the top, the developer is bound to win…so industry leaders predict that soon Azure will also provide a “IAAS kind of option” to provide flexibility and Amazon will be forced to ALSO provide a “PAAS” kind of option with pre-configured AMI’s!!

Next we will go a little deeper into AWS and try to compare it to Azure feature by feature…lets see who can fulfil all our Cloud Demands!!

Till then!

Anshulee

Federation Metadata Generator

While playing around with Claims code a common issue i faced was a “ID6013:The Signature Verification Failed” error while doing an Add STS reference. This was more so when i moved my STS around from one server to another or changed the STS url.

After a lot of struggle i realized that the The signature in a typical federation metadata contains a hash of the url. So once you move your STS around and change the EntityID url the hash becomes invalid.

There are two options here

1. Remove the signature section of your STS:- i.e Remove the following from the federation metadata node

Removing this section from the metadata will remove the Signature mismatch error but will show you the following warning about the metadata being unsigned during Add STS reference. Click OK and continue.

2. Use the Federation Metadata Generator to regenerate the Federation Metadata . Run it as Administator, Provide the new Issuer Url, Active endpoint url , add the certificate and Click on Sign certificate to regenerate the new hashed signature. This will regenerate the entire metadata with the correct url and signature.

Hope this helps you save time time and gray matter:-)

Anshulee

Identity Foundation:- Creating, Sending and Consuming Custom Claims

In continuation with our learnings on using the Claim Based Identity Framework , we will next see how to send Custom Claims from a STS  and how to receive it in the Silverlight Client we made in  the last post.

Lets see what we got as an output from our last post

image

Yeah i know it looks like “THIS is what we got after so much work??” but remember that we did a lot of very important steps which  set the framework to allow someone else to do the authentication work for you.

Just to recap the following code in the Silverlight app gave you the name of the logged in user

string userName = ClaimsIdentitySessionManager.Current.User.Identity.Name;

Name and Role are two default claims all STS give you by default . But what if you also want the surname  and Age of the logged in user?

Here are the steps you need to perform

 Define the claim in the STS:- How complicated this gets depends on whether the claim you want to retrieve is a custom claim or simply a new claim.

By Custom claim i mean you need to define it. It does not exist in the Microsoft.IdentityModel.Claim.ClaimTypes enum

First lets work with the Surname claim.

Open the TravelSTSService\CustomSecurityTokenService class and navigate to the GetOutputClaimsIdentity method. Here you can see code to return claims to the caller.

Replace by the following code

protected override IClaimsIdentity GetOutputClaimsIdentity( IClaimsPrincipal principal, RequestSecurityToken request, Scope scope )
{
 if ( null == principal )
   {
     throw new ArgumentNullException( "principal" );
   }

ClaimsIdentity outputIdentity = new ClaimsIdentity();

string userName = principal.Identity.Name;
switch (userName)
{
  case "anshulee":
      outputIdentity.Claims.Add(new Claim(ClaimTypes.Surname, "Asthana"));
      break;

}
outputIdentity.Claims.Add( new Claim( System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name ) );
outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Manager" ) );

return outputIdentity;
}

So we did some hardcoding (which you will obv remove in a real prod code) and we didn’t have to do much to return the Surname as it was part of a predefined set of claims in the “Claim Types”.

Now lets add age. Age does not exist in the ClaimTypes enum. So first we need to define a new claim called Age. Its a simple two step process

1. Define a constant called UserAge

private const string UserAge = "http://bsiltravels.com/2010/08/identity/claims/age";

2. Now add it in the Output Identities as usual

outputIdentity.Claims.Add(new Claim(UserAge, "80"));

Ok So far so good, but how does a client know that the STS is going to offer these claims?

What claims are being offered is part of the Federation Metadata of an STS. So now we need to add these two claims in the federation metadata

Open the Federation Metadata.xml file under …TravelSTSService\FederationMetadata\2007-06 and add the following node under the <fed:ClaimTypesOffered> node

<auth:ClaimType Uri="http://bsiltravels.com/2010/08/identity/claims/age" Optional="true" xmlns:auth="http://docs.oasis-open.org/wsfed/authorization/200706">
<auth:DisplayName>Age</auth:DisplayName>
<auth:Description>The age of the subject.</auth:Description>
</auth:ClaimType>

<auth:ClaimType Uri="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/Surname" Optional="True" xmlns:auth="http://docs.oasis-open.org/wsfed/authorization/200706">
<auth:DisplayName>Surname</auth:DisplayName>
<auth:Description>The surname of the subject.</auth:Description>
</auth:ClaimType>

So now the STS offers two more claims and also announces the same fact. If you were to add an STS reference to this service at this point you will get these claims directly.

However remember that we have already added the STS reference and there is no “Update STS reference option” in VS2010. So even though the Service now provides new claims, our client does not know about it. Also the client needs to ask for these claims. In a final production level system a Service will only provide the claims asked by the client.

One option is to remove and re-add STS. But if you don’t want to do that just add the following nodes in the BSILTravelPartners/web.config under the <claimTypeRequired>node

<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" optional="true"/>
<claimType type="http://bsiltravels.com/2010/08/identity/claims/age" optional="true"/>

Now the final part:- Accessing the claims in the code.

Replace the code in the ABCTravels/MainPage method Current_SignInComplete method with the following

string ageClaim = "http://bsiltravels.com/2010/08/identity/claims/age";
string userName = ClaimsIdentitySessionManager.Current.User.Identity.Name;
string surname = ClaimsIdentitySessionManager.Current.User.ClaimsIdentity.Claims[SL.IdentityModel.Claims.ClaimType.Surname].Value;
string age = ClaimsIdentitySessionManager.Current.User.ClaimsIdentity.Claims[ageClaim].Value;

this.txtName.Text = string.Format("{0} {1}:Age {2}", userName ,surname ,age );

Lets run the app and see what we get  now..

image

Much Better now!!

So to recap we just learnt how to create, send and consume custom claims!!

Coming up next…Taking this app to another level by using Azure App Fabric Service Bus for Authorization!!!

Till then…keep up your claims!!

Anshulee

Active Authentication:- Passing Claims to Silverlight Application

In a previous post on Customizing WCF Token Service for Custom Authentication we saw how we can create a WCF Token Service from VS2010 templates and then customize it to authenticate against a custom source

Next we need to Add it as a Federation Service to our Silverlight application.

To do that create a new Silverlight application called ABCTravels and host it in a WebApp BSILTravelPartners

image

 

Silverlight as such does not have the Microsoft.Identity.dll. Microsoft has instead provided two source codes in the SDK which can be used with Silverlight. They are obviously limited in functionality but will serve our purpose will now.

Navigate to your ..\IdentityTrainingKit2010\Labs\SilverlightAndIdentity\Source\Assets folder and add the SL.IdentityModel and SL.IdentityModel.Server folder to your solution.

image

From your Silverlight application add reference to the SL.IdentityModel.dll

From your web application add reference to the SL.IdentityModel.Server.dll

At the end your solution should look like this

image

Next add STS reference to the BSILTravelPartners using the AddSTSReference option .

Open BSILTravelPartners\Web.config and locate the following node

<system.webServer>
        <modules>
            <add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler"/>
            <add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler"/>
        </modules>
    </system.webServer>

Add a      

<validation validateIntegratedModeConfiguration="false" />

right above the <modules> node.

This has now hooked the Web application and the STS.

Next we will see how the Claim values returned by this service can be passed back to the Silverlight client. Remember that the STS  service was invoked by the WebApp hosting the Silverlight client and not the client itself hence the values will not be transferred to the SL client automatically.

Add a Silverlight Enabled WCF service to the BSIlTravelPartner site

 image

Open the .svc and replace with the following text

<%@ ServiceHost Language="C#" Debug="true" 
Factory="SL.IdentityModel.Server.AuthenticationServiceServiceHostFactory" 
Service="SL.IdentityModel.Server.SL.IdentityModel.Server"
 %>

image

Now to customize the Silverlight app..

Add a Login User Control(You can take it from the SDK sample) and reference it in your MainPage.xaml as a Popup.

Open the App.xaml and add the following to the Application node

 <Application.ApplicationLifetimeObjects>
        <id:ClaimsIdentitySessionManager ApplicationIdentifier="https://localhost/BSILTravelPartners/" >
            <id:ClaimsIdentitySessionManager.IdentityProvider>
                <id:WSTrustSecurityTokenService Endpoint="https://localhost/TravelSTSService/Service.svc/IWSTrust13" CredentialType="Username" />
            </id:ClaimsIdentitySessionManager.IdentityProvider>
        </id:ClaimsIdentitySessionManager>

    </Application.ApplicationLifetimeObjects>

Open the MainPage.xaml and paste the following code

public MainPage()
 {
     InitializeComponent();
     ClaimsIdentitySessionManager.Current.SignInComplete += new EventHandler<SignInEventArgs>(Current_SignInComplete);
     this.loginPopup.OnLogInCompleted += (s, e) =>
      {
        ClaimsIdentitySessionManager.Current. SignInUsernameAsync(e.UserName, e.Password);
      };

       this.loginPopup.Show();

 }

 void Current_SignInComplete(object sender  , SignInEventArgs e)
  {
    string userName = ClaimsIdentitySessionManager.Current.User.Identity.Name;
          
    this.txtName.Text = string.Format(userName);
  }

Now Run the application

image

Put a breakpoint at TravelSTS/CustomUserNameTokenPasswordHandler ValidateToken method and check the validation method

image

image

Coming Up Next:- Passing Custom Claims from the STS.

Until then…keep Claiming!!

Anshulee

WIF:-Customising the WCF Token Service template for Custom Authentication

Installing the Windows Identity Foundation SDK installs a set of templates into VS2008/VS2010. Two of these templates are for creating Custom Security Token Services.

image

Out of these the ASP.NET Security Token Service is a template for a Passive Federation STS and the WCF Security TokenService is a template for an Active FederationSTS.

I wanted to implement ActiveFederation but i had my own logic of authentication. I wanted the username password and would authenticate against a custom Database(maybe membership DB)

So i selected WCFSecurityTokenService as the template

But since this is a standard template, you need to then customize it as per you needs.

For a basic customization of taking in username and password and adding your own authentication logic follow the given steps..

 

Add the following config section under configuration

<configSections> 
    <section name="microsoft.identityModel" type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> 
  </configSections>

If for testing you do not want to use an Encryption certificate then replace the following line under AppSettings

<add key="EncryptingCertificateName" value="CN=DefaultApplicationCertificate"/>

with

 <add key="EncryptingCertificateName" value=""/>

I wanted to authenticate against a custom database so the username and password were to be passed to the STS in the SOAP request. Hence replace the Security Mode from Transport(basic https) with TransportWithMessageSecurity(Https with some credential information). So Replace

 <ws2007HttpBinding>
        <binding name="ws2007HttpBindingConfiguration">
          <security mode="Message">
            <message establishSecurityContext="false" />
          </security>
        </binding>
      </ws2007HttpBinding>

   with

<ws2007HttpBinding>
        <binding name="ws2007HttpBindingConfiguration">
          <security mode="TransportWithMessageCredential">
            <message establishSecurityContext="false" clientCredentialType="UserName" />
          </security>
        </binding>
</ws2007HttpBinding>

Last but not the least. I have my own authentication logic(against a custom database) so i need to put in a Custom SecurityTokenHandler  which inherits from UserNameSecurityTokenHandler in place which will contain my custom code.

<microsoft.identityModel>
    <service>
      <securityTokenHandlers>
        <remove type="Microsoft.IdentityModel.Tokens.WindowsUserNameSecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add type="CustomUserNamePasswordTokenHandler, App_Code"/>
      </securityTokenHandlers>
    </service>
  </microsoft.identityModel>

This is done in the <configuration> node. The Custom Class is placed in the App_Code folder.

Having Inherited from the UserNameSecurityTokenHandler  this class needs to override  two methods:- CanValidateToken and ValidateToken. The ValidateToken method will contain your validation logic.

A sample of this class can be found in the IdentityDeveloperTrainingKit

Until Next Time!

Anshulee

Next page »
Page view counter