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((?!@).)*$




Wednesday, 26 September 2018

Chrome secret, List of URLs


As a web developer many times we need to dig into client network to know more about debug  and more. Here is list of Chrome URLs that will help us in order to get more relevant information about debug, trace, network, extension, memory, system info, cache and many more.

You just need to type it or copy paste in chrome as URL:

chrome://chrome-urls/






Tuesday, 31 July 2018

Unit Testing for Private Methods in DotNet C#

Though Microsoft doesn't allow creation of unit test of private method as best practice.  Microsoft Unit Testing recommends to Public methods with no parameters whereas class may contains private methods with lots of parameters. As we can see how Visual studio behave when we try to create unit test of private member.

Creation with non-public Class.





Creation with public Class.



See how it escape private Methods.






Solution:

PrivateObject Class Allows test code to call methods and properties on the code under test that would be inaccessible because they are not public.
References: 
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx

Simple Demo:

IProgram.cs
using System;
namespace Private_Method_UnitTest
{
    public interface IProgram
    {
        string GetName();
    }
 
}


Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Private_Method_UnitTest
{
    public class Program : IProgram
    {
        public string GetName() => "Raj";
        private string GetAddress() => "Delhi";
        private string GetAddressWithParam(bool isPermanent) => (isPermanent? "Bihar":"Delhi");
    }
}

ProgramTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Private_Method_UnitTest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Private_Method_UnitTest.Tests
{
    [TestClass()]
    public class ProgramTests
    {
 
        private IProgram program;
        [TestInitialize]
        public void Setup()
        {
            program = new Program();
        }
 
        [TestMethod()]
        public void GetNameTest()
        {
            var name = program.GetName(); 
            Assert.AreEqual(name, "Raj");
        }
 
 
        [TestMethod()]
        public void GetAddressTest()
        {
            Program objProgram = new Program();
            PrivateObject privateObject = new PrivateObject(objProgram);
            var result = privateObject.Invoke("GetAddress");
            var exceptadResult = "Delhi";
            Assert.AreEqual(result.GetType(), exceptadResult.GetType());
        }
 
        [TestMethod()]
        [ExpectedException(typeof(MissingMethodException))]
        public void GetAddress_Failour_Test()
        {
            Program objProgram = new Program();
            PrivateObject privateObject = new PrivateObject(objProgram);
            var result = privateObject.Invoke("GetAddress", 1);
        }
 
 
        [TestMethod()]
        public void GetAddressWithParam()
        {
            Program objProgram = new Program();
            PrivateObject privateObject = new PrivateObject(objProgram);
            var result = privateObject.Invoke("GetAddressWithParam"new object[] { true });
            var exceptadResult = "Bihar";
            Assert.AreEqual(result.GetType(), exceptadResult.GetType());
        }
 
    }
}

Sunday, 29 July 2018

IndexedDB simple wrapper with examples



Indexed dB
○ Use as data storage at client end(web browser) support data access in same domain.
○ As we  already have 2 popular storage like  sessionStorage, localStorage, but its more powerful when its comes to size and Api.
○ We can also say it is alternative of deprecated local storage Web SQL database.
○ It is not a relational database, its NoSQL, storage based on Key, Pair values so we can say  its not a structured query language.
○ We can store structured data, including files/blobs.
○ Data can be indexed according to search keys, so provide faster search.
○ Support almost all major browsers: Chrome, Firefox, IE11, UC




Important terms
○ Database - Top level objects, that treat as DB, we can have multiple DB with different name based on requirements.
○ Object store - Treat as collection of  structured data object, like table but not table.
○ Index - Mechanism to organise objects store so that sorting, fetching would be efficient.
○ Operation - An interaction with the database.
○ Transaction -  it provide atomic read-modify-write operations as thread safe.
○ Cursor - Iteration over object with in Object Store.



Keywords:
○ indexedDB
○ Open
○ createObjectStore
○ Put()
○ Delete(), Clear()
○ getAll(), Get()

Wrapper
○ localForage
○ Dexie.js
○ ZangoDB
○ JsStore
○ MiniMongo
○ PouchDB
○ Jquery

I have created my own, example available on https://github.com/rajkrs/IndexedDB
Based on your requirement you can modified it easily.

Wednesday, 6 June 2018

Create Dynamic Object on the fly in C#

Many times we required Object on the fly, at run time. On that case
System.Dynamic.ExpandoObject and Newtonsoft.Json.Linq.JObject
will help us more.


In the below example you can see how we can extract few data on the fly from a Type having all properties. This dynamic object example may help us developing web api where we need list.


