The Rain and The Shade

September 30, 2011

Azure AppFabric Access Control Service

Filed under: AppFabric,Windows Azure — ovaisakhter @ 11:31 pm

My neighbor bought a new TV I wanted to go to his house and have a look at it. But the problem was I dint know him all that well. I asked one of our common friend to introduce me to him so that I can go to his house and have a look at his new TV. My friend introduced us and told him that my name is Ovais and I am a reasonably decent person. As my neighbor trusted my friend, he let me in his house

(there nothing true in this story except the fact that my name is ovais and I am a recently decent man Winking smile).

If we map this story to the cyber space it will be something like, I go to a website, it has no way to verify who I am, so it asks me to prove my identity to Facebook when I do that Facebook tells this site that I am Ovais and the website lets me in the member area.

If we describe the same scenario in terms of Access Control Service then,the website is the “Relying party (RP) application” I am the client and Facebook is the Identity provider. The difference in CyberSpace is that there can be multiple Identity Providers but they do not speak the same language. So you need some one to translate their different languages into one standard language so that the website’s access control functionality is simple and robust, and AppFabric Access Control Service provides this translation functionality.       

ACS currently supports following Identity Providers

  • Windows Live credentials
  • Facebook
  • Google
  • Yahoo
  • WS-Federation identity provider(e.g. Microsoft AD FS 2.0)

To get started with ACS you have to log into your Azure Management portion. Then go to AppFabric/Access Control section and create a new namespace. Once the namespace is created you are now ready to configure the service.

At this point you may get an error if you are not the primary administrator of the subscription. If this is the case have a look at this link with known issues and workarounds http://msdn.microsoft.com/en-us/library/windowsazure/gg429787.aspx. Either you have ask your primary administrator to do the steps mentioned on this link or will have to do it yourself, Of course if you know his/her password Winking smile.

(I will not describe every step in detail have a look at this detail for full details http://msdn.microsoft.com/en-us/library/windowsazure/gg429779.aspx)  

Once you are on the ACS Management portal here are the things you need to do

  • Add Identity Providers
  • Add a Relying Party Application
  • Create Rules

I hope with my award winning full of suspense story you were able to understand the concept of first two. You can find the details of the step in details on the above mentioned link. Here I will like to write a bit about the Rules.

To understand rules first we need to understand another very important concept i.e. Claims. If you again consider my story, my friend Claimed that I am a decent enough man. My neighbor trusted this claim so he let me in. When are you are authenticated by an Identity Provider it also claims some things about you like you have this name and this email and your designation is Manager. Now different IPs may use different names for these claims. Rules actually map these different types of claims into a standard language so that the relying party deals with only one set of terminology. You can also define conditional mapping. For example the rule in the snapshot says that if user’s email address is ahmed.ovais@gmail.com then add a claim that he has Admin role.

  image

All this configuration can be done using the management api which will enable you to automate this process or even create a more intuitive user interface for your administrators.

Once these steps are done you are all set to create your application and use the ACS there. 

You can enable an ASP.Net MVC application to use ACS following the step 8 provided in the link i.e. Step 8 – Configure Trust Between ACS and Your ASP.NET Relying Party Application. Once done with it you will be all set to test and execute your application. Here is how the log-in screen will look like when you will try to access your website. The options to login depend on the Identity Providers selected during configuration of the ACS.

image

So now your site has a Authentication system without writing a single line of code. You can at anytime add/remove the Identity provider without needing to change anything in the application.

In the next blog I will try to discuss how Authorization can be done using ACS in an MVC application.

Advertisements

September 27, 2011

Topics, Subscriptions and Receivers in Windows Azure App Fabric Service Bus

Filed under: AppFabric,Windows Azure — ovaisakhter @ 12:25 am

 

I believe the most complex thing I found when looking into the Azure AppFabic Service bus is the pricing model. After spending quite a few precious minutes of my life I now think understood it but I am still not sure if I am correct. So this matter has to wait until my next statement arrives and I got yelled by my support department. At which time I may come back with a blog on that. Meanwhile you can go ahead and have a look at the pricing FAQ at

http://www.microsoft.com/windowsazure/faq/#pricing

good luck with that Smile

So now back to simpler things, Usually Udi Dahan starts his NServiceBus presentation with this “Where is the bus, There is no bus”. Well in the case of AppFabric Service Bus there is a Bus. You can have a look at it at the Azure management portal.

Now I will use this bus to create a simple chat application and while I am using it I will try explain some of its concepts. Please make sure to install the relevant SDK installed from the following link

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27421

Our chat application is a WPF application containing only one screen. The application allow any number of users to join in and every one will see every one’s messages. For simplicity the user names are given in the configuration file. So the main screen only has a list of messages, a message textbox and a send button. Application uses MVVM so most of our functionality resides in the ViewModel. I am using Galasoft’s MVVM light framework here which is a treat to use in it self but more on that later.

Long story short the button is bound to a command and we are mostly concerned from that point onwards.

image

I have encapsulated all the logic related to the service bus functionality into a separate class let us call it service bus manager in its constructor the class connects to the service bus and tries to create the initial structure required for the communication. Have a look at the following code

var tokenProvider =
           TokenProvider.CreateSharedSecretTokenProvider(IssuerName, IssuerKey);
           var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty);

           _namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

