Thursday 1 February 2018

Azure Radis Cache Integration In C# Asp.net.

Step1- First add a Class File in your webApplication Name is RadisCacheLayer ->
 //----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Threading;
using StackExchange.Redis;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Text;
using System.Configuration;
using Newtonsoft.Json;
using BusinessEntities;
using System.Net.Http;
using System.Net;
using System.Linq;

namespace WebApplication
{
    public class RadisCacheLayer
    {
        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            //string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
            //return ConnectionMultiplexer.Connect(cacheConnection);
            return ConnectionMultiplexer.Connect("Satya.redis.cache.windows.net ,abortConnect=false,ssl=true,password=gfd5654vcbc5L1XEOq59RAvhgftlA11KcBEMhLmmvkqWpsLC4=");
        });

        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }

        public void ClearCachedTeams(string CacheName)
        {
            IDatabase cache = Connection.GetDatabase();
            cache.KeyDelete(CacheName);
            //cache.KeyDelete("teamsSortedSet");
            //  ViewBag.msg += "Team data removed from cache. ";
        }
    }
}
Step2- Declare Radis cache Object ->
   #region Declare Radeis Object and Set Connection
        IDatabase cache = RadisCacheLayer.Connection.GetDatabase();

    #endregion
Step3- Declare a Class For Example Name is ClsBackgroudLoadData ->
public class ClsBackgroudLoadData
    {

        public string Client_Domain { get; set; }
        public string CompanyBanner { get; set; }
        public string CompanyLogo { get; set; }
        public string CompanyTheme { get; set; }
        public string FavicaIconUrl { get; set; }
        public string CompanyTitle { get; set; }
        public string CompanyColorCode { get; set; }
        public string companytopBorder { get; set; }
        public string poweredImageurl { get; set; }    }
Step4- Get Data from Database and Store Radis cache Object ->
  List<ClsBackgroudLoadData> _objbranding = new List<ClsBackgroudLoadData>();
        private List<ClsBackgroudLoadData> GetAllcompayBrandingData()
        {

            string listvalueallCompanybranding = cache.StringGet("cachecompanyBranding");
            if (listvalueallCompanybranding == null)
            {
                _objbranding = (from m in GetMaster_ERPClient_Member()
                                join n in GetMaster_Login_User() on m.Login_User_ID equals n.Login_User_ID
                                join p in GetMaster_User_Registration() on n.User_RegistrationId equals p.User_RegistrationId
                                join o in GetAllCompanyBranding() on n.Login_User_ID equals o.Login_User_ID
                                select new ClsBackgroudLoadData
                                {
                                    Client_Domain = m.Client_Domain,
                                    CompanyBanner = o.CompanyBanner,
                                    CompanyLogo = o.CompanyLogo,
                                    CompanyTheme = o.CompanyTheme,
                                    FavicaIconUrl = o.FavicaIconUrl,
                                    CompanyTitle = o.CompanyTitle,
                                    CompanyColorCode = o.CompanyColorCode,
                                    companytopBorder = "10px solid" + " " + o.CompanyColorCode,
                                    poweredImageurl = "https://swasherpstorageaccount.blob.core.windows.net/kencentralmasterimage/logo.png",
                                }).ToList();
                if (_objbranding.ToList().Count > 0)
                {
                    cache.StringSet("cachecompanyBranding", JsonConvert.SerializeObject(_objbranding.ToList()), TimeSpan.FromMinutes(20));
                    return _objbranding;
                }
                return _objbranding;
            }
            else
            {
                var UserList = JsonConvert.DeserializeObject<List<ClsBackgroudLoadData>>(listvalueallCompanybranding);
                return UserList;
            }

        }
Step5- Delete Data from Cache ->

        #region..Clear Cache method....
        public void ClearCachedTeams()
        {
            cache.KeyDelete("cachecompanyBranding ");

        }

        #endregion

Dynamically Creating Database Using C# Asp.net Code.

