Thursday, August 27, 2020

Types Of Cloud Services

Cloud computing services are categories mainly three types as below:

1. SAAS - Software as a services
2. PAAS - Platform as a services
3. IAAS - Infrastructure as a services



As in the above picture you can see end use can hit only SAAS model and internally SAAS hit to PAAS and IAAS.

 1. SAAS (Software as a services):
  • SASS services = SAAS + PASS + IAAS
  • This services is just start using the software after getting the license or free one just need to register and start using.
  • Generally software companies buy PASS environments then host their software and start selling the software as SAAS model.
  • End user use the software thought internet or VPN connection.
  • Most of the customer sell SAAS on daily ,monthly,quarterly or yearly plan based on the data usage.
  • Common SAAS model software are gmail,CRM and accounting software, if you need CRM or accounting software just start paying on plan and start using the software.
  • SaaS is closely related to the application service provider (ASP) and on demand computing software delivery models.
 2. PAAS (Platform as a services):
  • PASS services = PASS + IAAS
  • This include operating system, database ,web server and development tools.
  • This provide the infrastructure to host the applications in web server and development environment to build the applications in other word this is complete development and deployment environment. 
  • This service is mostly used by IT engineers.
 3. IAAS (Infrastructure as a services):
  • IASS is purely hardware environment and this includes virtual machine,storage, load balancing and networking.
  • This can quickly scales up and down on demand.

4. Other cloud services:

I. FAAS (Function as service) : This follow the serverless architecture.
II. Communications As A Service (CAAS)
III. Network As A Service (NAAS)
IV. Monitoring As A Service (MAAS)

Friday, August 21, 2020

Different Type Of Parameters In Csharp

There are 4 different way we can pass the parameter in the C# methods which all are as below:

1. Value parameter
2. Ref parameter
3. Out parameter
4. Param parameter


1. Value parameter:
Pass the value of the variable to the method or function, this mean passing the local value of one function to another function and both the function variable value accessibility to the local only. If any value want to get from the function then we need to use return keyword.

Example:

        static void Main(string[] args)
        {
            int num1 = 2;
            int num2 = 3;
            int result = 0;
            //passing num1 and num2 value to function Mul
            //return the multiplication value of num1 and num2
            result = Mul(num1, num2);
            Console.WriteLine("Two no. multiplication value is :" + result);
            Console.ReadLine();
        }

        //Value Parameters  Method
        static int Mul(int num1, int num2)
        {
            return num1 * num2;
        }

Output:
Two no. multiplication value is :6

2. Ref parameter:
Reference type parameter passing the address of the variable instead of value,from and to function name need to use ref keyword before the variable name.This will be helpfully when need to return multiple value from the function.
Note: ref is read and write that means from function variable should have some value then only you will able to pass the value otherwise compiler error will be thrown as "Error CS0165 Use of unassigned local variable 'variable name'".

Example:

        static void Main(string[] args)
        {
            int num1 = 2;
            int num2 = 3;
            int result=0 ;
            //passing num1 & num2 as value type
            //Pass result as ref type to function Mul
            Mul(num1, num2, ref result);
            Console.WriteLine("Two no. multiplication value is :" + result);
            Console.ReadLine();
        }

        //Reference Parameters  Method
        static void Mul(int num1, int num2,ref int result)
        {
            result=num1 * num2;
        }

Output:
Two no. multiplication value is :6

In above example you can see there is no return value still we got the multiplication value in the result variable as "result" variable address's value is changed.

3. Out parameter:
Our parameter also passing the address of the variable instead of value same as ref,from and to function name need to use out keyword before the variable name.This will be helpfully when need to return multiple value from function.
Note:
out is optionally read and but must write that means from function variable can or can not have value,if you don't have value which is going to pass as out then no compiler error, this is the difference between ref and out.

