Thursday, September 1, 2022

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function (httpTrigger) and send html content  which will be converted into PDF and save in blob container.

Steps ;

Create Blob Container 

Go to azure portal ->Storage->Container (from Left Menu)->Click on + button and enter "firstcontainer" in container name. Name should be  in lowercase.


From Left menu click on Access Keys and copy connection string in your local file somewhere.



Create Azure function to Convert Html To PDF

Open Visual studio and create new project for azure function -> HttpTrigger

enter project name "azfuntionhtmltopdf"

Nuget Packages : make sure you have these packages . Here I am using DinkToPdf to convert html to pdf. you can use other library also.


Add class Startup.cs in root folder. and paste below code 

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using azfuntionhtmltopdf.Services;
using azfuntionhtmltopdf;
using DinkToPdf.Contracts;
using DinkToPdf;

[assembly: FunctionsStartup(typeof(Startup))]
namespace azfuntionhtmltopdf
{  

    public class Startup: FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
           
            builder.Services.AddTransient<IDocumentConverter, DocumentConverter>();
           
// these are required if you are using DinkToPdf ,otherwise just remove this.
builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
            var architectureFolder = (IntPtr.Size == 8) ? "64 bit" : "32 bit";
            var wkHtmlToPdfPath = Path.Combine(Environment.CurrentDirectory, $"wkhtmltox\\v0.12.4\\{architectureFolder}\\libwkhtmltox");
            CustomAssemblyLoadContext context = new CustomAssemblyLoadContext();
            context.LoadUnmanagedLibrary(wkHtmlToPdfPath);
//dinktopdf

        }
    }
}

Create one folder named services and add below classes 

CustomeAssemblyLoadContext -- if you are using some other library for html to pdf then this might not be required .

using System;
using System.Runtime.Loader;

namespace azfuntionhtmltopdf.Services
{
    public class CustomAssemblyLoadContext : AssemblyLoadContext
    {
        public IntPtr LoadUnmanagedLibrary(string absolutePath)
        {
            return LoadUnmanagedDll(absolutePath);
        }
        protected override IntPtr LoadUnmanagedDll(String unmanagedDllName)
        {
            return LoadUnmanagedDllFromPath(unmanagedDllName);
        }
       
    }
}

DocumentConverter.cs

using Azure.Storage.Blobs;
using DinkToPdf;
using DinkToPdf.Contracts;
using System;
using System.IO;


namespace azfuntionhtmltopdf.Services
{
    public class DocumentConverter: IDocumentConverter
    {
        private IConverter _converter;
        public DocumentConverter(IConverter converter)
        {
            _converter = converter;
        }