The bold variables actually signify some steps that should be done before starting the code i.e. You should create a Service Name space. The service name space is actually the unique identity of your service using which your service bus will be located. Here is a link on how you can do it otherwise you can log into the Azure Management portal and find your way to do that,

http://debugmode.net/2011/04/05/getting-started-with-azure-appfabric-service-bus-creating-namespace/

Once your namespace is created and selected you will be able to see Default Key property on the Properties section click the button and you will be able to see the IssuerName and IssuerKey.

NamespaceManager is the main class in the API once you have created an instance of this you can go on and manipulate things. Next thing we would like to do is to create a topic, Following code checks if there is a topic already created for the Chat if not then it creates it.

_myTopic = !_namespaceManager.TopicExists(ChatTopic) ? _namespaceManager.CreateTopic(ChatTopic) : _namespaceManager.GetTopic(ChatTopic);

all good except I have not explained what a topic is, “A topic is a durable message log with multiple subscription taps separately feeding subscribers” So topic is a central entity against which all the messages are published, and as many as 2000 subscribers can subscribe to it. Once a message is posted to a topic a copy of this message is sent to each of the subscribers. 

Speaking of subscriptions here is the code which will create the subscriptions to our newly created topic.

if (_namespaceManager.SubscriptionExists(_myTopic.Path, clientName))
            {
                _namespaceManager.DeleteSubscription(_myTopic.Path, clientName);
            }

            _namespaceManager.CreateSubscription(_myTopic.Path, clientName,
                                                 new SqlFilter(string.Format("From <>'{0}’", clientName)));

For the chat application we are creating one subscription for each client, we are checking if there is a subscription already I am deleting and creating a new one. This code also shows another aspects of the subscriptions that they can be selective i.e. you can tell what type of messages posted on the topic you are interested in. Here I am specifying that I am not interested in the messages sent by myself, which kind of makes sense for a chat application. Here “From” is a property of the message which contains the user name of the user who sent the message. In our application a chat message is represented by a ChatMessage Class

public class ChatMessage
    {
        public string Message { get; set; }
        public DateTime ReceivedTime { get; set; }
        public string From { get; set; }
        public string Id { get; set; }

    }

but we do not send this message as it is. More on this later let us carry on with the constructor code

              var factory = MessagingFactory.Create(serviceUri, tokenProvider);
            _myTopicClient = factory.CreateTopicClient(_myTopic.Path);
            _mySubscriptionClient = factory.CreateSubscriptionClient(_myTopic.Path, clientName, ReceiveMode.ReceiveAndDelete);