public ActionResult restoreazuredata()
        {
            string dbName = Txtdbnmae.Text;
            string backup = @"CREATE DATABASE [" + dbName + "] AS COPY OF [SatyaMetaData]";// SatyaMetaData Means Exiting Database
            SqlConnection myConn = new SqlConnection("data source=tcp:satya.database.windows.net,1445;persist security info=True;user id=satyauser;password=satyas46;database=master");//Your Connection Connection String

            try
            {
                SqlCommand cmd = new SqlCommand(backup, myConn);
                myConn.Open();
                cmd.CommandTimeout = 10000;
                cmd.ExecuteNonQuery();
                myConn.Close();
                return Json("1");
            }
            catch
            {
                return Json("0");
            }

        }

Creating Azure AD App Registration with PowerShell (Step1 and Step2)

Creating Azure AD App Registration with PowerShell – Part 1

============================
PS C:\Windows\system32> Connect-AzureRmAccount
WARNING: PowerShell version 3 and 4 will no longer be supported
version of PowerShell 5.1


Account          : admin@sdsdsch.onmicrosoft.com
SubscriptionName : Microsoft Azure
SubscriptionId   : 64aeb01f-d-46b0-ba2d-ad0570f72ec2
TenantId         : f49eb909-d-4ad1-8eb0-f17c9247b5dc
Environment      : AzureCloud

PS C:\Windows\system32> Get-AzureRmADServicePrincipal
ServicePrincipalNames : {d-34ce-4eb4-aa6a-70759cbb5e83}
ApplicationId         : d-34ce-4eb4-aa6a-70759cbb5e83
DisplayName           : MicrosoftAzureRedisCache
Id                    : fdeb7159-62ec-4e4d-805b-68ce62dc6f69
Type                  : ServicePrincipal

