The Case of REST & Azure Resource Manager APIs

There are two kinds of people in this world. One who love ready made SDKs and then there are others who love to work on pure REST APIs. I’m from the 1st category. :)

The reason behind using SDKs is they include pure abstracted API calls. For example, if you use Active Directory Authentication Library (ADAL), it has AcquireTokenAsync method. This method, if you call, takes just couple of lines of code and makes your life much more easier.

However, behind the scenes, this method does a lot of stuff. For example, in case of Windows apps: calling WebAuthenticationBroker, launching Web UI, handling app navigation, etc. Similarly, it does same thing, in iOS and Android. But that entire code base is repetitive in every app which is going to use Active Directory for login. Now, one may ask, why so many calls are made just to authenticate and acquire token or as we progress through this blog post, why so many calls are required to perform basic operations. The answer lies in purity of REST APIs. And ADAL makes life easier here by providing one method doing all this for you while abstracting all the details.

When I was working on my blog post Monitor Azure Resource Usage and Predict Expenses, there was no SDK available for Azure Resource Manager (ARM) and the old API was not an ideal way to handle Resource Management APIs.

So, I had to write an app from scratch to get ARM working in my sample and here my friend Gaurav Mantri (@gmantri) helped me a lot. Gaurav founded Cloud Portam, which helps to manage resources in Azure like Storage, Search, etc… Thanks to him, I could understand the flow and I’m going to put it here on this blog post.

Step 1: Authenticate with Common

ARM allows you to manage resources within subscription and subscription is now part of your Active Directory. So, the first thing that you need to do is to authenticate with right Active Directory. This is simple if you’ve just one subscription and one Active Directory in your subscription, but if you’ve multiple subscriptions/active directories, you may want to iterate through them and get separate access tokens. To avoid this, first we hit the ‘common’ endpoint and then get the Tenants available.

Step 2: Get Tenants

As a user, your user account may be associated with multiple active directories. A tenant is nothing but an active directory to which you have access. Here, in this step we get all active directories first by calling below method. Later on we’ll try to fetch subscription (if available) from each directory.

private async Task GetTenants()
{
var requestUrl = "https://management.azure.com/tenants?api-version=2015-01-01";
try {
var tenantResponse = await client.GetStringAsync(requestUrl);
tenantCollection = JsonConvert.DeserializeObject<TenantResponse> (tenantResponse);
}
catch (Exception ex) {
await DisplayAlert("Error!", ex.Message, "Dismiss");
}
foreach (var tenant in tenantCollection.TenantCollection) {
await GetSubscriptions (tenant.TenantId);
}
}

Step 3: Get Subscriptions

Once we get tenants, each tenant may have subscription on which we may want perform some actions. To do so, we pass each tenant ID from GetTenants() to this method and acquire new token silently (without login prompt)

private async Task GetSubscriptions(string tenantId)
{
var requestUrl = "https://management.azure.com/subscriptions?api-version=2015-01-01&quot;;
try {
var data = await DependencyService.Get<IAuthenticator> ().AuthenticateSilently (tenantId,
App.ManagementResourceUri, App.ClientId);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", data.AccessToken);
var subsriptionResponse = await client.GetStringAsync (requestUrl);
var subscriptions = JsonConvert.DeserializeObject<SubscriptionResponse>(subsriptionResponse);
foreach (var subscription in subscriptions.SubscriptionCollection) {
SubscriptionCollection.Add(subscription); }
IsFirstRunComplete = true; }
catch (Exception ex) {
await DisplayAlert("Error!", ex.Message, "Dismiss"); }
}

Step 4: Call ARM APIs

In order to perform management operations on an Azure Subscription, a user must be authenticated and authorized. Authentication part is handled by Azure Active Directory. There is a one to many relationship between an Azure AD and Azure Subscription. i.e. an Azure AD can be used as an authentication store for many Azure Subscriptions however authentication for an Azure Subscription can happen only with a single Azure AD. Once a user is authenticated with an Azure AD, next step is to find out a list of Azure Subscriptions the logged in user has access to. This is what we’re doing in this step. What a user can do in each of these subscriptions (i.e. the authorization part) can be accomplished by using Azure Resource Manager (ARM) API’s Role-based access control (RBAC).

var requestUrl = String.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Commerce/UsageAggregates?
api-version=2015-06-01-preview&reportedStartTime={1}&reportedEndTime={2}&aggregationGranularity=Daily&showDetails=false",
App.SelectedSubscription.SubscriptionId, startTime, endTime);
var usageData = await client.GetStringAsync (requestUrl);
var data = JsonConvert.DeserializeObject<AzureTracker.Model.UsageResponse> (usageData);

Now you can replace your code in Step 4 to manage or monitor resources in your Azure subscription, but the flow will not change. The entire list of APIs covering resources and possible operations on them is available here

I hope this post will helps you to understand the model behind ARM API calls.

Namaste,
Mayur Tendulkar

Experience with Crystal Reports printing on Dot Matrix Printer

Since few months, I was working on a project which involved migrating Cobol based ERP application to .NET. It includes writing object oriented code, creating RDBMS database and import data from old files (flat files actually) to this database. And finally generate reports and bills (in huge amount, hundreds of pages at a time)

I have been using Crystal Reports (CR) since a long time, so I decided to go for it. CR is the best tool for designing reports. Its easy and support many export formats. The most exciting thing is – it comes bundled with Visual Studio for evaluation purpose. Hence, I could evaluate it before purchasing.