As all good chat applications our application will send and receive messages _myTopicClient will be used to send the messages and _mySubscriptionClient will be used to receive the messages.

Let us talk about sending first,

public void SendMessage(ChatMessage chatMessage)
        {
            using (var message = new BrokeredMessage())
            {
                message.CorrelationId = chatMessage.From;
                message.Properties.Add("Message", chatMessage.Message);
                message.Properties.Add("From", chatMessage.From);
                message.Properties.Add("Id", chatMessage.Id);

                _myTopicClient.Send(message);
            }

        }

simple enough I guess. Just keep in mind that

“Maximum message size: 256KBMaximum header size: 64KBMaximum number of header properties in property bag: MaxValue Maximum size of property in property bag: No explicit limit. Limited by maximum header size.”

Now let us talk about receiving the message. Service bus messages are received by polling on the service bus “kaachhaaan” I can hear the sound of breaking heart but well this is true no events guys not for now at least. Here is the code that does “the magic”.

var task = new Task(ReceiveMessageTask);
            task.Start();

Started a task to start a separate thread for polling, may not be the best way to do it but it works we are good to go here.

private void ReceiveMessageTask()
       {
           while (true)
           {
               var message = _mySubscriptionClient.Receive(TimeSpan.FromSeconds(2));

               if (message == null) continue;

               var chatMessage = new ChatMessage
                                     {
                                         From = (string)message.Properties["From"],
                                         Id = (string)message.Properties["Id"],
                                         Message = (string)message.Properties["Message"],
                                         ReceivedTime = DateTime.Now
                                     };

               FireMessageReceived(chatMessage);

          }

       }

so we poll for message after every 2 seconds and if we receive a message we fire an event which is handled by the ViewModel which get the message and updates the UI.

Here is where I am chatting to myself

image

(ignore the “Not Connected” label on the left)

You can open as many applications as you want about (2000) to be precise give them different names and they will work.

Do try this at home. I have given the example of a chat application to explain some of the concepts in azure appfabric service bus. Of course I do not believe it to be a rightful use of this technology. Service bus is used to enable applications to talk to each other. If you would like to dig deep into how and where the service bus should be used I recommend looking into sessions of Udi Dahan. They are not related to AppFabric service bus but give you a great insight to the scenarios where it can be used.

You can download the full application code from this link

http://ge.tt/92ik9B8?c

Please do not mind the strange namespace name “DropBoxChatApp” as this is a story of another time.

Have fun guys

September 4, 2011

What to inject and what not to inject is the question..

Filed under: Unit Testing — ovaisakhter @ 6:51 pm

Some days back I was having a chat with a friend of mine regarding unit test and DI, we were going though his code and we started discussion on some of the service locators in his services code which I thought should also have been injected(DI or IoC), but he disagreed as he thought these locators are generic enough so they do not need to be injected or wrapped or abstracted. In the similar lines one my team members created a static configuration class in the core and was using it to access the configuration for the application, which started the discussion on how far your should go when it comes to dependency injection.

To answer this question I tried to look into an extreme example in my code and how it paid off in the end.

Recently in a project I wrote some services which were saving certain statistics about a website. An Asp.Net MVC application was calling my application controller service to store the  statistics. These statistics are saved in the context of a Date. In this scenario I can easily use a DateTime.UtcNow.Date inside my service for the Date and be done with it. The challenge comes when you have to write unit tests for this situation. We need to generate some sample data to test the system properly. Considering this situation I created an interface to inject the Date.

public interface IClock
    {
        DateTime Get();
    }

In my unit test project I created an implementation of this such that I can set the Date externally.

Now I created a method in my unit test project

internal class DateProvider : IClock
    {
        public DateTime CurrentDate;

        public DateProvider()
        {
        }

        public DateTime Get()
        {
            return CurrentDate;
        }
    }