Example:


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Dynamic_Objects
{
    class Program
    {
 
        string GetCityAsJson()
        {
            City objCity = new City();
            var cities = objCity.GetAllCities().Select(o =>
            {
                dynamic city = new System.Dynamic.ExpandoObject();
                city.Text = o.Name;
                city.Value = o.ID;
                return city;
            }
            ).ToList();
 
            return JsonConvert.SerializeObject(cities);
        }
 
 
        string GetCityAsJson2()
        {
 
            City objCity = new City();
            var cities = objCity.GetAllCities().Select(o =>
            {
                dynamic city = new Newtonsoft.Json.Linq.JObject();
                city.Text = o.Name;
                city.Value = o.ID;
                return city;
            }
            ).ToList();
 
            return JsonConvert.SerializeObject(cities);
        }
 
 
        string GetCityAsJson3()
        {
 
            City objCity = new City();
            var cities = objCity.GetAllCities().Select(o =>
            new
            {
                Text = o.Name,
                Value = o.ID
            }
            ).ToList();
 
            return JsonConvert.SerializeObject(cities);
        }
 
        static void Main(string[] args)
        {
            Program obj = new Program();
            Console.WriteLine(obj.GetCityAsJson());
            Console.WriteLine("---------------------------------------");
            Console.WriteLine(obj.GetCityAsJson2());
 
            Console.Read();
        }
    }
 
 
 
    class City
    {
        public int ID { getset; }
        public string Name { getset; }
        public string PreviousName { getset; }
        public string ShortName { getset; }
        public decimal longitude { getset; }
        public decimal latitude { getset; }
 
        public List<City> GetAllCities() =>
            new List<City>(){
                new City() { ID= 1, Name = "New Delhi", PreviousName="Delhi", ShortName = "Del", latitude= 24.40m, longitude= 77.14m   },
                new City() { ID= 1, Name = "Tokyo", PreviousName="Tokyo", ShortName = "Tok", latitude= 35.40m, longitude= 139.45m   }
            };
 
    }
}


Tuesday, 15 May 2018

Linq CopyToDataTable extension for anonymous type IEnumerable

Casting Enumerable into List, Array is to common but sometime we also need to projection in to DataTable. Though there is one inbuilt CopyToDataTable<DataRow>() to get DataTable, but it only works with IEnumerable<DataRow>. Where as sometime we also required casting with anonymous type which we are getting through join or group by Linq query. Here I am providing both predefined and Custom Extension method which will solve our problem.

Predefined Snippet:


var allSubscriptions = from license in licensesDataTable.AsEnumerable()
                                          where license.Field<bool>("IsExpired") == true
                                          select license;
            DataTable expiredSubscriptions = allSubscriptions.CopyToDataTable<DataRow>();



Custom Extension Method:

public static class EnumerableExtensions
    {
        public static DataTable CopyToDataTable(this IEnumerable<object> data)
        {
            var parseDT = new DataTable();
            data.Select((r, i) => new { Key = i, Value = r }).ToList().ForEach(r =>
            {
                if (r.Key == 0)
                {
                    r.Value.GetType().GetProperties().ToList().ForEach(p =>
                    {
                        parseDT.Columns.Add(p.Name, p.PropertyType);
                    });
                }
                var row = parseDT.NewRow();
                r.Value.GetType().GetProperties().ToList().ForEach(p =>
                {
                    row[p.Name] = p.GetValue(r.Value, null);
                });
                parseDT.Rows.Add(row);
 
            });
            return parseDT;
        }
    }

Small Example:


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LinqGroupByIntoDataTable
{
 
    public static class EnumerableExtensions
    {
        public static DataTable CopyToDataTable(this IEnumerable<object> data)
        {
            var parseDT = new DataTable();
            data.Select((r, i) => new { Key = i, Value = r }).ToList().ForEach(r =>
            {
                if (r.Key == 0)
                {
                    r.Value.GetType().GetProperties().ToList().ForEach(p =>
                    {
                        parseDT.Columns.Add(p.Name, p.PropertyType);
                    });
                }
                var row = parseDT.NewRow();
                r.Value.GetType().GetProperties().ToList().ForEach(p =>
                {
                    row[p.Name] = p.GetValue(r.Value, null);
                });
                parseDT.Rows.Add(row);
 
            });
            return parseDT;
        }
    }
    class Program
    {
 
        static void Main(string[] args)
        {
            var dt = GetTable();
            var grp = from row in dt.AsEnumerable()
                      group row by row.Field<string>("City"into rowGroup
                      select new
                      {
                          City = rowGroup.Key,
                          Name = rowGroup.Min(r => r.Field<string>("Name")),
                          ID = rowGroup.Min(r => r.Field<int>("ID"))
                      };
 
 
            foreach (var key in grp)
 
            {
                Console.Write(key.City + " " + key.Name);
                Console.WriteLine();
            }
 
 
            var dtNew = grp.CopyToDataTable();
 
 
            Console.ReadKey();
        }
 
        static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ID"typeof(int));
            table.Columns.Add("City"typeof(string));
            table.Columns.Add("Name"typeof(string));
            table.Columns.Add("Date"typeof(DateTime));
 
            table.Rows.Add(25, "Delhi""Raj"DateTime.Now);
            table.Rows.Add(26, "Delhi""Suman"DateTime.Now);
            table.Rows.Add(10, "Pune""Ankur"DateTime.Now);
            table.Rows.Add(21, "Patna""Abhi"DateTime.Now);
            return table;
        }
 
 
    }
 
}

Output: