Friday, January 17, 2020

C# : How to use Parallel.Invoke to execute the parallel operations


In nowadays we have multiple core CPU machine that enables to process the multiple thread on same time/simultaneously. .NET framework provides class library and runtime support to write efficient the parallel programming code. For more information about the parallel programming architecture please visit Parallel Programming in .NET.


In this article, we will discuss about the Parallel.Invoke method and how to write the parallel programming code with help of this.


Parallel.Invoke Parallel Programming


Parallel.Invoke method provides a simple way in which a number of Tasks may be created and executed in parallel and we don’t need to create a complicated threading code.

Here is syntax:

public static void Invoke(params Action[] actions);

Parallel.Invoke takes as array of delegates of method and it execute each of provided methods in parallel.

public static void Invoke(System.Threading.Tasks.ParallelOptions parallelOptions, params Action[] actions);

In second method, we have more control over execution of parallel operations. With help of additional parameter parallelOptions, we can control the max degrees of parallelism means the maximum number of concurrent tasks and we can also cancel the operation by using CancellationToken property.

Here is a simple example of Parallel.Invoke method:

static void Main()
        {
            List requests = GetRequests();

            ParallelOptions parallelOptions = new ParallelOptions();
            parallelOptions.MaxDegreeOfParallelism = 10;

            foreach (Request request in requests)
            {
                Parallel.Invoke(parallelOptions, async() => await ProcessRequest(request));
            }
           
        }

static async Task ProcessRequest(Request request)
        {
            // Process Request and produce response asynchronously
        }

In above example, we are controlling execution of parallel operations and only 10 max concurrent tasks are allowed.


Wednesday, January 15, 2020

ASP.NET MVC : How to display error message from controller to view

This blog explain how to show validation error in MVC View from Controller.

There is different ways to pass error message from controller to View

·         ModelState
·         ViewBag

Use AddModelError() method of ModelState  to display error message :

Model State is a Key/Value dictionary, which is used to store state of Model, which is posed from Action and it includes validation information for each fields.

It expose the main properties/method, with help of this, you can validate the posted model by calling IsValid Property, if Model has any failed validation, it return false otherwise true .

if (ModelState.IsValid)
            { 
                // Call further API/Service or business object 
            }
            else
            { 
                // Show error message 
            }

You can add validation error message by using AddModelError() method and you can use @Html.ValidationSummary() to display the validation message on view, basically  the ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and it can be used to display all the error messages for all the fields. It can also be used to display custom error messages

[HttpPost]

public ActionResult SavePerson(Person model)
{
  string Name = model.Name;   
  int firstOccurance = Name.IndexOf(',');
  int lastOcuurance =  Name.LastIndexOf(',');

  if (firstOccurance == 0)
  {
     ModelState.AddModelError("Name", "Name should not begin with Comma ','.");
  }
  else if (lastOcuurance == Name.Length - 1)
  {
     ModelState.AddModelError("Name", "Name should not end with Comma ','.");
  }

 return View("Person", person);
}

HTML Razor View:

@model Person
@Html.ValidationSummary()
<div>
    <div class="row">
        <div class="col-sm-12">
            @Html.Partial("_Person", Model })
        </div>
    </div>
</div>

HTML View:

ASP.NET MVC VALIDATION ERROR MESSAGE


Use Viewbag to display Error Message:

ViewBag is used to send data from controller to view and to display the error message, we can also use the ViewBag to transfer error or validation message from controller to view.

MVC Controller:

[HttpPost]

     public IActionResult SavePerson(Person person)
        {           
            string Name = person.Name;
            int firstOccurance = Name.IndexOf(',');
            int lastOcuurance = Name.LastIndexOf(',');

            if (firstOccurance == 0)
            {
                ViewBag.ErrorMessage = "Name should not begin with Comma ','.";
               // ModelState.AddModelError("Person.Name", "Name should not begin with Comma ','.");
            }
            else if (lastOcuurance == Name.Length - 1)
            {
                ViewBag.ErrorMessage = "Name should not begin with Comma ','.";
                //ModelState.AddModelError("Person.Name", "Name should not end with Comma ','.");
            }

            return View("Person", person);
        }

HTML Razor View:

<div class="alert alert-danger">
    <p>@ViewBag.ErrorMessage</p>
</div>

Thursday, January 9, 2020

SQL - How to modify system-versioned temporal table schema in SQL Server

In SQL Server, Temporal Table is used to keep the full history of data change for table without doing any extra coding or efforts. It will allow to you get table data at any point of time of past. For more information about SQL Server temporal tables, please visit temporal table in SQL Server .

If you want to modify (add or modify or delete column) the existing temporal table schema, you need to make sure history table schema should be sync.

Here are steps how to add new column ‘ZipCode’ in system-version temporal table.

1.   Turn off System Versioning

ALTER TABLE [dbo].[Office] SET (SYSTEM_VERSIONING = OFF);

2.   Modify the existing both Tables schema ( Office and OfficeHistory )

ALTER TABLE [dbo].[Office] ADD ZipCode varchar(10) NULL;

ALTER TABLE [dbo].[OfficeHistory] ADD ZipCode varchar(10) NULL;

3.   If data update is needed in history table, do it

Update [dbo].[OfficeHistory] SET ZipCode = '43212' where City = 'NYK'

4.   Turn on System Version option

        ALTER TABLE [dbo].[Office]
        SET
         (
            SYSTEM_VERSIONING = ON
           ( HISTORY_TABLE = [dbo].[OfficeHistory])
         );



Tables:

CREATE TABLE dbo.OfficeHistory(
     OfficeID int NOT NULL 
   , OfficeName varchar(50) NOT NULL

   , Street   varchar(50) NOT NULL

   , City varchar(50) NOT NULL

   , State varchar(2) NOT NULL

   ,SysStartTime   datetime2  NOT NULL,
   ,SysEndTime datetime2  NOT NULL,
)


CREATE TABLE Office  

(   

    OfficeID int NOT NULL PRIMARY KEY CLUSTERED

   , OfficeName varchar(50) NOT NULL

   , Street   varchar(50) NOT NULL

   , City varchar(50) NOT NULL

   , State varchar(2) NOT NULL

   , SysStartTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL

   , SysEndTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL

   , PERIOD FOR SYSTEM_TIME (SysStartTime,SysEndTime)    

)  

WITH   

   (  

      SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.OfficeHistory)  

   )



SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...