Example:

        static void Main(string[] args)
        {
            int num1 = 2;
            int num2 = 3;
            int result;
            //passing num1 & num2 as value type
            //Pass result as out type to function Mul
            Mul(num1, num2, out result);
            Console.WriteLine("Two no. multiplication value is :" + result);
            Console.ReadLine();
        }

        //out Parameters  Method
        static void Mul(int num1, int num2,out int result)
        {
            result=num1 * num2;
        }

Output:
Two no. multiplication value is :6

I. In above example you can see there is no return value still we got the multiplication value in result variable as "result" variable address's value is changed.
II. Also notice the int result; does not have value, in case of ref having value.

4. Params parameter:
Params parameter is usefully when we don't know no. of parameter need to pass in a function (but there are some constraint). By this we can pass no. of parameters to a variable by using params keyword and to function hold all the values in an array of same type.
Note: 
I. No. of parameters should be same type.
II. params should be the last parameter of the function.

Example:

        static void Main(string[] args)
        {
            //passing age as int 
            //passing emp name, dept and designation as params
            ParamsExample(42, "Johan", "Software", "Software Engineer");
            Console.ReadLine();
        }

        static void ParamsExample(int age,params string[] emp)
        {
           //print all params parameters 
            foreach (string empdata in emp)
            {
                Console.WriteLine(empdata);
            }
        }
        

       

Output:
Johan
Software
Software Engineer

Wednesday, August 19, 2020

ASP.Net MVC Interview Questions and Answers

I am listing down all questions which usually i ask in the ASP.Net MVC interview and i been asked but answer is not in deep, if you want to learn in details please contact me.

1. What is MVC design pattern?

Answer:
MVC design pattern is an architectural design pattern for the web UI layer.
This architecture separate the dynamic web application in three components as below:

Model: Model objects are the parts of the application that implement the logic for the application's data domain.

View: Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data.

Controller: Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI.

2. What is the advantages of ASP.Net MVC design pattern?

Answer:
I. This is light weight compare to ASP.Net event driven.
II. UI(view), data logic (model) and events (controllers) by design get separated, this way SoC design principle implemented.
III. Independent unit test can be written for all the MVC components.
IV. As components get separated out so best resource can work on the different components.

3. Explain page life cycle of ASP.Net MVC design pattern?

Answer:
I. When the request is first time then then RouteTable class initiated with the route data.
II. The UrlRoutingModule find the match of URL from the RouteData of RouteTable and instantiates a MVCHandler which is HttpHandler
III. Request send to MvcHandler and this will create the controller class object
IV. Controller class combine the data and view then sent the response to the browser

4. Which version of ASP.Net MVC you worked? Brief history or the version? Explain few latest features.

Answer:
Interviewer just want to confuse you here..just be prepared for version no. Here is the history of the ASP.Net MVC version:


5. Can you please explain how routing works? Explain the URL Patterns.

Answer:
Please refer Q. 3.
URL patterns works as below:
Please refer the below image and follow the statements:
I. "Home" is the controller name
II. "Index" is the action method name
III. If URL "http://localhost:52845" anyone type then invoke the default URL as per the route table

Can can find the RegisterRoutes code in the "App_Start\RouteConfig.cs"


6. Can we write the custom route ? if yes then how?

Answer:
Yes, we can write the custom route and we can write in the file "App_Start\RouteConfig.cs".

Can can find below "http://localhost://52845/Hotel/Index" is from custom route.



7. What is the difference between TempData, ViewData, and ViewBag?

Answer:
ViewData and ViewBag: 
ViewData and ViewBag both use to pass data from controller to view and data will be available for the current request only. Only the difference  is ViewData is dictionary object and ViewBag is dynamic property.

TempData: 
TempData also a dictionary object and this hold the data till the HTTP request time this mean we can use this data when redirect from controller to controller action methods and data will be persist.

8. What is Partial View in ASP.Net MVC?

Answer:
Using multiple partial view to make a page or we can say re-usable view component.

9. What is area View in ASP.Net MVC?

Answer:
Divide your application area wise this mean if large application then divide then into area so then better code management. e.g. admin modules can create as different area.

10. What is the difference between model and ViewModel?

Answer:
Model and ViewModel is same to hold the data only the diffreance is ViewModel is custom model for the view.

11. What is filter? How many different type of filter available? Explain all.

Answer:
Filter is execution of some logic before and after execution of action methods. There are four different type of filters as below:
I. Authorization filters – For authentication and authorizes.
II. Action filters – Before and after action methods execute. i.e. Authorize, OutputCashe, ValidateInput, HandleError
III. Result filters – Before and after view result.
IV. Exception filters – If some unhandled exception

12. How do you implement the unit testing in the ASP.Net MVC?

Answer:
I. No dependency object been created in the controller class.
II. Implement dependency injection by Unity framework

13. Explain the different return types of an action method?

Answer:
Below are the different type of return types:
ViewResult
PartialViewResult
RedirectResult
RedirectToRouteResult
ContentResult
JsonResult
JavaScriptResult
FileResult
EmptyResult

14. How to overload an action method?

Answer:
By ActionName filter you can overload the methods.


        [ActionName("OverloadedName")]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

15. What is Razor in ASP.Net MVC?

Answer:
Razar is open source view. In MVC you can implement ASPX view also.

16. How you will do Caching in ASP.Net MVC?

Answer:
By OutputCache filter we can implement caching in the MVC.

Sample code :

        [OutputCache(Duration = 60)]
        public ActionResult Index()
        {
            return View();
        }

17. How you will pass data from controller to controller action method?

Answer:
By TempData

18. Can you please explain some features of MVC 4?

Answer:
Please go though the my blog ASP.Net MVC 4 Features



Monday, August 17, 2020

How to develop Cloud Native App?

10 rules to build cloud native app:

  1. Application should be platform independent i.e. use dot net core 
  2. Follow domain driven design (DDD) approach to develop app
  3. All the services should be design as micro services 
  4. All the microservices should be light weight i.e. REST 
  5. All the micro services should be API based 
  6. Internal communication across micro services thought event base, asynchronous integration or asynchronous HTTP polling  
  7. App should be containerized hosted
  8. Monitoring operation integration i.e. kubernetes 
  9. DevOps: automation when code check-in; code should build , test and deploy in production
  10. Complete functional testing should be automated   

Best Software Design Principles

Top 10 Software Design Principles


1. Keep it simple, stupid (KISS):

This principle noted by U.S. Navy in 1960.This principle state that your software design should be simple not complex. Easily end user can use the software also with less training developer can board and start delivering.

How to implement:
  • UI Design: Any layman can use your software or less training require for the end users 
  • Implementation and deployment:  This should take less time to deploy in any environment and easy to configure customer specific data so that earliest possible system can be live
  • Architectural design: Need to keep it simple and understandable by all the developers. 
  • Class and methods design: Class and method design should be simple, should not unnecessary implement the design patterns, if require the patterns then only implement. 
  • Maintainability and code readability: Code is written such a way that easy to maintain when move to production. Code should have good readability. 
Reference:
https://en.wikipedia.org/wiki/KISS_principle

2. Don’t Repeat yourself (DRY):

What does mean of doesn’t repeat yourself in the software development? This mean you write the code in one place and keep re-using the piece of code in different places.

How to implement:
  • Don’t write big methods instead split the big method to small reusable code.
  • Create the utility class to include all common methods (mathematical calculation methods )  
  • Create a class for the contact variables
  • Business logic layer should be design such a way that method should be re-usable 
  • Well define the blue print of design so that all the developer know about the design and re-use the code instead of re-writing the code.
  • Create the model layer (data structure ) which can be use in the DAL, BLL and UI layer 
Reference:
en.wikipedia.org

3. SOLID:

Reference:
www.oodesign.com
docs.microsoft.com

4. Independent testable components:

Component or class should be independent testable, in other word the piece of code written can be unit testable.

How to implement:
  • There should not be any dependency in the class or method
  • Implement DP (dependency injection) or IOC (inversion or control ) if any object need to create in the class’s methods.

