Showing posts with label .NetCore5. Show all posts
Showing posts with label .NetCore5. Show all posts

Monday, November 14, 2022

gRPC

About gRPC 

gRPC is an open source remote procedure call (RPC) system initially developed at Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, blocking or nonblocking bindings, and cancellation and timeouts.

This would look similar to websockets but underlying difference is it works on HTTP2 protocol and the data format for request response would be bound to Protobuf, cannot use JSON or XML. But protobuf is more compact and light weight than the latter. The connection would be persistent and client can invoke the methods in remote server through the connection as needed. It offers 4 types of method call, traditional request/response model, server-side streaming, client side streaming and bi-directional streaming.

What are protocol buffers?
Protocol buffers are mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.


Notes: we can use gRPC from different languages  like C#, Dart, Java, Node, PHP, Python,...


Http2 vs Http1.1



Http 1.1 only supports Request/Response pattern, and not supports compress headers, create new TCP connection per request. So, if we visit a page that contains one image and one CSS, this means create 3 TCP connections!


Http 2.0. one TCP connection will use for multiple Requests/Responses, Supports Server Push, headers and data are both compressed to binary data (less bandwidth), support send multiple messages at the same time. SSL will be required by default.  


How to Enable http 2.0 on IIS?
IIS running on Windows 10 or Windows Server 2016 supports HTTP/2 by default, but the connection should be https.
you shouldn't need to change anything in your application for HTTP/2 to work.

here is how to install IIS and enable local SSL for testing...







How to validate that current connection using http2.0 ?

Launch your browser from your Windows 10 or Windows Server 2016 machine and hit F12, (or go to Settings and enable F12 Developer Tools), and then switch to the Network tab. Browse to https://localhost and voila, you are on HTTP/2!

if "Protocol" is not exists, then right click > Header Options > Protocol




Types of gRPC APIs



1. Unary
It is a classic request-response API. This is what everyone is using mostly as REST APIs. The Client sends a request and the server sends a response to that request.

2. Server Streaming
In this case, the client will send a request to the server and the server will keep sending data like a stream.

3. Client Streaming
It is a bit opposite to Server Streaming. Here client will send a stream of requests and expects a single response. The server will send a single response. May be after the end of all the requests or in the middle, it depends on the implementation.

4. Bi-Directional Streaming
It is a kind of combination of both Server Streaming and Client Streaming in the sense that both server and client will send a stream of requests and responses. The client will initiate a connection and start streaming messages in the request and the server will start streaming the response to the client.







gRPC Scalability 
Server : Async
Client: sync/ Async


gRPC Performance

let us compare Data Streaming via GRPC vs MQTT vs Websockets, which is better?


Above results clearly shows that GRPC wins because of persistent connection and protobuf data format, which is lightweight.

Conclusion
Out of 3 options, it depends on individual requirements to choose one. If it is collecting data from sensors and IoT device the choice would always be MQTT. But if data streaming is between devices which doesn't have resource constraints GRPC and websockets can be an options. For my requirement GRPC is winner.













Sunday, October 30, 2022

Create a temp URL valid for one minute only for file on Azure Blob Storage

 

How to allow dynamic URL in Azure using c# ?


        CloudStorageAccount account = CloudStorageAccount.Parse("yourStringConnection");
        CloudBlobClient serviceClient = account.CreateCloudBlobClient();

        var container = serviceClient.GetContainerReference("yourContainerName");
        container
            .CreateIfNotExistsAsync()
            .Wait();

        CloudBlockBlob blob = container.GetBlockBlobReference("test/helloworld.txt");
        //blob.UploadTextAsync("Hello, World!").Wait();

        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();

        // define the expiration time
        policy.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(1);

        // define the permission
        policy.Permissions = SharedAccessBlobPermissions.Read;

        // create signature
        string signature = blob.GetSharedAccessSignature(policy);

        // get full temporary uri
        Console.WriteLine(blob.Uri + signature);



From .NET 5, Entity Framework Core provides a method that is available to retrieve the SQL statement from a Linq query without executing it, which can be done by the ToQueryString() method of IQueryable 

Sunday, August 21, 2022

use React in MVC project

 install NuGet packages

React.AspNet
JavaScriptEngineSwitcher.V8
JavaScriptEngineSwitcher.Extensions.MsDependencyInjection

JavaScriptEngineSwitcher.V8.Native.win-x64 [old]
or
Microsoft.ClearScript.V8.Native.win-x64 [new]


Sunday, May 22, 2022

C# System.Collections.Generic

 1) ToLookup()

  1. It creates a Key based on the user's choice at runtime. In this article I have used the length of the string as the Key. So it stores data and creates the key based on the length of the string.
    E.g. "Lajapathy" has a length of 9, so the key is created with the value 9 and the value is "Lajapathy".
  2. Exactly the same concept of Dictionary<K, T>, but the key is not static; it is dynamic.
  3. Setting key at Runtime.
  4. It is very useful if using complex data type.
  5. It is useful to get data fast, because it stores as Index key.
  6. It is a KeyValue<K, T> pair.