I wrote a some code to generate random statistics and recorded the data created in the memory so that I can test it later on. Here is how the code looks like

           var daysToGoBack = random.Next(400, 1000);

           var dateTimeProvider = new DateProvider();
           var externallyControlledActionNotifier = new ExternallyControlledActionNotifier();
           var memorybasedStatisticsLogger = new MemorybasedStatisticsLogger(new IPBasedServerIdentityProvider(),
                                                                             new SiteStatisticsRepository(),
                                                                             externallyControlledActionNotifier, dateTimeProvider);

           for (var i = 0; i < 1000; i++)
           {
               dateTimeProvider.CurrentDate = DateTime.UtcNow.Date.Subtract(TimeSpan.FromDays(random.Next(0, daysToGoBack)));

               memorybasedStatisticsLogger.LogSiteView(surveyConfiguration.RowKey);
               testStatistics.Add(new Statistics { Day = dateTimeProvider.CurrentDate, PageViewed = true })
;

 

so now I am able to generate a random date in the past and I am able  to record in memory the data created so that I can test that correct data was created by my services or not.

As you can see that in this situation injecting a trivial thing like date has saved the day in terms of unit testing. So I believe that you should to inject every possible dependency as a convention, it may come handy at some time….

September 2, 2011

AppHarbor: Azure done Right(Simple)

Filed under: Cloud Computing — ovaisakhter @ 4:42 pm

Recently my boss heard something about a new cloud solution for Microsoft .Net applications. His description was “these guys I know have shifted from Azure to this new platform AppHarbor, they say it is much better and cheaper also, I think we should look into it”.

So I looked for the name and found the website www.appHarbor.com and the first thing that caught my attention was the slogan “Azure done right”, a pretty hefty claim I must say.

Development & Deployment

When you start looking into the platform the first thing you will observe is that the platform is very developer centric (which kind of makes sense). Startup time or learning curve to host your first application can be from little to almost none. Small if you have not used git(www.github.com), and none if you have used it.

So the idea is that you create an application on appharbor website, create a solution in visual studio, map these two things with git commands, push your code using Git , appharbor compiles it and executes the unit tests and deploys it. You can read more on

http://support.appharbor.com/kb/getting-started/deploying-your-first-application

and yes there is not additional requirements like you have in Azure. No special Apis, no special project types.

Scalability

By default you have one instance of an application and you can simply scale by providing the number of instances you want to run. The traffic will be routed between these instances by a load balancer.

Storage

appharbor provides an option to have SQL server or MySql database, database is free till 20 MB.  You can use the file storage on the servers but this storage is considered temporary and can be reset at anytime so do not get comfy Smile. appharbor recommends to you use some service like Amazon S3 for durable file storage.

Add-Ons

AppHarbor integrates with some service providers to provide you with an option to get additional services in your application, these services are called Add-Ons. These services mainly include NoSQL databases and caching solutions. You can get details from the following link

https://appharbor.com/addon

Mind you that these applications are not hosted at AppHarbor (That’s what I assume at least) which means they are not inside the same network, so Add-Ons like caching solutions seems to loose purpose for me.

Pricing 

AppHarbor provides extremely simple pricing model and enough free offers to help you to play to your hearts desire. You can have multiple applications  and pay nothing if you are using only one instance per application. You start paying 0.05 USD per hour for every additional instance of an application. Database is free till 20MB and you pay 10 USD for 10 GB SQL Server, and everything else is included in the price. More information at

https://appharbor.com/page/pricing 

Conclusion

I think that appharbor is a great offering for the very basic reason that it is good to have a choice. I believe this offering will be more exciting for startups, individuals and small organizations. I can almost say that this is a poor man’s (or a developers Smile) cloud.

As a software developer the working experience with appharbor is much better than Azure and in this sense they really are right in saying that “Azure made right” Smile

Create a free website or blog at WordPress.com.