Uncategorized

Securing Azure Web Services with AAD and accessing from CRM Online / Daemon applications

For Integrating CRM with outside world you might want to off load some of your work to Azure App services.

Azure Active Directory is one of the options for securing your Azure services so that they can be accessed only from Clients with Authentication credentials and Authorization to access the service.

There are a number a steps you need to follow in order to setup AAD and access them from CRM:

  1. First step is to Register the App Service in the same Tenant as your CRM Online instance
    1. This will generate 4 Authentication keys/ config items :
      1. ClientId – To identify the App
      2. Audience – Also known as the App Id URL, must be unique within your AAD
      3. Tenant – Same as your CRM Online Tenant
      4. Secret – More of a password
  2. Enable CORS in your Azure application
    1. clip_image001
    2. Here * indicates allow all origins.
  3. Enable CORS in the browser in case you would be accessing the service from Javascript.
    1. This is how you do it in IE
      1. clip_image002
  4. Register your Client Application as a Web Application in same AAD. Give access to the Service we Registered in the 1st step.

Now let us see some code for accessing Azure services from Javascript and Plugins:

Here’s the javascript code:

  $.ajax({
              type: "POST",
              contentType: "application/x-www-form-urlencoded",
              datatype: "json",
              data: {
                  "grant_type""client_credentials",
                  "client_id": {clientId},
                  "client_secret": {secret},
                  "resource": {resource}
              },
              crossDomain: true,
              url: "https://login.windows.net/" + tenant + "/oauth2/token",
              success: function (data, textStatus, xhr) {
                  debugger;
 
                  //alert(data.access_token);
                  var access_token = data.access_token;
                  contactId = contactId.toString().substring(1, contactId.toString().length - 1);
                    var url = { Service URL};
                  url = url + "/{End Point};
                  $.ajax({
                      type: "GET",
                        data: "{}",
                        cache: false,
                        contentType: "application/json; charset=utf-8",
                        datatype: "json",
                        url: url,
                        async: true,
                        beforeSend: function (xhr) {
                          xhr.setRequestHeader("Accept""application/json");
                          xhr.setRequestHeader("Authorization"'Bearer ' + access_token);
                      },
                        success: function (data, textStatus, xhr) {
                            if (onSuccessCallback != null) {
                              onSuccessCallback(returnValue, textStatus);
                          }
                      },
                        error: function (xhr, textStatus, errorThrown) {
                            if (onErrorCallback != null) {
                              onErrorCallback(errorThrown, textStatus);
                          }
                      }
                  });
 
              },
              error: function (xhr, textStatus, errorThrown) {
                  // alert("failure");
              }
          });

Plugin/C# code:

var t = token.Result;
 
           using (WebClientEx client = new WebClientEx())
           {
               client.Timeout = 5 * 1000 * 60;
               client.Headers.Set("Content-Type""application/xml");
               client.Headers.Set("Authorization""Bearer " + t.access_token);
               var byteArray = Encoding.UTF8.GetBytes(transformedMessage);
               response = client.UploadData(baseUrl + "api/"+ endPoint + "/""POST", byteArray);
               responseString = Encoding.UTF8.GetString(response);
           }
public static class AzureUtility
  {
 
      public async static Task<AzureAccessToken> CreateOAuthAuthorizationToken1(string clientId, string clientSecret, string resourceId, string tenant)
      {
          AzureAccessToken token = null;
          string oauthUrl = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenant);
          string reqBody = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&resource={2}", Uri.EscapeDataString(clientId), Uri.EscapeDataString(clientSecret), Uri.EscapeDataString(resourceId));           
          HttpClient client = new HttpClient();
          HttpContent content = new StringContent(reqBody);
          content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
          using (HttpResponseMessage response = await client.PostAsync(oauthUrl, content).ConfigureAwait(false))
          {
              if (response.IsSuccessStatusCode)
              {
                  DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AzureAccessToken));
                  Stream json = await response.Content.ReadAsStreamAsync();
                  token = (AzureAccessToken)serializer.ReadObject(json);
              }
          }
          return token;
      }
 
  }