5. Maintain the version:

when every you release the software or code there should be opportunity to maintain the version.

How to implement:
  • DLL or exe should have the version no. on each release
  • When you develop API then maintain the version by URI, query string , custom header and accept header parameter either one way
  • Class : use inheritance, static or dynamic polymorphism or interface

6. Separation of concerns:

This (SoC) principle state that each module will address different concern in other word I will say that you divide the software in different layers.

How to implement:
  • Divide the layers as UI , BLL and DAL
  • Implement MVC, MVVM or MVP design pattern
  • Implement micro service (domain driven design )
  • Implement service oriented architecture

7. What you produce other can consume:

What you develop the software there are different kind of users i.e. end user, documentation guy, who maintain the code after push production so always keep in mind when design someone else will be consuming or owning the portion of software .

7. What you produce other can consume:

Under construction

8. Principle of Least knowledge:

Under construction

9. Minimize upfront design:

Under construction

10. Flexible enough to integrate with third party components:

Under construction

Friday, August 14, 2020

List<T> Class in .Net - C#



     Definition Of List<T>:

  • List<T> class has been introduce in framework 2 (also part of C# 2)
  • This is part of generic feature of .Net and included in the namespace System.Collections.Generic. This is family of collection class and provide all the basic features of collection like add, remove, insert,foreach,find etc.
  • This allow us to create strong type of list of objects which can be access by the index, also when create List<T> type of objects then it does not require boxing and un-boxing from the object class.

     Syntax:

     List<T> objectName=new List<T>();

     Example code of List<T>

I. Create int-List<T> and retrieve data from objectSuppose we need to store bunch of numbers in a variable then we can take a List<int> variable:

           //Creating List<T> int type object
            List<int> number = new List<int>();
           //Add item to List
            number.Add(1);
            number.Add(2);
            number.Add(3);
            number.Add(4);
           //loop through all the item by foreach loop
            foreach (int num in number)
            {
                Console.WriteLine(num);
            }

            //loop through all the item by for loop
            //and get item by List index
            for (int i = 0; i < number.Count;i++ )
            {
                Console.WriteLine(number[i]);
               
            }
II. Create string-List<T> and retrieve data from objectCreate a List with string type: Suppose we need to store bunch of geometrical shape in a variable then we can take a List<int> variable:

 //Creating List string type object
            List geoShape = new List();
            //Add item to List
            geoShape.Add("Triangle");
            geoShape.Add("Circle");
            geoShape.Add("Square");
            geoShape.Add("Rectangle");
            //loop through all the item by foreach loop
            foreach (string shape in geoShape)
            {
                Console.WriteLine(shape);
            }

            //loop through all the item by for loop
            //and get item by List index
            for (int i = 0; i < geoShape.Count; i++)
            {
                Console.WriteLine(geoShape[i]);

            }
III. Create custom class-List<T> and retrieve data from objectCreate a List with custom type: I have taken an example of product model class to explain how to add list of products value to the List<Product> object.

public class Product
{
       public int ID { get; set; }
       public string Name { get; set; }
       public float Price { get; set; }
}

class Program
{
        static void Main(string[] args)
        {
            Product product = new Product();
            //Creating List Product class type object
            List productList = new List();
           //There are other way to assign product data, i have use in way to easy to 
           //understand the beginner
            product.ID = 1;
            product.Name = "Demo Product 1";
            product.Price = 400000;
            //Add product data to product List
            productList.Add(product);
            product = new Product();
            product.ID = 1;
            product.Name = "Demo Product 1";
            product.Price = 500000;
            //Add product data to product List
            productList.Add(product);

            //loop through all the item by foreach loop
            foreach (Product p in productList)
            {
                Console.WriteLine(p);
            }

            //loop through all the item by for loop
            //and get item by List index
            for (int i = 0; i < productList.Count; i++)
            {
                Console.WriteLine(productList[i]);

            }

            Console.ReadLine();

     }
}


     Interview Question on List<T> 

  •     When we have array then why we require List<T>
  •     What is the difference between array and List<T>
  •     What is the difference between ArrayList and List<T>
  •     What is the difference between IEnumerable and List <string>
  •     How to add item in the List or List<T>?
  •     How to count number of item in List<T>?
  •     What are the different way to retrieve complete data from the List<T> and which is the preferable?
  •     How to insert the data in List<T> at an index place?
  •     How to remove data from List<T>?

C# DotNet ArrayList (With example and interview questions)


I. Introduction To ArrayList:


  • ArrayList is similar to the array class but this grows dynamically as data grow and can have different type of data (i.e int,string) in a single variable.
  • Initial capacity of ArrayList will be 16 member as soon as 16 occupy then it grow to double the size as 32 member(increase array size as require).
  • ArrayList been implemented with the interfaces IList, ICollection, IEnumerable, ICloneable and it is available in the namespace System.Collection.

II. Syntax To Create ArrayList Object:

       ArrayList objectName=new ArrayList();

III. Example code of ArrayList:

Below example, created an ArrayList object and add item of int, string &  decimal data type also shown how to retrieve the item from collection

            //Create ArrayList object
            ArrayList arraylistObjct = new ArrayList();
            //Add integer value in the ArrayList object
            arraylistObjct.Add(1);
            arraylistObjct.Add(2);
            //same variable you can add string also
            arraylistObjct.Add("Circle");
            arraylistObjct.Add("Tringle");
            //same variable you can add flot value aslo
            arraylistObjct.Add(12.23);
            arraylistObjct.Add(34.32);

         Console.WriteLine("Output from foreach loop:");
            //loop through the arraylistObjct object and read all item
            foreach (var v in arraylistObjct)
            {
                Console.WriteLine(v);
            }
          Console.WriteLine("Output from foreach loop:");
            //loop through all the item by for loop
            //and get item by index
            for(int i=0;iarraylistObjct.Count;i++)
            {
              //get the ArrayList data by index
                Console.WriteLine(arraylistObjct[i]);
            }

            Console.ReadLine();

IV. Interview questions on ArrayList:



    1. What is the difference between Array and ArrayList?
    2. ArrayList can have different type of
    3. How ArrayList can have different type of data type in a single variable, please explain how         internally this manage also?
    4. What is the default size of ArrayList?

Memory Management in DotNet Framework



Introduction of garbage collection:

Dot net having automatic memory management through garbage collection (GC) . With this feature dot net will allocate the memory, track and release (cleaned up) the object from memory. So developers need not to be worry about the memory release or manually write the code to clean up the objects from memory.
But in all the cases memory is not handled by the GC, GC is only working for the managed code and unmanaged resource object has to be cleaned up manually mean we have to write the code for that.
However, when we create objects that encapsulate unmanaged resources, we must explicitly(directly) release the unmanaged resources when we are finished using them in your application. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource.
Dot net divide the source code in two different cases as below:

  • Managed code: Dot net code which is executed by framework
  • Unmanaged code: Code does not handled by framework.
Hope with the above definition we are very much clear about memory management when we have to release memory explicitly (directly) and when we have to leave the memory management on GC (implicit memory management).

We can do the memory management by two ways:

  • Implicit : through GC, only for the managed code
  • Explicit: manually writing the code to clean up the resources, it can be either managed or unmanaged code.

Understanding Memory management

When we are creating the instance of a class with new keyword then class object occupy a memory location and assign an address (reference) to the object. These objects are created on heap with a sequence order. Heap having a special pointer begin at position 0 on the heap and is incremented for the size of the allocated object. This establishes the beginning point for the next object to be allocated. The process continues until memory is full.


In the above picture four objects A, B, C and D have been allocated on the heap. After each allocation the next object pointer pointes to the top of the last object allocated.

When heap is full and another object try to occupy space in memory then two things can happen as below:

  • If all objects are live and in use, an out of memory exception thrown.
  • Our program must clean some of the memory space in memory.

Inside the Garbage collection

The purpose of GC is to clean up the unused objects on heap which is no longer is used by other objects. When an object goes out of scope or all the references to it are set to null that all objects are going to be clean up by GC.

1. Live graph:  
Live graph (active object graph) generated by GC after visiting in all the available objects in memory. All objects which all are not in the live graph that all objects are no longer use in applications and going to be cleaned up by GC. After GC fire objects will be cleaned up and available object compact with each other in the heap. Now pointer will be pointing at the next available heap memory location.

2. GC process::  
Garbage collection process is happening in three stages as below:
  • Beginning GC: In this stage GC traverse the entire object to find the status of the object and build the live graph (active object graph). EX: As in the below figure A is the root object, pointing the object B and D. Further object B having the reference of the object F.
  • During GC: Since object C and E are no longer reference by any of the objects, so C and E is going to be cleaned up by GC. In the live graph these both objects C and E will not be available.
  • After GC: The last stage shows how heap objects are compact and next object pointer is reset and ready for the next object to allocated. 
Have a look to the below image for GC process:

Garbage collection optimization

Generation : The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

  1. Generation 0: This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation. Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection. Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.
  2. Generation 1: This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.
  3. Generation 2: This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.
Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).

