Thursday, 17 January 2019

Who changed DB Objects in MSSQL Server?

If you want to trace that who changed the db objects you can find it by using following Sql Server script. Bellow script is given to trace the changes of a procedure myProcName in last 7 days in database myDbName.

--From trace file

DECLARE @filename VARCHAR(255);
SELECT @filename = SUBSTRING(path, 0, LEN(path) - CHARINDEX('\', REVERSE(path)) + 1) + '\Log.trc'
FROM sys.traces
WHERE is_default = 1;

--From DB
SELECT gt.HostName,
       gt.EventClass, AS EventName,
FROM [fn_trace_gettable](@filename, DEFAULT) gt
    JOIN sys.trace_events te
        ON gt.EventClass = te.trace_event_id
WHERE EventClass IN ( 164 )
      --AND gt.EventSubClass = 2
      AND gt.ObjectName LIKE ('%myProcName%')
      AND DatabaseName = 'myDbName'

Thursday, 10 January 2019

Automate C# Client API for Web API DotNetCore

If you have developed Web API in any platform like .Net Core and you have corresponding swagger json documentation then developing client to consume that service is just waste of time. Will recommend to have look on NSwagStudio of Nswag [Official Microsoft documentation].

Follow simple steps: 

1. Implement Swashbuckle or NSwag in your application and get swagger specification like: https://localhost:44359/swagger/v1.0/swagger.json which contains JSON Data.
2. Get MSI installer of NSwagStudio from and install it in your client machine.

3. Open NSwagStudio, put swagger specification url, create local copy explore some setting and get your client in few clicks

5. You can save your code in any existing project. by changing some settings

Set appropriate name for namespace

 Specify Output file path

Click on Generate Files and you will get file like this, build it and use it anywhere.

Wednesday, 2 January 2019

What is AspNet Core Proxy and how to create it?

If we want to have a proxy on top of multiple micro-services based on specific route, we can use Microsoft.AspNetCore.Proxy Nuget Package it provide RunProxy as method extension under IApplicationBuilder, which allow us to configure mapping of micro-service.

Let's explore the diagram given below:

If we want to see 1-1 mapping for a simple actual implementation, we can see how easy it mapped in given below pic

So let's see how we need to manage the code in order for actual implementation.

Here is code snippet that we need to put in under ProxyApi, Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace AppProxy
    public class Startup
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit
        public void ConfigureServices(IServiceCollection services)
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            if (env.IsDevelopment())
            //app.Run(async (context) =>
            //    await context.Response.WriteAsync("Hello World!");
            app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/Account/api"), builder => builder.RunProxy(new ProxyOptions {
                Scheme = "http",
                Host= "localhost",
                Port = "54169"
            app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/Order/api"), builder => builder.RunProxy(new ProxyOptions
                Scheme = "http",
                Host = "localhost",
                Port = "54409"

Output could be easy understand by looking in to below pic:

Watch full Demo on YouTube

Wednesday, 28 November 2018

Azure function Basic Information

    Azure function is same as Google Cloud function, Amazon lambda and

    What is Azure Function?
    Is server-less architecture, server-less means not without server :-). Its means that we do not worry about servers and infra
    We can say is Nano services
    Being call
    • By web-hooks
    • By scheduling
    • By specific trigger
      • From storage
      • Form services

    Separate system into two flow:
    1: Command that point to a service (it alter the state)
    2: Query that provide response from service

    Is it cost effective?
    We only pay for what we consume through services. 

    Can develop into any language
    C#, Python, Java, JavaScript

    We can set binding and output for it.

    Where to use?: 
    Background application that can process data based on storage, IO, http trigger like 
    creating pdf and sending email once to all pending user once in a day. Process image and 
    copy in 4 different dimension just after uploading a profile pic etc.

    How to create?
    1. Go to azure Marketplace
    2. Search Function App
    1. Create
    1. Choose Subscription, Resource Group(Create new or Existing)
    2. Chose Hosting Plan 
      1. Dynamic: Independent billing/uses/monitoring or
      2.  App Service Plan: Your existing service plan
    1. Create
    2. New Function
    3. Choose a template - HttpTrigger-Csharp
    1. Name you function
    2. Choose Authorization level - Anonymous
    1. Create
    1. Change Code in to run.csx
    2. Take you Function URL
    3. Check your Function URL in any tools like Postman
    4. Verify Azure Log

How to Create a Simple Azure Function In Visual Studio?

Based on above instruction you may can easily develop and test you Azure Function locally in  Visual Studio.For it you must have installed either Data Storage and processing or Azure development components in Visual Studio. And flow below steps

Thursday, 25 October 2018

How to get CamelCase Json format in MVC 5 with System.Web.Mvc.JsonResult?

Well, I fall in a problem where all of my client side code like JavaScript was written with CamelCase format format to parse Web Api response. Every thing was working properly when Api was developed on DotnetCore with default Serializer Settings. After some time we have decided to downgrade the application on MVC 5 and now with System.Web.Mvc.JsonResult.Json() we are getting response with PascalCase format with default Serializer setting, and it broke all client side execution.

I tried to changed formatting with global setting on Application_Start with bellow code spinet

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

That not worked for me, as i became able to know that Json() use in build JavaScriptSerializer to serialize object. The globally configured Serializer Settings will not affect with Json() .

So finally i decided to create my own helper that will help to change format.

public class JsonCamelCase : JsonResult
    private object _data;
    public JsonCamelCase(object data, JsonRequestBehavior jsonRequestBehavior = JsonRequestBehavior.DenyGet)
        _data = data;
            base.JsonRequestBehavior = jsonRequestBehavior;
    public override void ExecuteResult(ControllerContext context)
        if (context == null)
            throw new ArgumentNullException("context");
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET"StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException("GET verb not allowed for this operation, set JsonRequestBehavior to AllowGet.");
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;
        if (_data != null)
            var jsonSerializerSettings = new JsonSerializerSettings
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            response.Write(JsonConvert.SerializeObject(_data, Formatting.Indented, jsonSerializerSettings));

And in MVC controller instead of Json() i used JsonCamelCase(), it worked for me.
return new JsonCamelCase(questions);
//return Json(questions);

Monday, 22 October 2018

SQL Injection Regex Find in Project

This is a common regex template by using which you can easily find all select * SQL statement used in you project. You just have to copy below text and pate  in Ctrl+ F window with regex option and find into Current project.

select [*] from .+ where((?!@).)*$