Showing posts with label AspNet.Core. Show all posts
Showing posts with label AspNet.Core. Show all posts

Wednesday, 21 January 2026

What are the various ways to add Custom Properties in Application Insights

 In this tutorial we are going to see what are the various ways to add custom properties in application insights.

  1. Direct in Logger
  2. Using Scopes
  3. Using Telemetry Client
  4. Using Telemetry Initializer
  5. Using Telemetry Processor

Direct in Logger:
When ever you give message to Log Methods if you pass parameters and value in methods using {paramname}, then this will consider as custom properties. for example below two custom properties are there one is Id another one is AuthorTimeStamp.



Using Scopes:
Using BeginScope we can pass the Custom Properties for entire scope, that means whatever log method is inside this scope will add this custom properties. Both LogDebug and LogError will have AuthorRequest and AuthorId Custom Properties.















Using Telemetry Client:
This is a direct message added using Telemetry client where you can add the custom properties with the telemetry. for example we are using below ExceptionTelemetry and TraceTelemetry.



Using Telemetry Initializer:
This will run in pipeline before telemetries are send to Azure monitor. In below code we are attaching or adding one custom property to all Trace Telemetry.




Using Telemetry Processor:
This will run in pipeline after Telemetry Initializer, Here we are adding custom property to Request Telemetry when it have response code 200.



From this tutorial you can learn how to add the Custom properties in various ways in application insights.

Monday, 11 February 2019

Using the OwinMiddleware in AspNet Core (or) use IAppBuilder in IApplicationBuilder

In this post we are going to see how to use the OwinMiddleware in Asp.net Core or use the IAppBuilder in IApplicationBuilder.

First we will see the custom OwinMiddleware which will authenticate the user in Web Api Request.

public class PinBasedAuthenticationMiddleware : OwinMiddleware
    {
        public PinBasedAuthenticationMiddleware(OwinMiddleware next) : base(next)
        {
        }

        public override async Task Invoke(IOwinContext context)
        {
            bool authorised = IsAuthorised(context.Request.Headers);
            if (authorised)
            {
                IEnumerable<Claim> claimCollection = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier,"123456"),
                    new Claim(ClaimTypes.Country, "India"),
                    new Claim(ClaimTypes.Gender,"Male"),
                    new Claim(ClaimTypes.Email,"test@gmail.com"),
                    new Claim(ClaimTypes.Role, "SA"),
                    new Claim(ClaimTypes.Sid,Guid.NewGuid().ToString())
                };
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, 
                                              "Pin_Based");
                IPrincipal principal = new ClaimsPrincipal(claimsIdentity);
                context.Request.User = principal;
                await Next.Invoke(context);
            }
            else
            {
                context.Response.ReasonPhrase = "UnAuthorized";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }           
        }

         private bool IsAuthorised(IHeaderDictionary requestHeaders)
        {
            string[] pinValues;
         bool pinHeaderPresent = requestHeaders.TryGetValue("x-token-auth", 
                                       out pinValues);
            if (pinHeaderPresent)
            {
                string[] valuesInHeader = pinValues.ToList()[0].Split(
                                           new char[] { '|' }, 
                                          StringSplitOptions.RemoveEmptyEntries);
                if (valuesInHeader.Length == 2)
                {
                    int pin;
                    if (int.TryParse(valuesInHeader[1], out pin))
                    {
                        if (pin >= 10000)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
        
    }

Now we will see how to use this middleware in Asp.Net Core, Normally we cant do this straight away. because in Asp Net core it is using the IApplicationBuilder, but to configure the owin middleware we need the IAppBuilder.

Let we do a Extension Methods which will do this.
First install the following package in application install package Microsoft.AspNetCore.App
to use the UseOwin method

internal static class ApplicationBuilderExtension {
    public static IApplicationBuilder UseOwinMiddleware(
    this IApplicationBuilder coreApp,
    Action<IAppBuilder> configuration) {
        return coreApp.UseOwin(setup => setup(next => {
            AppBuilder owinBuilder = new AppBuilder();
            IApplicationLifetime coreLifeTime = 
                        (IApplicationLifetime)coreApp.ApplicationServices
                            .GetService(typeof(IApplicationLifetime));
            AppProperties owinProp = new AppProperties(owinBuilder.Properties);
            owinProp.OnAppDisposing = coreLifeTime?.ApplicationStopping ?? 
                                               CancellationToken.None;
            owinProp.DefaultApp = next;
            configuration(owinBuilder);
            return owinBuilder.Build<Func<IDictionary<string, object>, Task>();
        }));

    }
}


How to use this extension method in asp.net core, let we see that.

public class Startup {
 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  /* install package Microsoft.AspNetCore.App */
  app.UseOwinMiddleware((build) => {
           build.MapWhen((ctx) => {
                          return ctx.Request.Headers.ContainsKey("rash");
                         },
                         (appbuilder) => {
                           appbuilder.Use<PinBasedAuthenticationMiddleware>();
                         });
            });
 }
}


I am applying a middleware based on condition whenever the request contains the headers "rajesh" following middleware will be apply, this middleware will authenticate the request.


From this post you can learn how to use the OwinMiddleware in Asp.net Core. or use IAppBuilder in IApplicationBuilder.