Survival and Promotions Objects that are not reclaimed in a garbage collection are known as survivors, and are promoted to the next generation. Objects that survive a generation 0 garbage collection are promoted to generation 1; objects that survive a generation 1 garbage collection are promoted to generation 2; and objects that survive a generation 2 garbage collection remain in generation 2.

When the garbage collector detects that the survival rate is high in a generation, it increases the threshold of allocations for that generation, so the next collection gets a substantial size of reclaimed memory. The CLR continually balances two priorities: not letting an application's working set get too big and not letting the garbage collection take too much time.
Ephemeral Generations and Segments Because objects in generations 0 and 1 are short-lived, these generations are known as the ephemeral generations.

Ephemeral Generations and Segments Because objects in generations 0 and 1 are short-lived, these generations are known as the ephemeral generations.
Ephemeral generations must be allocated in the memory segment that is known as the ephemeral segment. Each new segment acquired by the garbage collector becomes the new ephemeral segment and contains the objects that survived a generation 0 garbage collection. The old ephemeral segment becomes the new generation 2 segment.

The ephemeral segment can include generation 2 objects. Generation 2 objects can use multiple segments (as many as your process requires and memory allows for).

The amount of freed memory from an ephemeral garbage collection is limited to the size of the ephemeral segment. The amount of memory that is freed is proportional to the space that was occupied by the dead objects.