So, I designed the reports and tested it on regular laser/ink jet printers – it was perfect. The formatting, printing speed and page-breaks was as expected.

In India (as per my knowledge and requirements of this application), even though we talk about e-Governance and paperless office, to submit reports to government (or to be specific RG32 report) it must be in triplicates (on different colour paper). So, laser/inkjet printers was no option and It was a costly solution. Hence, we had to depend on dot matrix printer. But, problems like – the speed of printing which was very slow, formatting which was very dark and incorrect page-breaks on continuous paper were introduced when I printed the same reports on dot matrix printer. The problem is mentioned here and here on MSDN

So, I checked many options (as listed below) from various sources (SAP Forum, MSDN Forum, other software products in same category, etc).

  • I tried exporting report to given formats (Word, Excel, PDF) but the same problem of printing speed, incorrect formatting and incorrect page-breaks remained as it is – unsolved.
  • Some software products used to export the report data to DOS and print from there. This wasn’t feasible for me and didn’t want to do this. Because, actually I was migrating DOS based application to Windows.
  • Install correct printer drivers was one solution. So, I tried latest drivers from manufacturer as well as drivers which comes bundled within Windows. But, it wasn’t the solution. The problem was still there.
  • On some forums (link here), I found out that we need to install Generic/Text printer driver. This will give option to use Draft font with Character Per Inch (CPI) size required for dot matrix printers. The report in viewer showed correctly, but on printer – the same problem.

At last, I found one solution (listed here) which exports the report to text format and print it directly. But then the code was showing error on line

ExportOptions.CreateTextFormatOptions.CharactersPerInch = 16

After searching a lot, I found (actually a reply to my question on SAP Forum) that, the version of CR which comes with VS2008 is BASIC. It doesn’t have export to text functionality (!). I’ll need to upgrade to CR2008 Full. Hence I upgraded to the full version and tested the code mentioned at this link 

And Bingo! I was able to export the raw data to text file and print it directly. And everything (font, formatting, page breaks, speed) was as expected.

There were many other issues which came into picture when I upgraded to full version of CR, like it doesn’t integrate well with VS2008. I needed SP0 of CR2008 to do this integration, then deployment of CR2008 runtime on client machines. But these issues were not of much headache and importance. These all issues are now got resolved and now my project is in testing and final data migration phase.

It is also scheduled for next version with additions of new functionalities.

When people are happy, I’m happy Smile

I hope, this will help developers, who are interested in building applications which involves reporting and printing these reports on dot matrix printers.

Namaste

Mayur Tendulkar | www.mayurtendulkar.com

WCF Se Maine Pyar Kiya Tak :)

Today, we’re going to understand a new concept and for that matter, you must be familiar to Bollywood and movies like ‘Maine Pyar Kiya’ (MPK). You can say this as a pre-requisite.

In MPK, there was a situation, where hero and heroine were separated a distance apart. Then heroine used to send ‘Love Letters’ using pigeon postal service. And she used to sing a song for that matter – ‘Kabootar Ja Ja Ja

Untitled-1

Now, Windows Communication Foundation (WCF) is a unified programming model to build distributed applications. In our scenario, Sallu is providing his ‘best love’ services (pyar, daulat, shoharat, etc…) and Bhyagyashree is going to consume those.

Here hero and heroine are at two distant places and we call it as end-points. And, if they want to communicate, they must have ABCs i.e.

  1. A for Address on which she will send a letter, look at Sallu’s address
  2. B for Binding which defines how they communicate – here ‘OnAirBinding’ or Pigeon is used
  3. C for contract, the contract between Sallu and Bhagyashree says, if Bhagyashree wants Sallu to bestow all romantic poems, letters on her, she must send a love letter to him, kind of.

This scenario depicts the basic peer-to-peer communication in WCF (oops Bollywood movies). Here, in this mode of communication Salman is service provider and Bhagyashree is consumer, but sometimes situation can be other way round. And it’s very much possible.

image

In this new picture, what do you understand?

Well, WCF is not just about peer-to-peer applications. But can be used in many different applications as well. In this case Salman is a service provider (or publisher) and Aish, Kat and Bhyagyashree are service consumers (or subscribers). They are registered with Salman for his ‘best’ services.

But to provide these services, everyone needs to have ABCs.

  1. A – Address. Everyone will have a unique address for communication purpose
  2. B – Binding. Everyone will have their own mode of communication. In previous case it was Pigeon service, now it’s Email, Phone, Mobile and what not. WCF provides bindings like Http, TCP/IP, etc…
  3. C – Contract. All these actresses will have their own terms and conditions to work with Salman. And these terms and conditions will be put into contracts.

The main advantage of WCF is – it can communicate with any other technology. That means, WCF can communicate with .NET Managed based applications, Native applications, J2EE based applications.

To consume WCF services, client creates a proxy object of the service (mostly called as ‘ServiceClient’). In our scenario, all the gals will be having their own ‘personal copy’ of Salman Khan; however, original Salman is totally different. It’s like Salman will be having clones to enjoy himself with his girlfriends. Remember Dev Anand in ‘Teen Devian’? Nice idea, if we could implement in our world.

Probably, I’ll share some technical examples in next few posts. But, after this, you can see the how WCF works.

Enjoy.

Namaste

Mayur Tendulkar | www.mayurtendulkar.com