Monday 15 May 2023

Azure B2B Token Auth | Microsoft azure

 Azure B2B Token auth once of best way for auth.

Way to Generate Auth Token:

public async Task<DataResponse> GenerateB2BToken()

        {

            List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>

                    {

                        new KeyValuePair<string, string>(CLIENT_CREDENTIALS),

                        new KeyValuePair<string, string>(B2CClientId),

                        new KeyValuePair<string, string>(B2CClientSecret),

                        new KeyValuePair<string, string>(B2BResource)

                    };

            using (var client = new HttpClient())

            {

                _httpClient.DefaultRequestHeaders.Accept.Clear();

                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                FormUrlEncodedContent content = new FormUrlEncodedContent((List<KeyValuePair<string, string>>)postData);

                using HttpResponseMessage response = await client.PostAsync(urlPath, content);

                {

                    var responsedata = await response.Content.ReadAsStringAsync();                    

                    return responsedata;

                }

            }

            if (!string.IsNullOrEmpty(response))

            {

                TokenAuthData token = JsonConvert.DeserializeObject<TokenAuthData>(response);

                if (token != null && !string.IsNullOrWhiteSpace(token.token_type) && !string.IsNullOrWhiteSpace(token.access_token))

                {                     

                       return Json( new { Token = $"{token.token_type} {token.access_token}" });                   

                }

                

            }

            return  null;

        }

 Token Validation : 

public async Task<bool> ValidateB2BToken(string idtoken)

        {

            string _token = idtoken.Replace(BEARER, "").Replace(BEARER.ToUpper(), "").Trim();

            if (!string.IsNullOrEmpty(_token))

            {

                try

                {

                    var token = new JwtSecurityToken(jwtEncodedString: _token);

                    if (token.Claims != null && token.Claims.Count() > 0)

                    {

                        var expiry = long.Parse(token.Claims.Where(x => x.Type == "exp").Select(x => x.Value).FirstOrDefault());

                        var aud = token.Audiences.Where(x => x == "your client id").Select(x => x).FirstOrDefault();

                        long epochTime = await ToUnixTime(DateTime.UtcNow);

                         //validate expiry and audience

                        if (!string.IsNullOrEmpty(aud) && epochTime <= expiry)

                        {

                            return true;

                        }

                        else

                            return false;

                    }

                }

                catch (Exception ex)//Token expired case

                {

                    

                    return false;

                }

            }

            return false;

        }

        private async Task<long> ToUnixTime(DateTime date)

        {

            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return await Task.FromResult( Convert.ToInt64((date - epoch).TotalSeconds));

        }


Above way you can validate Token auth B2b

Thursday 16 February 2023

Git fails when pushing commit to github | try increasing http.postBuffer

 Recently I faced issue while pushing more files to GIT, here is solution if you face similar error message which title of this blog represent,

unable to rewind rpc post data - try increasing http.postBuffer

Error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054

send-pack: unexpected disconnect while reading sideband packet


Solution:

Open command prompt and copy paste below line  hit on enter,

git config http.postBuffer 524288000
Above statement will increase http write buffer size, huge number of file you can able to push then.


Tuesday 7 February 2023

How to truncate a foreign key constrained table?

 Recent time I've faced challenge while mysql table truncation data,

Cannot truncate a table referenced in a foreign key constraint 

In above case error, 

MySQL Query: 

  SET FOREIGN_KEY_CHECKS = 0;

  truncate table mydb.TableName

  SET FOREIGN_KEY_CHECKS = 1;

You could able to do truncate entire table which having foreign key as well.


Saturday 17 September 2022

Azure key Vault Access using C#/.Net

 Azure key vault is one of best secure place to dealing with secret exchange through azure cloud storage.

Benefits:

  • Run-time we can update vault values possible.
  • Expiration can be set, Validity for specific key secret possible
  • Versioning for secret is possible.
Let's try to consume Azure key vault using Nuget for C# .net.
Below is the nuget, I've utilized you can refer for the same. versioning can be upgradable/downgrade as per your requirement.
  • Azure.Identity (version 1.6.1)
  • Azure.Security.KeyVault.Secrets (version 4.3.0)


We have to create key vault in azure portal, and in-order to consume secret using tenant/clientid/secret, we have to register app in azure portal, which we need to map with with key-Vault.
App registration:
Once we will create app, it will provide us clientId, and secret, same app need to assign to key vault.
Key vault App registration Mapping:

Key vault
Permission grant/access with app registration.