Example

public static List<string> GetStringList()
    {
        List<string> list = new List<string>();
        list.Add("Lajapathy");
        list.Add("Sathiya");
        list.Add("Parthiban");
        list.Add("AnandBabu");
        list.Add("Sangita");
        list.Add("Lakshmi");
        return list;
    }

.................................
.................................

        List<string> list = GetStringList();
 
        //Sets KeyValue pair based on the string length.
        ILookup<intstring> lookup = list.ToLookup(i => i.Length);


        //Iterates only string length having 7.
        foreach (string temp in lookup[7])
        {
            HttpContext.Current.Response.Write(temp + "<br/>");
        }

======================================================

    public static List<Employee> EmployeeList()
    {
        List<Employee> emp = new List<Employee>();
        emp.Add(new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" });
        emp.Add(new Employee { ID = 200, Name = "Parthiban", CompanyName = "FE" });
        emp.Add(new Employee { ID = 400, Name = "Sathiya", CompanyName = "FE" });
        emp.Add(new Employee { ID = 300, Name = "Anand Babu", CompanyName = "FE" });
        emp.Add(new Employee { ID = 300, Name = "Naveen", CompanyName = "HCL" });
        return emp;
    }
..............................................
..............................................
        List<Employee> empList = EmployeeList();
        //Creating KeyValue pair based on the ID. we can get items based on the ID.
        ILookup<intEmployee> lookList = empList.ToLookup(id => id.ID); 

        //Displaying who having the ID=100.
        foreach (Employee temp in lookList[100])
        {
            Console.WriteLine(temp.Name);
        } 

========================================================

2) Max, Min methods

using System.Linq;
using System.Collections.Generic;
................

List<int> list = new List<int>() { 5, -1, 4, 9, -7, 8 };

int maxValue = list.Max();
int maxIndex = list.IndexOf(maxValue);
 
int minValue = list.Min();
int minIndex = list.IndexOf(minValue);
 
Console.WriteLine("Maximum element {0} present at index {1}", maxValue, maxIndex);
Console.WriteLine("Minimum element {0} present at index {1}", minValue, minIndex);



3) Where , FirstOrDefault


        List<string> myList = new List<string>();
        list.Add("Lajapathy");
        list.Add("Sathiya");
        list.Add("Parthiban");
        list.Add("AnandBabu");
        list.Add("Sangita");
        list.Add("Lakshmi");


       //return the first item which matches your criteria or Null
      string result = myList.FirstOrDefault(s => s == "Lakshmi");


      //return all items which match your criteria
     IEnumerable<string> results = myList.Where(s => s == search);



4) LIKE operator in LINQ


Typically you use String.StartsWith/EndsWith/Contains. For example:


public class Student{
public int Id;
public string Name;
}

var students= new List<Student>() { 
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"}
            };

var id = students
                       .Where(p => p.Name.Contains("u"))
                       .FirstOrDefault()
                       .Id;


5) AddRange to Append to List


var favouriteCities = new List<string>();
var popularCities = new List<string>();

string[] cities = new string[3]{ "Mumbai", "London", "New York" };

popularCities.AddRange(cities);
favouriteCities.AddRange(popularCities);


6) Remove vs RemoveAt


var numbers = new List<int>(){ 10, 20, 30, 40, 10 };

numbers.Remove(10); // removes the first 10 from a list

numbers.RemoveAt(2); //removes the 3rd element (index starts from 0)



7) Contains() to Check Elements in List


var numbers = new List<int>(){ 10, 20, 30, 40 };
numbers.Contains(10); // returns true
numbers.Contains(11); // returns false



8) Sort vs Reverse()


var words = new List<string> {"falcon", "order", "war", "sky", "ocean", "blue", "cloud", "boy"};

words.Sort();
Console.WriteLine(string.Join(",", words));

words.Reverse();     // descending order
Console.WriteLine(string.Join(",", words));



9) Linq OrderBy()


class Pet { public string Name { get; set; } public int Age { get; set; } } public static void OrderByEx1() { Pet[] pets = { new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 } }; IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); } } /* This code produces the following output: Whiskers - 1 Boots - 4 Barley - 8 */


10)  Linq: from where select



// Specify the data source. int[] scores = { 97, 92, 81, 60 }; // Define the query expression. IEnumerable<int> scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); } // Output: 97 92 81



11) Linq Distinct, OrderBy 


string s = "efgabcddddddaaaaaaaaaaa";
List<char> myList = s.Distinct().OrderBy(q => q).ToList();
Console.Write(string.Join(">",myList));    //a>b>c>d>e>f>g