Finalize and Destructor

Finalize or destructors are more expensive to clean up objects because this works in two round to cleaned the object from memory.

  • Finalize method called for the object and object move to Finalization queue.
  • Now when GC invoke, the entire object which all were available in the Finalize queue move to the F-Reachable queue. 
  • Still objects are not garbage, again when the GC fire then it identify these objects and cleaned up from the memory.

Dispose:

In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive. Apply dispose method in the class is the best way to manage the unmanaged resource memory management.

// Design pattern for a base class.
public class Base: IDisposable
{
   //Implement IDisposable.
   public void Dispose() 
   {
              // Free other state (managed objects).
           GC.SuppressFinalize(this); 
   }

}
Real world example: Suppose in the program need to create an object to read a text file then text file object will be unmanaged code and require manual cleanup by IDisposable pattern.

public class TextReaderClass: IDisposable
{
   private TextReader fileReader;
   
   public TextReaderClass()
   {
       this. fileReader = new TextReader();
   }

   public void Dispose()
   {
        fileReader.Dispose();
       GC.SuppressFinalize(this);
   }
}

References:

http://msdn.microsoft.com/en-us/library/ee787088(v=vs.110).aspx

Azure Function or Serverless Function

In this blog I covered what is Azure function? Why to use azure function? How to create azure function from azure portal and how to pass pa...