public partial class Startup
      {
          // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
          public void ConfigureAuth(IAppBuilder app)
          {
              app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                  new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                  {
                      Tenant = ConfigurationManager.AppSettings["Tenant"],
                      TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidAudience = ConfigurationManager.AppSettings["Audience"]
                      },
                  });
          }
      }

 

You would also have to configure your App service to use Windows Azure Active Directory as Authentication mechanism:

public partial class Startup
      {
          // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
          public void ConfigureAuth(IAppBuilder app)
          {
              app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                  new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                  {
                      Tenant = ConfigurationManager.AppSettings["Tenant"],
                      TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidAudience = ConfigurationManager.AppSettings["Audience"]
                      },
                  });
          }
      }
Standard
Uncategorized

Triggering Azure Web Jobs manually

Web jobs are mostly scheduled i.e. they are triggered at a particular time of the day/ weekly etc., but at times you would require to trigger a batch job manually (A use case would be to test the functionality of the web job after deployment or if the customer wants the job to be run on ad-hoc basis as per need. We could also have a button in CRM which can trigger the web job).

Triggering a web job is nothing but a Http Post call to a URL, passing along the Authorization header.

These are the following options to trigger the web job manually:

From the portal

The easiest way to run the job is to do it from the portal, this is mostly helpful during Integration activities where in you want to test the functionality of the job after deployment or any change in related services.

Go to Azure Portal => App service (Web site) used to host the web job => Web Job you want to trigger manually and hit Run.

clip_image002

 

Using a Web Debugging tool like Fiddler

From fiddler you can create a Http Post request and encode the Username/Password using the Text wizard to base64 string.

clip_image004

clip_image006

 

Using C# code

If you want to trigger the job on execution of a plugin in CRM , you can do so using C# code or for that matter any server side code:

  HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(https://%5BWebsite Name].scm.azurewebsites.net/api/”);

 

            var byteArray = Encoding.ASCII.GetBytes(“[username:password]”);

 

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Basic”, Convert.ToBase64String(byteArray));  

       

            var response = await client.PostAsync(“triggeredwebjobs/[WebJob name]/run”, null);

 

 

[Website Name]: This is the Website used to Host the WebJob.

[username:password]: You can get the username/password combination to access the batch job from the Azure portal by first going to the website used to host the batch job and then selecting your batch job. You will find the Username/Password combination in the properties section:

clip_image008

clip_image010

Using Javascript

var clientId = “[Username]”;

var clientSecret = “[Password]”;

 

var authorizationBasic = $.base64.btoa(clientId + ‘:’ + clientSecret);

 

var request = new XMLHttpRequest();

request.open(‘POST’, [Website Name], true);

request.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded; charset=UTF-8’);

request.setRequestHeader(‘Authorization’, ‘Basic ‘ + authorizationBasic);

request.setRequestHeader(‘Accept’, ‘application/json’);

request.send(null);

 

request.onreadystatechange = function () {

    if (request.readyState == 4) {

    alert(request.responseText);

    }

};

Standard
Azure, Uncategorized

How to deploy a Web Application to Azure using Powershell

I have been using this ps script to deploy a webapp/ webapi to Azure using Powershell. It has minimal configuration but the commands allow you to define everything from Resource Group to scaling options for that matter if there is a need.

  1. PS D:\Deploy> $WebSiteLoc=”East US”
  2. PS D:\Deploy> $WebSiteName = “PowershellTrialSaurabh”
  3. PS D:\Deploy> Test-AzureName -Website $WebSiteName
    False
  4. PS D:\Deploy> New-AzureWebsite -Location $WebSiteLoc -Name $WebSiteName

