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:

Tuesday, 8 May 2018

Micro-ORM Dapper Short Info

See what Microsoft says about Dapper in his official website.

Dapper is a micro-ORM built and maintained by StackExchange engineers. It focuses on performance, and can map the results of a query to a strongly-typed list, or to dynamic objects.

Dapper is in production use at Stack Overflow.

Supports

Dapper works with almost all popular provider of across all

  • .NET ADO providers
  • SQLite
  • SQL CE
  • Firebird
  • Oracle
  • MySQL
  • PostgreSQL and
  • SQL Server.

Advantages


  • Efficiently work with raw execution with minimal overheads.
  • Retain control over SQL server syntax.
  • Light wight ORM

Limitations

Implementation of Dapper use ConcurrentDictionary in order to maintain cache item for better performance of query execution.And the cached item never flushed. So if we use parameterised query than its good or else for the raw sql script execution it may hit memory.

My favorite
  • Multiple Results, Single execution with multiple query.
  • Multi Mapping, Work with Join.
  • Return list of dynamic objects, <dynamic>.
  • Support async call.
For examples have a look on StackExchange .


Tuesday, 17 April 2018

Table Hint NOLOCK In SQL Server

Resources on which lock apply:
  1. Pages: The fundamental unit of data storage in SQL Server is the page. The disk space allocated to a data file (.mdf or .ndf) in a database is logically divided into pages numbered contiguously from 0 to n. Disk I/O operations are performed at the page level.
  2. Extends: Extents are a collection of eight physically contiguous pages and are used to efficiently manage the pages. All pages are stored in extents.
  3. Table
  4. Partition
  5. Row

Types:
  1. Share Lock
    1. Whenever use Select statement
  2. Update Lock
    1. Whenever use Update statement
    2. Whenever use Delete statement
  3. Exclusive
    1. Update locks provide exclusive lock on objects so no other resources can use it.
  4. Intent
    1. Hierarchy based lock, and apply whenever we use perform operation on any hierarchical based objects (like: Row > Table> Page > Extend)
  5. Schema
    1. Whenever use DDL statement
    2. Types
      1. Schema m - one perform alter statement.
      2. Schema s - When execution plan creating.


Row level lock
  1. RID : Row Identifier, without index work with heap table.
  2. Key : Having Index.


Serial
SSMS Editor 1
SSMS Editor 2
Summary
1
CREATE TABLE dbo.Demo
(
    id INT IDENTITY NOT NULL,
    details VARCHAR(MAX) NULL
);

INSERT INTO dbo.Demo
(
    details
)
VALUES
('Record 1'),
('Record 2');

Just Created a table and inserted few records.
2

SELECT * FROM DB2016.dbo.Demo
No lock
3
BEGIN TRANSACTION TRAN1;
UPDATE dbo.Demo
SET details = 'Updated Record 2'
WHERE id = 2;


4

SELECT * FROM DB2016.dbo.Demo;

SELECT * FROM DB2016.dbo.Demo
 where id=1;
Locked, not able to get result. Because data lock applied on id=2 while searching one by one.
5

SELECT Top 5 * FROM DB2016.dbo.Demo WITH (NOLOCK)
Locked but still we are able to get data as explicitly  READUNCOMMITTED level.
6
ROLLBACK TRANSACTION


7

SELECT * FROM DB2016.dbo.Demo
Lock released and we got result.
8
CREATE CLUSTERED INDEX CID_ID ON dbo.Demo (id);

Index created.
9
BEGIN TRANSACTION TRAN1;
UPDATE dbo.Demo
SET details = 'Updated Record 2'
WHERE id = 2;


10

SELECT * FROM DB2016.dbo.Demo;
Locked because of id=2
11

SELECT * FROM DB2016.dbo.Demo
 where id=1;
Got result, because searched on index and id=1 is no locked.
12
COMMIT TRANSACTION;


13

SELECT * FROM DB2016.dbo.Demo;
Got data, lock released.

See what Microsoft and other say about uses of Table Hints like NOLOCK

Because the SQL Server query optimizer typically selects the best execution plan for a query, we recommend that hints be used only as a last resort by experienced developers and database administrators.

Support for use of the READUNCOMMITTED and NOLOCK hints in the FROM clause that apply to the target table of an UPDATE or DELETE statement will be removed in a future version of SQL Server. Avoid using these hints in this context in new development work, and plan to modify applications that currently use them.

Reference