ServicePrincipalNames : {fc780465-d-40d4-a0c5-307022471b92, https://userrequestsgraphapiep-prd.trafficmanager.net,
                        https://api.securitycenter.windows.com/,
                        https://securitycenter.onmicrosoft.com/windowsatpservice...}
ApplicationId         : fc780465-2017-d-a0c5-307022471b92
DisplayName           : WindowsDefenderATP
Id                    : ff82a263-6561-4d41-92d7-5b396871295b
Type                  : ServicePrincipal
PS C:\Windows\system32> Get-AzureRmADApplication -DisplayNameStartWith TestNewArchitechApp
DisplayName             : TestNewArchitechApp
ObjectId                : 6545a29d-2e67-451f-b118-e0f7b72f7d55
IdentifierUris          : {https://kencloud.in/3472406d-0bc8-466c-a86c-5781d1d8abf4}
HomePage                : http://kennewarchi.azurewebsites.net
Type                    : Application
ApplicationId           : 77624b13-59e7-400d-8590-8fd8561588ed
AvailableToOtherTenants : False
AppPermissions          :
ReplyUrls               : {http://kennewarchi.azurewebsites.net}


===================


When developing Microsoft cloud solutions, Azure Active Directory is very important. Not only for user accounts, but also for registering your app. With this app you provide secure sign in and authorization for its services. This first of 2 articles describes how to register your app using PowerShell instead of manually clicking it all together in the Azure Management Portal.






Module AzureAD

Before we can use the required cmdlets assure you have the AzureAD module installed. Run Windows PowerShell as an Administrator and execute the cmdlet Install-Module AzureAD


(Note: you may need to add the parameter –Force if you have a previous version installed)
Once the module is installed, connect to your Azure AD using the cmdlet Connect-AzureAD



If your account has access to multiple tenants, then you need to supply the correct tenantId as well.
1
Connect-AzureAD -TenantId 469e5440-f229-44f8-bed2-c32cdd34d90a
You can find the correct TenantId value in the Azure Portal, under Azure Active Directory and then properties. It’s the Directory ID:



Creating your first Azure AD App Registration

We are using the cmdlet New-AzureADApplication. For this we need to following pieces of information: the name of the application and the IdentifierURI.
1
2
3
4
5
6
$appName = "MyApplication"
if(!($myApp = Get-AzureADApplication -Filter "DisplayName eq '$($appName)'"  -ErrorAction SilentlyContinue))
{
    $myApp = New-AzureADApplication -DisplayName $appName -IdentifierUris $appURI
}
Voilà.
But of course, you need more. What about the Homepage (where your users can sign in), Reply URLs and even an Application Key (client secret)? Adding the HomePage URL and Reply URLs is easy:
1
2
3
4
5
6
7
8
$appName = "MyApplication"
$appReplyURLs = @($appURI, $appHomePageURL, "https://localhost:12345")
if(!($myApp = Get-AzureADApplication -Filter "DisplayName eq '$($appName)'"  -ErrorAction SilentlyContinue))
{
    $myApp = New-AzureADApplication -DisplayName $appName -IdentifierUris $appURI -Homepage $appHomePageUrl -ReplyUrls $appReplyURLs   
}
As you can see the parameters HomePage and ReplyUrls are available. If you have multiple ReplyUrls, then supply all of them as an array of strings.

Adding the Application Key

To close this first article I’ll finish with adding the Application Key (aka ClientSecret). This key must be stored in your administration because you will need the value later for some purpose. It cannot be retrieved any more from the Azure Portal.
Edit: There is a new cmdlet New-AzureADApplicationPasswordCredential.
1
2
3
4
5
6
#
# Application Password Credentials (ClientSecret)
#
$startDate = Get-Date
$endDate = $startDate.AddYears($script:yearsOfExpiration)
$aadAppKeyPwd = New-AzureADApplicationPasswordCredential -ObjectId $AADApplication.ObjectId -CustomKeyIdentifier "Primary" -StartDate $startDate -EndDate $endDate
The cmdlet New-AzureADApplication takes a parameter called PasswordCredential. We need to provide such an object (outdated version, probably not working anymore).
1
2
3
4
5
6
7
8
$Guid = New-Guid
$startDate = Get-Date
     
$PasswordCredential = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordCredential
$PasswordCredential.StartDate = $startDate
$PasswordCredential.EndDate = $startDate.AddYears(1)
$PasswordCredential.KeyId = $Guid
$PasswordCredential.Value = ([System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(($Guid))))+"="
The value of the PasswordCredential object will be your Key (aka ClientSecret) that needs to be saved in your administration. It’s a Base64 value always ending with a ‘=’ character.


You can download the complete script from my Assets page. When you run it, it looks like this:

Summary

In this first of 2 articles I introduced how to create an Azure AD App Registration using PowerShell. This can be quite useful when automating your processes.
In part 2 I will describe how to add the Required Permissions to your Azure AD app. Stay tuned!

===============================Step 2=================================


Create Azure AD App Registration with PowerShell–Part 2


In my I started with the basic Azure AD App registration using PowerShell. I described how to set the HomePage URL, Reply URLs and even create an Application Key.


In this second part I’ll take you to the next level! I’ll describe how to add required permissions for your app.

Required Permissions

When your app needs access to other sources, like SharePoint Online sites or Mailboxes, you need to set permissions for your app. For example, this app can access Microsoft Graph, Windows Azure Active Directory and Office365 SharePoint Online:

And the explicit permissions set for SharePoint Online are:

Application Permissions: Your application needs to access SharePoint Online directly as itself (no user context). This type of permission requires administrator consent.
Delegated Permissions: Your application needs to access SharePoint Online as the signed-in user, but with access limited by the selected permission. This type of permission can be granted by a user unless the permission is configured as requiring administrator consent.
This can be a lot clicking if you don’t script it. So, let’s make your life much easier now!

ServicePrincipal

To add a required permission, you have to find out a couple things. First, we need to find the service principal on which the permissions are defined. And then second, we need to find the Application Permissions or the Delegated Permissions that you want to require.
To get a list of all service principals you use the cmdlet Get-AzureADServicePrincipal:
Get-AzureADServicePrincipal -All $true
If you want a specific service principal, you can filter on the DisplayName

When you store the service principal in a variable, you can then access the permissions:
$svcprincipal = Get-AzureADServicePrincipal -All $true | ? { $_.DisplayName -match "Office 365 SharePoint Online" }

# Show the Application Permissions
$svcprincipal.AppRoles | FT ID, DisplayName

# Show the Delegated Permissions
$svcprincipal.Oauth2Permissions | FT ID, UserConsentDisplayName
Now we know all available service principals and their permissions. We can use this now to set the required permissions for our app.

The tough part…

When we take a look at the cmdlet to create Azure AD Apps (New-AzureADApplication), we notice a parameter –RequiredResourceAccess is available. (https://docs.microsoft.com/en-us/powershell/module/azuread/new-azureadapplication?view=azureadps-2.0). However, this parameter takes an array of objects of type Microsoft.Open.AzureAD.Model.RequiredResourceAccess. Things will get more technical now and when you search the internet for this type of object, you may end up with some MSDN article: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#requiredresourceaccess-type
We need two kind of objects:
  • RequiredResourceAccess (which basically represents the Service Principal)
  • ResourceAccess (which basically represents the Application and Delegated Permissions)
The first object, RequiredResourceAccess, has two properties to set: ResourceAppId and ResourceAccess. The ResourceAppId is the same value of the ServicePrincipal AppId property.
$svcprincipal = Get-AzureADServicePrincipal -All $true | ? { $_.DisplayName -match "Microsoft Graph" }

### Microsoft Graph
$reqGraph = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$reqGraph.ResourceAppId = $svcprincipal.AppId

The property ResourceAccess is a list of required permissions. We need to create those objects first.
##Delegated Permissions
$delPermission1 = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "0e263e50-5827-48a4-b97c-d940288653c7","Scope" #Access Directory as the signed in user

##Application Permissions
$appPermission1 = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "62a82d76-70ea-41e2-9197-370581804d09","Role" #Read and Write All Groups
$appPermission2 = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "19dbc75e-c2e2-444c-a770-ec69d8559fc7","Role" #Read and Write directory data

The first parameter value that’s been provided when creating the ResourceAccess object is the Id of the permission. The second value indicates the permission type: Delegated Permission (value= Scope) or Application Permission (value = Role).
Once permission objects are created, those can then be set on the RequiredResourceAccess object:
$reqGraph.ResourceAccess = $delPermission1, $appPermission1, $appPermission2

OMG, more GUIDs…

But how about that Permission Id value? By the GUID itself it is hard to recognize what permission it is. I think we have a couple of approaches here.
  1. You call the AppRoles and OAuth2Permissions properties to get the list of all available permissions and save it for later use. Use the required Id directly in your script and add some comments to your script what permission it is. I used this approach in this blog post.
  2. Query each permission based on the DisplayName property:
    $permission = $svcPrincipal.AppRoles | ? { $_.DisplayName -match "Read and write directory data" }
    
    $appPermission1 = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList $permission.Id,"Role"
    
    
    However, Microsoft may update the DisplayName, since this area is growing!
  3. Like option 2, but now to query each permission based on the Value property.

  1. Example:
    $svcPrincipal.AppRoles | ? { $_.Value -eq "User.Read.All" }
    
    At least this feels better to read and understand than the Id (option 1), but personally I’d like to stick with option 1, because I think those GUIDs aren’t going to change.
No, I did not forget it. Yes, we still need to provide the required permissions to the New-AzureADApplication cmdlet:
$myApp = New-AzureADApplication -DisplayName $appName -IdentifierUris $appURI -Homepage $appHomePageUrl -ReplyUrls $appReplyURLs -PasswordCredentials $PasswordCredential -RequiredResourceAccess $reqGraph

If you have multiple permissions, e.g. MS Graph and SharePoint Online, supply all permission objects as an array:
-RequiredResourceAccess @($reqGraph, reqSPO)

The complete script can be download from my Assets page. Go ahead, make your life easier now!

Summary

Azure AD App registrations can be created using PowerShell. Even the required permissions can be set by providing the RequiredResouceAccess parameter. To gather all information the Get-AzureADServicePrincipal cmdlet is of great help. Along with its properties AppRoles and OAuth2Permissions.