Instances : {}
NumberOfWorkers : 1
DefaultDocuments : {Default.htm, Default.html, Default.asp, index.htm…}
NetFrameworkVersion : v4.0
PhpVersion : 5.4
RequestTracingEnabled : False
HttpLoggingEnabled : False
DetailedErrorLoggingEnabled : False
PublishingUsername : $PowershellTrialSaurabh
PublishingPassword : EFWilNQrGDMoeYh1oemrku0NSn47h2P8SiPgPDaulebANQzlefzz0qFLTppQ
AppSettings : {WEBSITE_NODE_DEFAULT_VERSION}
Metadata : {}
ConnectionStrings : {}
HandlerMappings : {}
Name : PowershellTrialSaurabh
State : Running
HostNames : {powershelltrialsaurabh.azurewebsites.net}
WebSpace : saurabhfirstmvcsample-RG-EastUSwebspace
SelfLink : https://waws-prod-blu-053.api.azurewebsites.windows.net:454/subscriptions/a866dc2f-b0
ec-4247-80d2-80a365738118/webspaces/saurabhfirstmvcsample-RG-EastUSwebspace/sites/Pow
ershellTrialSaurabh
RepositorySiteName : PowershellTrialSaurabh
Sku : Free
UsageState : Normal
Enabled : True
AdminEnabled : True
EnabledHostNames : {powershelltrialsaurabh.azurewebsites.net,
powershelltrialsaurabh.scm.azurewebsites.net}
SiteProperties : Microsoft.WindowsAzure.Commands.Utilities.Websites.Services.WebEntities.SitePropertie
s
AvailabilityState : Normal
HostNameSslStates : {powershelltrialsaurabh.azurewebsites.net,
powershelltrialsaurabh.scm.azurewebsites.net}
AzureDriveTraceEnabled :
AzureDriveTraceLevel : Error
AzureTableTraceEnabled :
AzureTableTraceLevel : Error
AzureBlobTraceEnabled :
AzureBlobTraceLevel : Error
ManagedPipelineMode : Integrated
WebSocketsEnabled : False
RemoteDebuggingEnabled : False
RemoteDebuggingVersion :
RoutingRules : {}
Use32BitWorkerProcess : True
AutoSwapSlotName :
SlotStickyAppSettingNames : {}
SlotStickyConnectionStringNames : {}

6. PS D:\Deploy> Show-AzureWebsite $WebSiteName
7. PS D:\Deploy> $path = “D:\Deploy\sampleazureapp.zip”
8. PS D:\Deploy> Publish-AzureWebsiteProject -Name $WebSiteName -Package $path
Change Summary:
Bytes Copied: 23380708
Files Added: 108
Files Updated: 4
Files Deleted: 1
Errors: 0
Warnings: 0
Parameters Changed: 0
Total No of Changes: 113

Standard
Uncategorized

Heap Data Structure using C#

Heaps are the implementation of the Abstract Data Structure Priority Queue.

Heaps are very useful in scenarios where we want to get the Minimum or Maximum of a set of objects in O(1) time (constant time).

I will be discussing implementing Heaps using Arrays which would account for most of the use cases except when the number of objects are not known before hand, then you use a Linked List as it’s internal DS.

There are two types of Heaps:

  • Max Heaps – Used when we want to get the Max in constant time
  • Min Heaps – Used when we want to get the Min in constant time

Let us first see how to code Max Heaps in C#:

namespace DSAndAlgorithms.DataStructures.Heaps
{
    public class MaxHeap
    {
        public MaxHeap(int[] input, int length)
        {
            this.Length = length;
            this.Array = input;
            BuildMaxHeap();
        }
 
        public int[] Array { getprivate set; }
 
        public int Length { getprivate set; }
 
        private void BuildMaxHeap()
        {
            for (int i = this.Length / 2; i > 0; i--)
            {
                MaxHeapify(i);
            }
 
            return;
        }
 
        public void MaxHeapify(int index)
        {
            var left = 2 * index;
            var right = 2 * index + 1;
 
            int max = index;
            if (left <= this.Length && this.Array[left - 1> this.Array[index - 1])
            {
                max = left;
            }
 
            if (right <= this.Length && this.Array[right - 1> this.Array[max - 1])
            {
                max = right;
            }
 
            if (max != index)
            {
                int temp = this.Array[max - 1];
                this.Array[max - 1= this.Array[index - 1];
                this.Array[index - 1= temp;
                MaxHeapify(max);
            }
 
            return ;
        }
 
        public int RemoveMaximum()
        {
            int maximum = this.Array[0];
 
            this.Array[0= this.Array[this.Length - 1];
            this.Length--;
            MaxHeapify(1);
            return maximum;
        }
    }

Now let us see How to code MinHeaps using C#:

namespace DSAndAlgorithms.DataStructures.Heaps
{
    public class MinHeap
    {
        public MinHeap(int[] input, int length)
        {
 
            this.Length = length;
            this.Array = input;
            BuildMinHeap();
        }
 
        public int[] Array { getprivate set; }
 
        public int Length { getprivate set; }
 
        private void BuildMinHeap()
        {
            for (int i = this.Length / 2; i > 0; i--)
            {
                MinHeapify(i);
            }
 
            return;
        }
 
        public void MinHeapify(int index)
        {
            var left = 2 * index;
            var right = 2 * index + 1;
 
            int Min = index;
            if (left <= this.Length && this.Array[left - 1< this.Array[index - 1])
            {
                Min = left;
            }
 
            if (right <= this.Length && this.Array[right - 1< this.Array[Min - 1])
            {
                Min = right;
            }
 
            if (Min != index)
            {
                int temp = this.Array[Min - 1];
                this.Array[Min - 1= this.Array[index - 1];
                this.Array[index - 1= temp;
                MinHeapify(Min);
            }
 
            return;
        }
 
        public int RemoveMinimum()
        {
            int Minimum = this.Array[0];
 
            this.Array[0= this.Array[this.Length - 1];
            this.Length--;
            MinHeapify(1);
            return Minimum;
        }
    }
}

}

Final Words:

As I said Heaps are important when all we care to know is Max/Min in constant time. Heap DS is used in many optimizing algorithms like Minimum Spanning Trees etc.
Also Heap Sort uses the same Heap DS internally to get Maximums or Minimums and then Rebuilding the Heap again which takes O(NLogN) time in all and additional benefit that you get is there is no additional memory required for sorting( But keep in mind Heap Sort ins’t stable :-))

Standard
Uncategorized

How to allow only a single instance of the application to be run using Mutex

There are different types of Locks in C#, one of the interesting one’s is the Mutex.

The characteristic of a Mutex which stands out is that it can be used to synchronize threads across processes.

 

One of the application of the Mutex is to force running of only single instance of an Application. Let us see how we can achieve this using a Mutex.

using System;
using System.Threading;
 
namespace OnlyOneApplicationUsingMutex
{
    class Program
    {
        static void Main(string[] args)
        {
            var mutex = new Mutex(false"OnlyOneApplicationUsingMutex");
 
            if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
            {
                Console.WriteLine("Another Instance of the application is already running. Press any key to exit!!!!");
  Console.ReadLine();
                return;
            }
 
            StartApplication();
        }
 
        private static void StartApplication()
        {
            Console.WriteLine("Application started");
            Console.ReadLine();
        }
    }
}

 

First instance of the Application:

mutex1

 

Second Instance of the Application:

 

mutex2

 

Final words

The only thing to keep in mind about  Mutexes is that they are slow, around 50 times slower than the Lock (Monitor.Enter / Monitor.Exit), So use Mutexes only when synchronization across processes is required. Also, in order to do so, make sure you name your Mutex to be able to refer to it from the other process.

Standard
Algorithms, C#, Uncategorized

Bit manipulation to the rescue in C#. Reducing Space/Time complexity using Bit Manipulation

Why

Bit manipulation is fun and still  relevant in the realm of C#. You can do things in a way that can increase performance substantially or simplify an algorithm in hand.

Bit manipulation also in certain scenarios helps to save memory, take for example if you want to store multiple flags (True/False values) the most obvious solution would be to use a list of bool types. This may seem to be OK but takes 1 byte per flag. If you are working with 30 flags in hand, you can use an Int32 type in .Net and use its bit values to store 1 for truthy values and 0 for falsy values (often referred as using  bits of an Integer to represent a Set)

So although it’s not imperative to know Bit Manipulation but it can really come to rescue in some corner cases as we plan to see in this blog post.

 

Bitwise Operators

Before diving deep into scenarios where Bit manipulation can come to rescue let’s look into various Bitwise operators so that we all start on the same page:

 NOTE: I am using 8 bits to explain the concepts.

The .Net int type is a  32 bit integer, but the concepts would remain the same 

Bitwise Compliment
/*Bitwise Compliment
             * 1  = 00000001
             * ~1 = 11111110 (In 2's compliment representation this is -2) 
             * ------Explanation of -2:---------
             *  2 = 00000010
             * -2 = 11111101 +1 = 11111110
             */
            Console.WriteLine(~1);
 
 
Bitwise And / Set Intersection

            /*Bitwise And 
             * 1  = 00000001
             * 2  = 00000010
             * 1&2= 00000000 = 0
             */
            Console.WriteLine(1 & 2);
 
Bitwise Or / Set Union
 
            //Bitwise Or
            //1  = 00000001
            //2  = 00000010
            //1|2= 00000011 = 3
            Console.WriteLine(1 | 2);
 
 
Bitwise XOR
            /*
               Here's how XOR works:
             * If both operands have a bit set i.e. 1, the result does not 
             * have that bit set.
             * If neither has a bit set, the result still does not have
             * the bit set. 
             * But if one has the bit set, the result is set.
             * XOR is used for checking bit parity
             */
 
 
            //Bitwise XOR
            //1  = 00000001
            //2  = 00000010
            //1&2= 00000011 = 3
            Console.WriteLine(1 ^ 2);
 
Bitwise Shift Operators
One common use of shifting is to access a particular bit, for example, 
1 << a is a binary number with bit a set and the others clear(bits are 
always counted from the least significant bit, which is numbered 0)
 
Bitwise Right Shift

            //Bitwise Right Shift. Right shift is equivalent to division by 2
            //1   = 00000001
            //1>>2= 00000000 = 0
            Console.WriteLine(1 >> 2);
 
Bitwise Left Shift
 
            //Bitwise Left Shift . Left shift is equivalent to multiplying by 2
            //1   = 00000001
            //1<<2= 00000100 = 4
            Console.WriteLine(1 << 2);
 
Flag Enums
 
            // Bitwise OR operator is used for adding a flag to the Enum
            States states = States.AL | States.TN;
 
            CheckStates(states);
 
            states |= States.MN;
 
            CheckStates(states);
 
            states |= States.WI;
 
            CheckStates(states);
 
            // Bitwise ^ operator is used for removing a flag from the Enum
            states ^= States.AL;
 
            CheckStates(states);
        }
 
         private static void CheckStates(States states)
        {
            switch (states)
            {
 
                case States.AL:
                    {
                        Console.WriteLine("AL");
 
                    }
                    break;
                case States.AL | States.TN:
                    {
                        Console.WriteLine("AL, TN");
 
                    }
                    break;
 
                case States.AL | States.MN:
                    {
                        Console.WriteLine("AL, MN");
 
                    }
                    break;
            }
        }

Set Subtraction

// Set Subtraction
Console.WriteLine(a & ~b);

Set subtraction can be easily understood by using a diagram:

Set Subtraction

Set Subtraction

 

Set Negation

// Set Negation
           Console.WriteLine(ALLBITS ^ a);

Here ALLBITS is an integer value, wherein all bits are 1

 

Set Bit

In order to set a bit, use the following:

// Set Bit
            a |= 1 << shift;

Clear Bit

// Clear Bit
           a &= ~(1 << shift);

 

Now let us look into a few problems wherein we can

leverage Bit manipulations to Reduce Complexity of

an Algorithm/ Reduce space requirements of a program.

 

Scenario 1: Reducing Time Complexity

Given two Integers, find whether they are of opposite signs or not.

Here is the obvious solution:

 

public static bool AreIntegersOfOppositeSigns(int a, int b)
       {
           if (a > 0 && b < 0)
           {
               return true;
           }
 
           if (a < 0 && b > 0)
           {
               return true;
           }
 
           return false;
       }

And here is the solution which uses Bit manipulation:

public static bool AreIntegersOfOppositeSignsUsingBitManipulation(int a, int b)
       {
           return (a^b) < 0;
       }

Did you notice the no. Of lines getting reduced? But it’s not just the lines getting reduced, it’s the complexity/

branching which got reduced here.

First solution has 3 branches/paths and 9 operators whereas the 2nd solution has no branching, additionally just 3 operators.

 

Scenario 2: Reducing Space Complexity

Given a String, determine if all of its characters are Unique

Here is one of the solutions wherein we use a Char Array of size 256 (assuming dealing with ASCII) as a HashTable

to figure out if there are any duplicates:

 

public static bool AreUniqueChars(String str)
     {
         var chars = new bool[256];
         for (int i = 0; i < str.Length; i++)
         {
             int val = str[i];
             if (chars[val]) return false;
             chars[val] = true;
         }
         return true;
     }


public static bool AreUniqueCharsUsingBitManipulation(String str)
   {
       int checker = 0;
       for (int i = 0; i < str.Length; ++i)
       {
           int val = str[i] - 'a';
           if ((checker & (1 << val)) > 0) return false;
           checker |= (1 << val);
       }
       return true;
   }

In this scenario we got rid of the Character array that we were using as a HashTable to detect duplicates.

Final Words

We saw two specific scenarios to reduce Space and Time complexity of an Algorithm. I hope you got the idea of the

power of Bit Manipulation and how can we use it to write performant and efficient code.

Standard
Uncategorized

Getting the GetHashCode and Equals Method Implementation right in C#

Why & When…

Let us first understand why and when would you want to override the default behavior of these two methods in the Object class.

Here is the ‘When’:

  •  If your item will be used as a key in a Dictionary or a HashSet<T>. Also when you want to compare elements of a Type by calling equals rather than manually checking for equality.

Here is the ‘Why’:

  •  The Equals() and the GetHashCode() methods are used to derive if two Keys are equal or not in a HashSet and on that basis they land up at a place in the Table or not considered at all in case they are duplicates.

Points to consider while implementing these methods

  • If Equals() return True for two Objects then the Objects must return the same value for GetHashCode()
  • If GetHashCode() returns the same value for two Objects, it is not necessary that the Objects would be equal. Equals method would be called to see if it is a real equality or not.

Let us see an Example

First of all you need to identify the fields of a Type which would uniquely identify your Object. In this example I have considered one of the Data Structures I am currently working with in my Project and here is how it looks like:

/// <summary>
/// This method implements Equality using Value semantics since this class is immutable
/// and "Equals" in our case means that all corresponding Property values are the same
/// </summary>
/// <param name="obj">An instance of a <see cref="Coverage"/></param>
/// <returns>True of the "values" of All properties are the same</returns>
public override bool Equals(object obj)
{
    var criteria = obj as AvailableCoverage;
 
    if (criteria == null)
    {
        return false;
    }
 
    return this.VehicleCoverageCode == criteria.VehicleCoverageCode
           && this.VehicleCoverageLimitCode == criteria.VehicleCoverageLimitCode
           && this.VehicleCoverageDeductibleCode == criteria.VehicleCoverageDeductibleCode
           && this.VehicleId == criteria.VehicleId;
}
 
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// The integer
/// </returns>
public override int GetHashCode()
{
    var hashCode = 37;
 
    if (this.VehicleCoverageCode != null)
    {
        hashCode = (hashCode * 23+ this.VehicleCoverageCode.GetHashCode();
    }
 
    if (this.VehicleCoverageLimitCode != null)
    {
        hashCode = (hashCode * 23+ this.VehicleCoverageLimitCode.GetHashCode();
    }
 
    if (this.VehicleCoverageDeductibleCode != null)
    {
        hashCode = (hashCode * 23+ this.VehicleCoverageDeductibleCode.GetHashCode();
    }
 
    hashCode = (hashCode * 23+ this.VehicleId.GetHashCode();
 
    return hashCode;
}
Standard