Below code base for helper class:
KKKKK
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace VaultService
{
    public  class KeyVaultHelper
    {
        private static NameValueCollection appSettings = ConfigurationManager.AppSettings;
        public static string AzureKeyVaultUrl; //=appSettings["AzureKeyVaultUrl"];

        public static string TenantId; //= appSettings["TenentId"];

        public static string ClientId;  //= appSettings["SASClientId"];

        public static string Secrets; //= appSettings["SASClientSecret"];

        public KeyVaultHelper()
        {
            if (appSettings != null &&
                string.IsNullOrWhiteSpace(AzureKeyVaultUrl)
                || string.IsNullOrWhiteSpace(TenantId)
                || string.IsNullOrWhiteSpace(ClientId)
                || string.IsNullOrWhiteSpace(Secrets)
                )
            {
                AzureKeyVaultUrl = appSettings["AzureKeyVaultUrl"];
                TenantId = appSettings["SASTenantId"];
                ClientId = appSettings["SASClientId"];
                Secrets = appSettings["SASClientSecret"];
            }
        }
        
        private static async Task SetEnvVariableToKeyValut()
        {
            AzureKeyVaultUrl = appSettings["AzureKeyVaultUrl"];
            TenantId = appSettings["SASTenantId"];
            ClientId = appSettings["SASClientId"];
            Secrets = appSettings["SASClientSecret"];
            await Task.CompletedTask;
        }


  //GET SECRET CLIENT
        private static async Task<SecretClient> GetSecretClient()
        {
            SecretClientOptions options = new SecretClientOptions()
            {
                Retry =
                    {
                        Delay= TimeSpan.FromSeconds(2),
                        MaxDelay = TimeSpan.FromSeconds(16),
                        MaxRetries = 5,
                        Mode = Azure.Core.RetryMode.Exponential
                    },
            };
            if(string.IsNullOrEmpty(TenantId) || string.IsNullOrEmpty(ClientId) || string.IsNullOrEmpty(Secrets))
            {
                await SetEnvVariableToKeyValut();
            }
            ClientSecretCredential clientSecretCredential = new ClientSecretCredential(TenantId,
                   ClientId, Secrets);
            var secretClient = new SecretClient(new Uri(AzureKeyVaultUrl), clientSecretCredential);
            return await Task.FromResult(secretClient);
        }
        public static async Task<string> GetKeyVaultValueAsync(string key)
        {
            try
            {
                //Get ket valut
                var cancelToken = new CancellationToken();
                SecretClient secretClient = await GetSecretClient();
                KeyVaultSecret keyVaultSecret = await secretClient.GetSecretAsync(key, null, cancelToken);
                return await Task.FromResult(keyVaultSecret?.Value);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public static async Task<bool> SetKeyVaultValueAsync(string key, string value, SecretClient client = null)
        {
            // Create a new secret using the secret client.
            var cancelToken = new CancellationToken();
            try
            {
                if (client == null)
                {
                    client = await GetSecretClient();
                }
                KeyVaultSecret secret = await client.SetSecretAsync(key, value, cancelToken);
                return await Task.FromResult(secret != null ? true : false);
            }
            catch (Exception exx)
            {
                return false;
            }
        }

        public static async Task<bool> DeleteVaultValueAsync(string key, SecretClient client = null)
        {
            // Delete a new secret using the secret client.
            var cancelToken = new CancellationToken();
            try
            {
                if (client == null)
                {
                    client = await GetSecretClient();
                }
                var secret = await client.StartDeleteSecretAsync(key, cancelToken);
                return await Task.FromResult(secret != null ? true : false);
            }
            catch (Exception ex)
            {
                return false;
            }
            
        }

    }
}

Above code snippet use-ful while consuming Key vault. 

Please feel free to connect in-case if you face any challenge, gjinformatic@gmail.com or comment here.

 


Wednesday 26 January 2022

Leptop battery stuck at 99% DELL leptop

 If you having issue with DELL leptop stuck at 99% , please check report with below commands.

powercfg /batteryreport /output "C:\bettery-report.html"

If still if you face challenge then upgrade BIOS drivers. and then check, or else your battery performance might be impacted. 

Tuesday 25 January 2022

Working with ExpandoObject in c# C-sharp

 Hello all,

Some of coolest topics , I came across, ExpandoObject in C#

dynamic dynamicObject = new ExpandoObject();


While addiing into code base, found compile time error, 

Error CS0656 Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

To over come from this, You need to add a reference to the DLL Microsoft.CSharp.dll

It will resolve your compile time error, and you can take benifitws of ExpandoObject.

Thursday 25 February 2021

Angular Error / Warning heap limit Allocation failed - JavaScript heap out of memory

 Today I have observe one of error , which while we are extracting and building with node.

I was facing some challenges,

FATAL ERROR: heap limit Allocation failed - JavaScript heap out of memory.

node --max_old_space_size=8000

By using this in command line or environment variable setting we can able to extend size of allocation.

Generally Visual studio or Other tool through while running application we will face such problem.

For watch on command and extend the allocation size :

node --max_old_space_size=8000 ./node_modules/@angular/cli/bin/ng build --watch

this will be same command you can use in powershall windows or cmd.

It will resolve allocation size memory issue.

Saturday 14 December 2019

Top 5 emerging technology trends for the year 2019 - 2020

Technology is growing rapidly, now we also need to learn and run fast along with newest technology, According to source upcoming  year for IT industry toughest competition and laid off employee.



 Technology witnessed rapid growth in 2019. From cloud-based computing to machine learning, throughout the year technologies with significant potential evolved, paving the path to the upcoming year. Power players in the field including Google, Amazon, Facebook, and Apple showed tremendous potential to bring consumer behavior based technologies to the households. Using Big Data, Power BI,  these companies have evolved to enhance user experience.
Some of the significant trends of 2017 including artificial intelligence (AI), machine learning, augmented reality are moving from the niche space to more prominent usage in the industry.
As these trends become the stepping stones for 2018, the technological evolution has led to 5 major trends for 2018, as predicted by Gartner.
According to them next 2-5 year IoT, AI will take place and human power will be replace with robotics.

1. Intelligent apps and analytics
Having created an impact in 2019, it suffices to say that the penetration of AI in applications and services has become inevitable. Forming a layer of systems and people, AI has been instrumental in creating intelligent apps to serve humans better. From virtual assistants to task performers, smart apps have the potential to transform the consumption of services. Using omni-channel presence, Incedo has developed Incedo Cognitive Framework (ICF) that addresses full platform lifecycle for solutions including Chatbots and virtual assistants. These intelligent apps use Natural Language Processing (NLP) to develop a contextual understanding of user interactions to have smart, human-like conversations.
2. Artificial intelligence
Fastest growing in industry, The growing interest in AI has led to significant investments in the field by businesses. A study by Gartner reveals that 59% of organizations are continuously gathering information to build AI strate-gies. As the insights into AI learning deepen, the usage is rapidly moving from understanding user voice to performing human tasks that will soon increase machine-human interaction. Incedo’s mobil-ity center for excellence (CoE) leverages the growth of AI in various machine learning solutions. Creating an interactive platform for data, devices, and people, CoE helps build smarter customised applications.
3. Digital twins
It help us for Integrating AI, machine learning and analytics with data, digital twins refers to the replica of physi-cal assets in the digital world. Continuously updated from multiple sources, digital twins use sensor data to update. With the rise of IoT, digital twins have now evolved from being a concept into reali-ty. Gartner predicts that half of the industrial companies will use digital twins by 2021 thus result-ing in 10% improvement in the effectiveness of the organization. With IoT, Incedo transforms into a systems integrator that helps different industries including Healthcare, Telecommunication, Pharmaceutical, Automotive. The service offerings span across idea generation, application development, sensor & platform integration, and predictive analytics.
4. Conversational platforms
The conversation between machines and humans has evolved beyond the realms of performing basic tasks of calling a person from the contact list. The evolution of conversational platforms has in-creased the burden on the system to interpret even more complicated interactions such as making a movie reservation. With the increased adoption of bots, the growth of Robotic Process Automation (RPA) helps companies with process efficiencies and cost reduction. Incedo’s expertise in RPA in-cludes the proper implementation of RPAs to replace processes that are predictable, have low hu-man discretion, and expensive. From selecting the right technology through implementation, Incedo has proven to be successful in the RPA journey of various organizations.
5. Blockchain
Moreover blockchain is de-centrelize system, The growth of Blockchain holds the promise to revolutionize industries by enabling smooth interac-tions among commercial parties outside the system. With an improved architecture, blockchain can help existing infrastructures remove business friction by transforming into independent individual applications or participants. For a practical implementation without any compromise of data through blockchain, Incedo offers data solutions that help with data engineering, management, and BI plan-ning. These solutions help in data lake governance, Big Data architecture, and OLAP analytics.

Sunday 28 July 2019

ASP.NET Core Interview Questions and Answers

What is .NET Core?

  • cross-platform version of .NET, that supports almost all things that .NET supported (except things like WPF, Windows Forms, Web Forms and Active Directory)
  • It is leaner, faster and improved version of .NET
  • .NET Core and ASP.NET Core are FREE and Open Source but also they are supported by Microsoft.
  • It is kinda the new .NET framework
  • Main framework that Microsoft has been focusing on is .NET Core
  • The .NET Core Runtime installation file is only about 20 MBs
  • .NET Core provides dotnet CLI – command line interface
Main characterestics of ASP.NET Core:
  • DI Container which is quite simple and built-in. You can extend it with other popular DI containers
  • Built-in and extensible structured logging. You can redirect output to as many sources as you want (file, Azure, AWS, console)
  • Extensible strongly typed configuration, which can also be used to reload at run-time
  • Kestrel – new, cross-platform and super fast web server which can stand alone without IIS, Nginx or Apache
  • New, fully async pipeline. It is easily configured via middleware
  • ASP.NET All meta package which improves development speed, and enables you to reference all Microsoft packages for ASP.NET Core and it will deploy only those that are being used by your code
  • There is no web.config. We now use appsettings.json file in combination with other sources of configuration (command line args, environment variables, etc.)
  • There is no Global.asax – We have Startup.cs which is used to set up Middleware and services for DI Container.
  • 1) What are the advantages of ASP.NET Core over ASP.NET?

    There are following advantages of ASP.NET Core over ASP.NET :
    • It is cross-platform, so it can be run on Windows, Linux, and Mac.
    • There is no dependency on framework installation because all the required dependencies are ship with our application
    • ASP.NET Core can handle more request than the ASP.NET
    • Multiple deployment options available withASP.NET Core
  • What is Metapackages?

    The framework .NET Core 2.0 introduced Metapackage that include all the supported package by ASP.NET code with their dependencies into one package. It helps us to do fast development as we don't require to include the individual ASP.NET Core packages. The assembly Microsoft.AspNetCore.All is a meta package provide by ASP.NET core.
  • Can ASP.NET Core application work with full .NET 4.x Framework?

    Yes. ASP.NET core application works with full .NET framework via the .NET standard library.
  • What is the startup class in ASP.NET core?

    Startup class is the entry point of the ASP.NET Core application. Every .NET Core application must have this class. This class contains the application configuration rated items. It is not necessary that class name must "Startup", it can be anything, we can configure startup class in Program class.
    1. //Nicer way to understand execution
    2. public class Program
    3. {
    4. public static void Main(string[] args)
    5. {
    6. CreateWebHostBuilder(args).Build().Run();
    7. }
    8. public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    9. WebHost.CreateDefaultBuilder(args)
    10. .UseStartup<TestClass>();
    11. }
    1. What is the use of ConfigureServices method of startup class?

      This is an optional method of startup class. It can be used to configure the services that are used by the application. This method calls first when the application is requested for the first time. Using this method, we can add the services to the DI container, so services are available as a dependency in controller constructor.
    2. What is the use of Configure method of startup class?

      It defines how the application will respond to each HTTP request. We can configure the request pipeline by configuring the middleware. It accepts IApplicationBuilder as a parameter and also it has two optional parameters: IHostingEnvironment and ILoggerFactory. Using this method, we can configure built-in middleware such as routing, authentication, session, etc. as well as third-party middleware.
    3. What is middleware?

      It is software which is injected into the application pipeline to handle request and responses. They are just like chained to each other and form as a pipeline. The incoming requests are passes through this pipeline where all middleware is configured, and middleware can perform some action on the request before passes it to the next middleware. Same as for the responses, they are also passing through the middleware but in reverse order.
  • What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run()?

    We can use both the methods in Configure methods of startup class. Both are used to add middleware delegate to the application request pipeline. The middleware adds using IApplicationBuilder.Use may call the next middleware in the pipeline whereas the middleware adds using IApplicationBuilder.Run method never calls the subsequent ore next middleware. After IApplicationBuilder.Run method, system stop adding middleware in request pipeline.
    1. What is routing in ASP.NET Core?

      Routing is functionality that map incoming request to the route handler. The route can have values (extract them from URL) that used to process the request. Using the route, routing can find route handler based on URL. All the routes are registered when the application is started. There are two types of routing supported by ASP.NET Core
      • The conventional routing
      • Attribute routing
      The Routing uses routes for map incoming request with route handler and Generate URL that used in response. Mostly, the application having a single collection of routes and this collection are used for the process the request. The RouteAsync method is used to map incoming request (that match the URL) with available in route collection.
    2. How to enable Session in ASP.NET Core?

      The middleware for the session is provided by the package Microsoft.AspNetCore.Session. To use the session in ASP.NET Core application, we need to add this package to csproj file and add the Session middleware to ASP.NET Core request pipeline.
      1. public class Startup
      2. {
      3. public void ConfigureServices(IServiceCollection services)
      4. {
      5. ….
      6. ….
      7. services.AddSession();
      8. services.AddMvc();
      9. }
      10. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      11. {
      12. ….
      13. ….
      14. app.UseSession();
      15. ….
      16. ….
      17. }
      18. }
    3. What are the various JSON files available in ASP.NET Core?

      There are following JSON files in ASP.NET Core :
      • global.json
      • launchsettings.json
      • appsettings.json
      • bundleconfig.json
      • bower.json
      • package.json
    4. What is tag helper in ASP.NET Core?

      It is a feature provided by Razor view engine that enables us to write server-side code to create and render the HTML element in view (Razor). The tag-helper is C# classes that used to generate the view by adding the HTML element. The functionality of tag helper is very similar to HTML helper of ASP.NET MVC.
      1. Example:
      2. //HTML Helper
      3. @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", placeholder = "Enter Your First Name" })
      4. //content with tag helper
      5. <input asp-for="FirstName" placeholder="Enter Your First Name" class="form-control" />
      6. //Equivalent HTML
      7. <input placeholder="Enter Your First Name" class="form-control" id="FirstName" name="FirstName" value="" type="text">
    5. How to disable Tag Helper at element level?

      We can disable Tag Helper at element level using the opt-out character ("!"). This character must apply opening and closing the Html tag.
      Example
      1. <!span asp-validation-for="phone" class="divPhone"></!span>
    6. What are Razor Pages in ASP.NET Core?

      This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric development model just like ASP.NET web forms. It supports all the feature of ASP.NET Core.
      Example
      1. @page
      2. <h1> Hello, Book Reader!</h1>
      3. <h2> This is Razor Pages </h2>
      The Razor pages start with the @page directive. This directive handle request directly without passing through the controller. The Razor pages may have code behind file, but it is not really code-behind file. It is class inherited from PageModel class.
    7. How can we do automatic model binding in Razor pages?

      The Razor pages provide the option to bind property automatically when posted the data using BindProperty attribute. By default, it only binds the properties only with non-GET verbs. we need to set SupportsGet property to true to bind a property on getting request.
      Example
      1. public class Test1Model : PageModel
      2. {
      3. [BindProperty]
      4. public string Name { get; set; }
      5. }
    8. How can we inject the service dependency into the controller?

      There are three easy steps to add custom service as a dependency on the controller.
      Step 1: Create the service
      1. public interface IHelloWorldService
      2. {
      3. string SaysHello();
      4. }
      5. public class HelloWorldService: IHelloWorldService
      6. {
      7. public string SaysHello()
      8. {
      9. return "Hello ";
      10. }
      11. }
      Step 2: Add this service to Service container (service can either added by singleton, transient or scoped)
      1. public void ConfigureServices(IServiceCollection services)
      2. {
      3. ….
      4. services.AddTransient<IHelloWorldService, HelloWorldService>();
      5. }
      Step 3: Use this service as a dependency in the controller
      1. public class HomeController: Controller
      2. {
      3. IHelloWorldService _helloWorldService;
      4. public HomeController(IHelloWorldService helloWorldService)
      5. {
      6. _helloWorldService = helloWorldService;
      7. }
      8. }
    9. How to specify service lifetime for register service that added as a dependency?

       
      ASP.NET Core allows us to specify the lifetime for registered services. The service instance gets disposed of automatically based on a specified lifetime. So, we do not care about the cleaning these dependencies, it will take care by ASP.NET Core framework. There is three type of lifetimes.

      Singleton

      ASP.NET Core will create and share a single instance of the service through the application life. The service can be added as a singleton using AddSingleton method of IServiceCollection. ASP.NET Core creates service instance at the time of registration and subsequence request use this service instance. Here, we do not require to implement Singleton design pattern and single instance maintained by the ASP.NET Core itself.
      Example
      1. services.AddSingleton<IHelloWorldService, HelloWorldService>();

      Transient

      ASP.NET Core will create and share an instance of the service every time to the application when we ask for it. The service can be added as Transient using AddTransient method of IServiceCollection. This lifetime can be used in stateless service. It is a way to add lightweight service.
      Example
      1. services.AddTransient<IHelloWorldService, HelloWorldService>();

      Scoped

      ASP.NET Core will create and share an instance of the service per request to the application. It means that a single instance of service available per request. It will create a new instance in the new request. The service can be added as scoped using an AddScoped method of IServiceCollection. We need to take care while, service registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like singleton object.
      1. services.AddScoped<IHelloWorldService, HelloWorldService>();
    Feel free to reach out @ gjinformatic@gmail.com