Thursday, 25 August 2016

make MVC Web API available with method name and its parameters

Technology: MVC, WEB API , .NET


Steps:

  1. Open the web API solution.
  2. expand folder named "App_Start"
  3. Open file named "RouteConfig"


Replace below method:


  public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }


Download blob from Azure storage

Technology : Azure, Azure Storage

Name Spaces Required:

using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;

       

        public async Task<string> GetBlobData()
        {
            string AccountName = "Azure Storage Name";
            string AccountKey = "Azure storage Key";
            string ContainerName = "Container name";
            //StorageCredentials credentials = new StorageCredentials(AccountName, AccountKey);

            string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            var blobClient = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(storageConnectionString).CreateCloudBlobClient();
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer _BlobContainer = blobClient.GetContainerReference(ContainerName);
            OperationContext context = new OperationContext();
            BlobRequestOptions options = new BlobRequestOptions();
            BlobResultSegment blobSeg = await _BlobContainer.ListBlobsSegmentedAsync(null, true, BlobListingDetails.All, null, null, options, context);
            CloudBlockBlob result = null;
            foreach (CloudBlob tempObj in blobSeg.Results)
            {
                if (tempObj.Properties.LastModified == DateTime.Now)
                    result = (CloudBlockBlob)tempObj;
            }
            string resultContent =await result.DownloadTextAsync();
            //List<CloudBlob> lstBlobs= blobSeg.Results.Where(x=>x.)


            return resultContent;

        }

Generate SAS token to access Blobs/Container from Azure storage

Technology: Azure Storage, SAS token 

Name Spaces Required: 


using Microsoft.WindowsAzure.Storage.Blob;


            string AccountName = "Azure storage Name";
            string AccountKey = "Azure storage key";
            string ContainerName = "Container Name";

            string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            var blobClient = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(storageConnectionString).CreateCloudBlobClient();
            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer _BlobContainer = blobClient.GetContainerReference(ContainerName);
            CloudBlockBlob blob = _BlobContainer.GetBlockBlobReference("Blob Name"); //Enter blob name for which SAS token need to be generated
            string url = "";
             string token=GetContainerSasUri(_BlobContainer); // container level SAS token
             url = await GetBlobSasUri(_BlobContainer); // blob level SAS token 


       static string GetContainerSasUri(CloudBlobContainer container)
        {
            //Set the expiry time and permissions for the container.
            //In this case no start time is specified, so the shared access signature becomes valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
            sasConstraints.Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List;

            //Generate the shared access signature on the container, setting the constraints directly on the signature.
            string sasContainerToken = container.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            return container.Uri + sasContainerToken;
        }


        static async Task<string> GetBlobSasUri(CloudBlobContainer container)
        {
            //Get a reference to a blob within the container.
            CloudBlockBlob blob = container.GetBlockBlobReference(ImageName);

            //Upload text to the blob. If the blob does not yet exist, it will be created.
            //If the blob does exist, its existing content will be overwritten.
            //string blobContent = "This blob will be accessible to clients via a Shared Access Signature.";
            //MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(blobContent));
            //ms.Position = 0;
            //using (ms)
            //{
            //    await blob.UploadFromStreamAsync(ms);
            //}
            //byte[] imagebytes=null;
            //await blob.DownloadToByteArrayAsync(imagebytes, 0);
            


            //Set the expiry time and permissions for the blob.
            //In this case the start time is specified as a few minutes in the past, to mitigate clock skew.
            //The shared access signature will be valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5);
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
            sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write;

            //Generate the shared access signature on the blob, setting the constraints directly on the signature.
            string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            return blob.Uri + sasBlobToken;
        }

Authenticate windows 10 app with Azure AD (WAM)

Technology: Windows 10 Apps, Azure AD, WAM

Required Name Spaces:

using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web;
using Windows.Security.Authentication.Web.Core;
using Windows.Security.Credentials;



        
        public static string AdalClientId = App.clintID; //clientID from Azure AD
        public static string AdalResourceId = App.ServiceResourceUrl; // Web api Service appID from Azure AD
        const string MicrosoftAccountProviderId = "https://login.microsoft.com";
        public string AdalIssuerAuthority = "https://login.windows.net/contoso.onmicrosoft.com";
        
        string URI = string.Format("ms-appx-web://Microsoft.AAD.BrokerPlugIn/{0}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); //URI need to enter while registering into Azure AD
        string szReturnUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;
        AuthenticationResult AResult;
        public async Task<string> Authenticate(bool prompt)
        {
            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, AdalIssuerAuthority);

            try
            {
                WebTokenRequest webTokenRequest = new WebTokenRequest(provider, "", AdalClientId);

                // webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
                webTokenRequest.Properties.Add("resource", App.ServiceResourceUrl);

                // If the user selected a specific account, RequestTokenAsync will return a token for that account.
                // The user may be prompted for credentials or to authorize using that account with your app
                // If the user selected a provider, the user will be prompted for credentials to login to a new account
                WebTokenRequestResult webTokenRequestResult;
                if (prompt)
                {
                    webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);


                    ////result = await context.AcquireTokenAsync(AdalResourceId, AdalClientId, _returnUri, PromptBehavior.Auto, objUserIdtfr, "domain_hint=microsoft.com");
                }
                else
                {
                    webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
                }
                // If a token was successfully returned, then store the WebAccount Id into local app data
                // This Id can be used to retrieve the account whenever needed. To later get a token with that account
                // First retrieve the account with FindAccountAsync, and include that webaccount 
                // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                  
                    App.AccessToken = webTokenRequestResult.ResponseData[0].Token;

                    string szUserinfo = webTokenRequestResult.ResponseData[0].WebAccount.UserName;
                    if (!szUserinfo.ToLower().Contains("microsoft.com"))
                    {
                        await Utils.ShowPopUp("Not a valid user. App now exits");
                        Windows.UI.Xaml.Application.Current.Exit();
                    }
                    if (!string.IsNullOrEmpty(szUserinfo) && szUserinfo.Contains("@"))  //TODO: This is not always alias, for some users emailid and alias is differnt
                        App.szUserAlias = szUserinfo.Split('@').First();

                    App.szUserName = App.szUserAlias;
                    
                }

Monday, 15 August 2016

Get Client ID for your app from Azure AD

Technology: Azure , Azure AD


Step 1:

Log into the Azure portal using link https://manage.windowsazure.com/  and log in with your credentials.

Step 2:

Select "Active Directory" option from side menu



Step 3:

Select an Active Directory and click on "Applications " as shown in below screen shot.








Step 4: Click on "Add" option from the bottom bar. This will provide you with option to register your application as shown below



 
     Enter a name for your application registration.
   

     select an option based on your application type












Step 5: After entering details, click on "arrow" button to continue and you can see below screen.

for web applications: 



Enter web app URL in "sign on URL".

Enter a unique name in "App ID URI"

Then click on "Tick" button which is present at the bottom right corner to complete the registration.  











for Native client apps:




Enter Redirect URI which can get from your client code.


Then click on "Tick" button which is present at the bottom right corner to complete the registration.  










Step 6:

Click on "Configure" tab and there you can find your app client ID as shown in below screenshots.




Note: If you have any doubts please ask in comments.