        public void CreateAndSaveInBlob(string htmlString, string documentTitle)
        {
            try
            {

                string connString = "stroage connection string";
                string blobName = "firstcontainer";

                var bytePdf = PDFByte(htmlString, documentTitle);

                BlobServiceClient blobServiceClient = new BlobServiceClient(connString);

                var blobContainerClient = blobServiceClient.GetBlobContainerClient(blobName);
                blobContainerClient.CreateIfNotExists();
                using (MemoryStream stream = new MemoryStream(bytePdf))
                {
                    blobContainerClient.UploadBlob(documentTitle, stream);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        private byte[] PDFByte(string htmlString,string documentTitle)
        {
            try
            {
                var globalSettings = new GlobalSettings
                {
                    ColorMode = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize = PaperKind.A4,
                    Margins = new MarginSettings { Top = 10 },
                    DocumentTitle = documentTitle,
                 
                };
                var objectSettings = new ObjectSettings
                {
                    PagesCount = true,
                    HtmlContent = htmlString,
                    //  WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Environment.CurrentDirectory, "css", "site.css") }, //pass your css file link if needed
                    // HeaderSettings = { FontName = "Calibri", FontSize = 9, Right = $"Page [page] of [toPage] {header}", Line = true, Spacing = 1.5 }, //header setting
                    // FooterSettings = { FontName = "Calibri", FontSize = 9, Line = true, Center = "center content", Right = DateTime.Now.ToString("dd/MM/yyyy hh:mm a") } //footer seeting
                };
                return _converter.Convert(new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects = { objectSettings }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
         
         
        }
       
    }
}

Add  interface IDocumentConverter.cs

namespace azfuntionhtmltopdf.Services
{
    public interface IDocumentConverter
    {

        void CreateAndSaveInBlob(string htmlString, string documentTitle);
    }
}

Model.cs -- to get request body data

namespace azfuntionhtmltopdf.Services
{
    public class Models
    {
        public string HtmlString { get; set; }
        public string FileName { get; set; }
    }
}

Now update your default created Function1.cs class as below :

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using azfuntionhtmltopdf.Services;

namespace azfuntionhtmltopdf
{
    public class Function1
    {
        private readonly IDocumentConverter _docConverter;
        public Function1(IDocumentConverter docConverter)
        {
            _docConverter = docConverter;

        }

        [FunctionName("fnHtmlToPdf")]
        public  async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
         
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var data = JsonConvert.DeserializeObject<Models>(requestBody);

            _docConverter.CreateAndSaveInBlob(data.HtmlString,data.FileName);        
         

            //you can handle error here
            return new OkObjectResult("pdf created");
        }
     
    }
}

That's It . We are done with  coding part. now run the project and copy the url as below


url will be someting  :http://localhost:7071/api/fnHtmlToPdf

open postman to test azure function :

After executing function if all works then your pdf file would be saved in storage.


 you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples

Friday, August 26, 2022

Get user list & details using Micorsoft graph api in c#

 In previous post I have shown how to use MS Graph Api to create users in Azure AD. Now Lets see how we can fetch and filter users using MS Graph Api. Go through the Setup Graph Api for uses of microsoft Graph Api from starting. This blog is continuous of the previous blog. To create project see Setup Graph Api.

Get All User By Page size 

Create class "UserData": For mapping Azure Ad user data.

 public class UserData
    {
        public string GivenName { get; set; }
        public string SurName { get; set; }
        public string Id { get; set; }
        public IEnumerable<ObjectIdentity> Identities { get; set; }
        public string DisplayName { get; set; }
        public string Email { get; set; }
        public string Country { get; set; }
        public string EmployeeId { get; set; }      
    }

Create another class "UserList" and paste below code


    public class UserList
    {
        public List<UserData> Users { get; set; }
        public string SkipToken { get; set; }     //in user object graph api return
//token for next paging ,if it reaches last token will be null  

    }

Now in your controller paste the below code

  [HttpGet]
        [Route("user-list")]
        public async Task<IActionResult> GetAllRegisterdUser(int pageSize=5,string pageNumer="")
        {
            var _graphClient = await GraphClientHelper.GetGraphApiClient(_configuration);
            var userList = new UserList();
            var queries = new List<QueryOption>();
            queries.Add(new QueryOption("$count","true"));
            queries.Add(new QueryOption("$top", pageSize.ToString()));        
            if (!string.IsNullOrWhiteSpace(pageNumer))
            {
                queries.Add(new QueryOption("$skiptoken", pageNumer));
            }

           var result = await _graphClient.Users
              .Request(queries)  
              //use if you need selected data
              .Select(x => new
              {
                  x.DisplayName,
                  x.Id,
                  x.Identities,
                  x.GivenName,
                  x.Mail,
                  x.Country,
                  x.Surname,
                  x.EmployeeId
              }).GetAsync();

            var data = result.CurrentPage.Select
                (p => new UserData
                {
                    DisplayName = p.DisplayName,
                    Country = p.Country,
                    Email = p.Mail,
                    EmployeeId = p.EmployeeId,
                    GivenName = p.GivenName,
                    Id = p.Id,
                    Identities = p.Identities,
                    SurName = p.Surname,
                }).ToList();

            userList.Users = data;
            userList.SkipToken = result.NextPageRequest?.QueryOptions?.FirstOrDefault(x =>
                       string.Equals("$skiptoken", x.Name, StringComparison.InvariantCultureIgnoreCase))?.Value;        


            return Ok(userList);

        }


Get user by search text :

 [HttpGet]
        [Route("user-search/{searchItem}")]
        public async Task<IActionResult> GetUserBySearch(string searchItem="",int pageSize = 5, string pageNumer = "")
        {
            var _graphClient = await GraphClientHelper.GetGraphApiClient(_configuration);
            var userList = new UserList();

            var queries = new List<QueryOption>();          
            queries.Add(new QueryOption("$top", pageSize.ToString()));
            if (!string.IsNullOrWhiteSpace(pageNumer))
            {
                queries.Add(new QueryOption("$skiptoken", pageNumer));
            }

            var result = await _graphClient.Users
               .Request(queries)
               .Filter(SetFilter(searchItem))
               //use if you need selected data
               .Select(x => new
               {
                   x.DisplayName,
                   x.Id,
                   x.Identities,
                   x.GivenName,
                   x.Mail,
                   x.Country,
                   x.Surname,
                   x.EmployeeId
               }).GetAsync();

            var data = result.CurrentPage.Select
                (p => new UserData
                {
                    DisplayName = p.DisplayName,
                    Country = p.Country,
                    Email = p.Mail,
                    EmployeeId = p.EmployeeId,
                    GivenName = p.GivenName,
                    Id = p.Id,
                    Identities = p.Identities,
                    SurName = p.Surname,
                }).ToList();

            userList.Users = data;
            userList.SkipToken = result.NextPageRequest?.QueryOptions?.FirstOrDefault(x =>
                       string.Equals("$skiptoken", x.Name, StringComparison.InvariantCultureIgnoreCase))?.Value;


            return Ok(userList);

        }

 private string SetFilter(string searchItem)
        {
            if (string.IsNullOrWhiteSpace(searchItem))
            {
                return string.Empty;
            }

            return $"startswith(givenName, '{searchItem}')" +
                   $" or startswith(surname, '{searchItem}')"+
                    $" or startswith(displayName, '{searchItem}')" ;
         
        }


Get user by Email Id / Identity  :

[HttpGet]
        [Route("search-by-email/{emailId}")]
        public async Task<IActionResult> GetUserByEmail(string emailId)
        {
            var _graphClient = await GraphClientHelper.GetGraphApiClient(_configuration);
            var userList = new UserList();

            var result = await _graphClient.Users
               .Request()
               .Filter($"identities/any(c:c/issuerAssignedId eq '{emailId}' and c/issuer eq '{tenant url}') ")
               .Select(x => new
               {
                   x.DisplayName,
                   x.Id,
                   x.Identities,
                   x.GivenName,
                   x.Mail,
                   x.Country,
                   x.Surname,
                   x.EmployeeId
               }).GetAsync();
            return Ok(result);

        }


Get user by User Id:

 [HttpGet]
        [Route("search-by-Id/{userId}")]
        public async Task<IActionResult> GetUserById(string userId)
        {
            var _graphClient = await GraphClientHelper.GetGraphApiClient(_configuration);
            var result = await _graphClient.Users[userId]
               .Request()
               .GetAsync();
            return Ok(result);

        }


await GraphClientHelper.GetGraphApiClient(_configuration); //to configure this you follow Setup Graph Api.



 you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples

Wednesday, August 24, 2022

Create, update ,delete, deactivate User in Azure AD B2C using Microsoft Graph Api

User creation using Microsoft Graph Api in Azure AD B2C.

Scenario - A company is using Azure AD B2C to manage application access  for its customer. Admin registers customer through application. While registering customer need to save user details to AZURE AD and Application DB . Later customer can be authenticated/Authorized for application. Admin manages users in Azure AD B2C.

In order to achieve above scenario I will use Microsoft Graph and .Net Core web api .

Microsoft Graph :It is a RESTful web API that enables to access all  Microsoft Cloud service resources. It uses Http methods to call api.

Steps :
1. Register an application to Azure AD B2C
2. Api Permission to Microsoft Graph 
3. Create Web Api 

Register an application to Azure AD B2C :

Go to azure portal -> Azure AD B2C tenant -> Click on App Registration from Left menu.
Follow this link if you want to create tenant from starting.


Click +New Registration .
In new screen fill the app name "MSGraphAppTest" and click Register. All Other field leave default .


Go to registered app and click on Client & Secret from left menu  .
Click New client secret ->enter name and choose expiry ,click on Add .
Added client secret will be added in list .Copy the value of the client secret and save somewhere in your local before leaving this window.


Api Permission to Microsoft Graph 

Click on Api Permission from Left menu -> Add a permission . you can see first tab is Microsoft graph ,this is what you need to use. Here you need to give permission to MS Graph api .


Click on Microsoft graph-> Application Permission -> search "User" you will see User .Under User permission check User.ReadWrite.All then click Add Permission.


Once permission added you need to grant admin consent .





Before leaving ,lets copy Application Client Id ,tenant Id  .Click on overview and copy below ,save in local file .



Create Web Api 

Open visual studio ->create .Net core web api  named  "MsGraphAzureAdTest" .



Go to Nuget package manager and install



Open appsettings.json file and replace with below code 

{
  "B2CUserSettings": {
    "Tenant": "<<tenant name>>.onmicrosoft.com",
    "ClientId": "<<ClienId>>",
    "ClientSecret": "<<secret>>",
    "B2CExtensionAppClientId": "<<extensionClientId>>"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}


Create "RegisterUser" class and paste below code

using Microsoft.Graph;
using Newtonsoft.Json.Linq;

namespace MsGraphAzureAdTest
{
    public class RegisterUser
    {
//input from UI
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string EmployeeId { get; set; }
        public string CompanyCode { get; set; }
        public string CompanyName { get; set; }
        public string JobTitle { get; set; }
        public string Location { get; set; }

//set Data in User object and return
        public User SetUserData(
            string extensionClientId,
            string tenant)
        {
            var extension = "extension_" + extensionClientId;

            var jsonObject = new JObject
            {
                {"accountEnabled", true},
                {"country", "India"},
                {"creationType", "LocalAccount"},
                {"givenName",FirstName},
                {"surName",LastName},
                {$"{extension}_CompanyCode", CompanyCode},//custom attribute
                {$"{extension}_CompanyName", CompanyName},  //custom attribute            
                {"displayName", FirstName + " " + LastName},
                {"passwordPolicies", "DisablePasswordExpiration,DisableStrongPassword"},
                {"passwordProfile", new JObject
                {
                    {"password", "abc@123"},
                    {"forceChangePasswordNextLogin", false}
                } },
                {"Identities", new JArray
                    {
                        new JObject
                        {
                            {"signInType",  "emailAddress"},
                            {"issuer",tenant},
                            {"IssuerAssignedId",Email }
                        }
                    } }
                };

            return jsonObject.ToObject<User>();
        }
    }
}


Create new class "GraphClientHelper" and paste below code
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MsGraphAzureAdTest
{
    public class GraphClientHelper
    {
        public static async Task<GraphServiceClient> GetGraphApiClient(IConfiguration _configuration)
        {
            var clientId = _configuration["B2CUserSettings:ClientId"];
            var secret = _configuration["B2CUserSettings:ClientSecret"];
            var domain = _configuration["B2CUserSettings:Tenant"];

            var credentials = new ClientCredential(clientId, secret);
            var authContext =
                new AuthenticationContext($"https://login.microsoftonline.com/{domain}/");
            var token = await authContext
                .AcquireTokenAsync("https://graph.microsoft.com/", credentials);

            var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                    .Headers
                    .Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);

                return Task.CompletedTask;
            }));

            return graphServiceClient;
        }
    }
}


Add a new controller named "UserManagerController" and add below code


CREATE USER


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace MsGraphAzureAdTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserManagerController : ControllerBase
    {

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IConfiguration _configuration;
        public UserManagerController(ILogger<WeatherForecastController> logger,
            IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        [HttpPost]
        public async Task<IActionResult> RegisterUser([FromBody] RegisterUser command)
        {
            var _graphClient =await GraphClientHelper.GetGraphApiClient(_configuration);
            // Create user
            var user = command.SetUserData(_configuration["B2CUserSettings:B2CExtensionAppClientId"], _configuration["B2CUserSettings:Tenant"]);
            if (user == null)
            {
                return BadRequest($"Error in setting user data in graph api");
            }
            var result = await _graphClient.Users
            .Request()
            .AddAsync(user);
            if (result == null)
            {
                return BadRequest($"Unsuccesful attempt to create user {command.Email}");

            }

            //Logic to save extra data in db

            return Ok();

        }


    }
}


Run your web api and submit through swagger.




Go to azure portal -> Active Directory B2C and click users from left menu . you can see added user in the user list.


UPDATE USER :

 User details can be updated as below , If you want to disable or enable account for login , update AccountEnabled property.

   [HttpPut]
         public async Task<IActionResult> UpdateUser(string userId,bool enabled=true)
        {
            var _graphClient =  GraphClientHelper.GetGraphApiClient2(_configuration);
            var user = await _graphClient.Users[userId]
             .Request()
             .GetAsync();
            if (user == null)
            {
                return BadRequest($"Error in setting user data in graph api");
            }

            user.AccountEnabled = enabled; // this will decativate the user from login
            user.Mail = "test@g.com";
            return Ok( await _graphClient.Users[userId]
            .Request()
            .UpdateAsync(user));

        }

After updating AccountEnabled as false ,user signIn will be blocked .



DELETE USER :


   [HttpDelete]      
        public async Task<IActionResult> DeleteUser(string userId)
        {
            var _graphClient = GraphClientHelper.GetGraphApiClient2(_configuration);
              await _graphClient.Users[userId]
                   .Request()
                   .DeleteAsync();
            return Ok();

        }



We finished all the operation on user object by using MS Graph Api. In next tutorial will see how we can query on user to get and filter users.

 you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples


Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...