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

Monday, April 25, 2022

JSON Path to use in Angular Projects

How to use JSON Path to query any JSON object.

For example, consider below simple JSON, if you want to query JSON we can use simply query as this.obj.name or this.obj.id to access to the JSON

this.obj ={

   id: 1,

   "name": "balaji"

}

For array object we can use index, for ex: this.objData[0].id. For more JSON path to find we can refer https://jsonpathfinder.com/

this.objData = {

        data: [

  {

    "id": 1,

    "name": "Balajiprasad",

    "age": 18,

              "address": {

                      "state": "TN",

                       "country": "India"

                } 

 

  },

  {

    "id": 2,

    "name": "prasad",

    "age": 28,

     "address": {

                      "state": "Tx",

                       "country": "US"

                } 

  }

]}


In angular project, if we need to use JSON path dynamically then we can refer the jsonpath library Ref: https://www.npmjs.com/package/jsonpath

Steps to use,

1. Add "json-path" in package.json file under dependencies

    "dependencies": {

"jsonpath": "1.1.1"

}


2. Add reference of "json-path" directly in component. No need to specify in App.module

    import * as jp from 'jsonpath'

3. Use the JSON path in code , need to use $.. (double dots)

   let state = jp.query(this.objData, '$..data[0].address.state')

 



Monday, September 13, 2021

Browser - Change Current Geo Location

In order to test different Geo Location in browser, we have option to change location in browser. Follow below steps,

Browsers used: Chrome, IE Edge

  1. Go to Developer Tools (Click F12)
  2. Click ... Settings Icon -> More Tools -> Sensors
  3. Now in Sensors Window, Change the location as needed. You can also manage for new locations.




Thursday, May 14, 2020

How to ignore property conditionally during JSON serialization

Consider i have class Employer, i want serialize this class to json string and need ignore some properties conditionally. For ex: in my example, i want to include address1 and address2 only if it has valid values


  public class Employer
    {
 public int id { get; set; }

        public string name { get; set; }
       
 public string ssn { get; set; }

        public string address1 { get; set; }

        public string address2 { getset; }
   }



Declare some values


Employer employer = new Employer(){ … address1 = "some value", address2 = null };


Now serialize it for json string


var jsonstring = JsonConvert.SerializeObject(employer,
                       Newtonsoft.Json.Formatting.None,
                       new JsonSerializerSettings
                       {
                           
                       });

Here you will get all the properties.

Now lets see how to ignore the properties conditionally, you can choose either one of these options.

Option 1: Use ShouldSerialize property inside class itself like below. But you need add individual shouldSerialize property for each class property.

  public class Employer
    {
 public int id { get; set; }

        public string name { get; set; }
       
 public string ssn { get; set; }

        public string address1 { get; set; }

        public string address2 { get; set; }

        public bool ShouldSerializeaddress1()
        {
            // don't serialize if it is null or empty or add any your custom conditions
            return !string.IsNullOrEmpty(address1);
        }
        public bool ShouldSerializeaddress2()
        {
            // don't serialize if it is null or empty or add any your custom conditions
            return !string.IsNullOrEmpty(address2);
        }

   }


Option 2: Instead creating multiple ShouldSerialize property inside class, we can create ContractResolver and add it in Json serialization as below,

Create Resolver Class,

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Reflection;
...

  public class EmployerShouldSerializeContractResolver : DefaultContractResolver
    {
        public new static readonly EmployerShouldSerializeContractResolver Instance = new EmployerShouldSerializeContractResolver();

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            if (property.DeclaringType == typeof(Employer))
            {
                property.ShouldSerialize =
                    instance =>
                    {
                        //ignore default values
                        return instance.GetType().GetProperty(member.Name).GetValue(instance, null) != property.DefaultValue;
                    };
            }

            return property;
        }

    }


Include it in JSON serialization,

var jsonstring = JsonConvert.SerializeObject(employer,
                       Newtonsoft.Json.Formatting.None,
                       new JsonSerializerSettings
                       {
                           ContractResolver = new EmployerShouldSerializeContractResolver()
                       });


Wednesday, June 13, 2018

OTP Mechanism in Asp.Net core

OTP mechanism can be done using different algorithms like TOTP or HOTP. To use it we have inbuilt plugins available,

I have used Otp.Net and TOTP algorithm for this purpose, we can refer it from https://github.com/kspearrin/Otp.NET

Step 1: Refer library from Nuget "Otp.Net" https://www.nuget.org/packages/Otp.NET

Step 2: Create TOTP Object


var emailToSend ="balajisrmv@gmail.com";
var secretKey = Encoding.ASCII.GetBytes(emailToSend);
var TotpObj = new Totp(secretKey, step: 60); //set step for 60 secs for OTP expiration
var otpString = TotpObj.ComputeTotp();

//Send to email, you can customize this to however needed.
emailService.SendEmail(toAddress: emailToSend, subject: "OTP Subject", body: "Your otp code is: " + otpString);


Step 3: Send this otpString to any channel like Email or SMS as your covenient

Step 4: Create seperate action method to validate input OTP code from user

public IActionResult OnPostVerifyAuthCodeAsync(string OtpCode)
        {
   var emailToSend ="balajisrmv@gmail.com";
   var secretKey = Encoding.ASCII.GetBytes(emailToSend);
   var TotpObj = new Totp(secretKey, step: 60); //set step for 60 secs for OTP expiration            
bool otpValid = TotpObj.VerifyTotp(OtpCode, out long timeStepMatched, new VerificationWindow(2, 2));

            if (otpValid)
            {
               
//OTP is valid proceed your business logic            

            }
            else
            {
               //OTP is invalid throw error
     }

            return Page();

        }

Wednesday, May 2, 2018

VS - Asp.Net core application not worked and run only on fiddler

I have faced some specific issue, where .Net core project was not running on my local machine visual studio and ruins only when Telerik Fiddler ruins. It always goes to 500 error page (only for me). I have tried changing all browser proxy settings, but those not fixed my

I was searching for my Outlook automatic replies not opened and calendar schedules not shown issue, for that got fix from Microsoft as https://support.microsoft.com/en-in/help/2847833/proxy-server-causing-issues-in-outlook-with-free-busy-oof-and-mailtips, surprisingly it fixed my visual studio .net core project issue. Try below steps to reset proxy