ASP.NET Application Life Cycle

When a ASP.NET web application is launched, a series of steps are carried out. These steps combined are known as Application Life Cycle.

Below are the life cycle steps:

  • Application Start: Application’s lifecycle starts when a user makes a request for a web application to the web server. This generally happens when the first user visits the web application for the first time. At this time, a method named Application_Start is executed by the web server. All global variables are set set to their default value in this method. If there is any other initialization, that is also done in this method.
  • Object Creation: Application objects such as HttpContext, HttpRequest and HttpResponse are created and initialized. HttpContext object will be created newly for every request made to the application and acts as a container for for HttpRequest, HttpResponse, Server, Session, Cache, User details etc. HttpRequest object contains information about current request, cookies, browser information etc. HttpResponse contains the response that is sent back to the client.
  • HttpApplication object created: HttpApplication object is created and assigned to the request. The request is processed by this object by calling various events.
  • Dispose: This method is called before the application instance is destroyed. This can be used to manually release any unmanaged code.
  • Application End: At this stage, application is finally unloaded from memory.

ASP.NET Glossary

 

ASP.NET It is a web development platform which provides a programming model and various services required to build web applications for desktop and mobile.
Common Language Runtime (CLR) CLR performs memory management, debugging, exception handling, thread and code execution, safety, verification and compilation of code.
Managed Code This is the code that is directly managed by CLR. When this code is compiled, compiler converts the source code to IL (Independent Intermediate Language) code. JIT (Just-In-Time) compiler compiles this IL code into CPU specific native code.
.NET Framework Class Library This is a library that contains reusable types like classes, interfaces, structures, enum values etc.
Common Language Specification CLS contains specification for the languages that are supported by .NET. It defines a set of rules and restrictions that every language must follow which runs under .NET Framework, hence enabling cross-language integration. It is a subset of CTS.
Common Type System CTS describes the data types that can be used by managed code by providing guidelines for declaring, using and managing them during runtime and cross-language integration. For example, int in C# and integer in VB.NET is represented as Int32 in CLR data type.
Metadata It is the binary information that describes the characteristics of a resource. This information includes assembly description, data types and members, references, security permission etc.
Assembly Assemblies are the building blocks of .NET Framework applications; they form the fundamental units of deployment, version control, reuse, activation scoping and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.
AJAX ASP.NET AJAX contains the components using which a developer can create applications that update data on a website without the complete reload of the page.
ADO.NET It is used to work with data and databases like SQL Server, OLEDB etc. We can perform CRUD operations on the data.
WF Windows Workflow Foundation is used to build workflow-based applications in windows that can contain activities, workflow designer etc.
WPF Windows Presentation Foundation  is a UI framework that creates desktop client applications. The WPF development platform supports a broad set of application development features, including an application model, resources, controls, graphics, layout, data binding, documents, and security.
WCF Windows Communication Foundation is used to build service oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another.

 

Introduction to ASP.NET Web API

  • As per Wikipedia, API (Application Programming Interface) is a set of subordinate definitions, communication protocols and tools for building software.
  • With API, we can access the features or data of an application with the help of specific set of functions.
  • Web API is an API interface over web applications, that can be accessed using HTTP protocol.
  • Web API can be built using different technologies like Java, .NET etc.
  • ASP.NET Web API is a framework for building HTTP based services that can be accessed in different applications on different platforms like web, windows and mobile.
  • It is an ideal platform to build RESTful services.
  • It is built on top of ASP.NET and supports the request/response model of the same.
  • It supports different formats of response data like JSON, XML, BSON etc.
  • It can be hosted in IIS, self hosted or any other server that supports .NET 4.0+.
  • It supports only HTTP protocol. If you want to use any other protocol, you can use WCF.
  • It maps HTTP verbs to methods.
  • Does not support Reliable Messaging and Transactions.

Implicitly Typed Local Variables in C#

We usually specify the data type of the variable while declaring it like int age; string name; etc. This is known as explicitly typed variables.

But sometimes, we need to create a variable that can hold any variable of any data type. We can do this using var keyword. This is known as implicitly typed variables. The var keyword can be used in place of specifying a specific data type such as int, string etc. When you do so, the compiler will automatically infer the underlying data type based on the initial value used to initialize the local data point.

Below is a sample code:

var myInt = 1234;
var myBool = true;
var myStr = "Hello";

Console.WriteLine("Value of myInt is: " + myInt + " and type of myInt is: " + myInt.GetType().Name);
Console.WriteLine("Value of myBool is: " + myBool + " and type of myBool is: " + myBool.GetType().Name);
Console.WriteLine("Value of myStr is: " + myStr + " and type of myStr is: " + myStr.GetType().Name);

Below is the output of the above code:

Restrictions on implicit typed local variables

    • Implicit typing applies only to local variables in a method or property scope.
    • It is illegal to use var keyword to define return values, parameters or field values of a custom type.
      For example, below are invalid usage of var keyword:
      class varUsage
      {
      // Error: var cannot be used as field data
      private var age=100;
      // Error: var cannot be used as a return value or parameter type
      public var Add(var a, var b){}
      }
    • Local variables declared with the var keyword must be assigned an initial value at the time of their declaration. We cannot assign null value to varExample:// Error: Must assign an initial value to var variables
      var data;// Error: Must assign value at the time of declaration
      var data;
      data = “Hello”;// Error: Can’t assign null
      var data = null;

      // No error as this is a reference type;
      var car = new Vehicle();
      car = null;

      // Below code is also fine
      var data = “hello”;
      var data1 = data;

    • It is allowed to return an implicitly typed local variable to the caller, provided the method return type is the same as of var-defined data type.Example:
      static int GetValue()
      {
      var value=9;
      return value;
      }

    Implicit typed data is strongly typed data

    Implicit typed data effects only at compile time. After that, that variable is treated as if it was declared with that data type. You cannot assign a value of different data type to that variable, even at later point of time. It will result in compile time error.
    Example:
    static void GetValue()
    {
    var str = “Hello World”;
    str = “Hiiii”;

    // Error: Cannot implicitly convert type ’int’ to ‘string’
    str = 1234;
    }

Arrays in C#

Arrays are a set of items of same data types which are accessed using numerical index. This index starts with 0. Arrays have pre-specified length. For example, an array of 5 integers, an array of 7 strings etc.

Below is the sample code for array:

static void Main(string[] args)
{
    // Declaring array. 3 is the total number of elements in the array.
    int[] codes = new int[3];

    // Filling array
    codes[0] = 1234;
    codes[1] = 2222;
    codes[2] = 9876;

    // Array Declaration and Initialization. 
    // You need not to specify the size of array in below case. 
    string[] countries = new string[5] { "India","Nepal","China","USA","Mexico"};

    // Accessing array elements using indexes
    for(int i=0;i<codes.Length;i++)
    {
        Console.WriteLine(codes[i]);
    }
    Console.WriteLine();
    foreach (string cntry in countries)
        Console.WriteLine(cntry);

    Console.ReadLine();
}

Below is the output of the above code:

You will get compiler error in the below code “An array initializer of length ‘2’ is expected”, as defined length of array is less as compared to the number of items assigned n it.

string[] countries = new string[2] { "India","Nepal","China","USA","Mexico"};

The value of e^x is 1+x+(x^2)/2+(x^3/3) …… (x^n/n) using C#

The value of e^x is 1+x+(x^2)/2+(x^3/3) …… (x^n/n). We are taking values of x and n from user.
Below is the code for the above problem in C#:

class Program
{
    static void Main(string[] args)
    {
            Console.WriteLine("The value of e^x is 1+x+(x^2)/2+(x^3/3) ...... (x^n/n) ");
            Console.WriteLine("Enter the value of x: ");
            int x = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the value of n: ");
            int n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Sum is: " + Exp(x,n));
            Console.ReadLine();
     }
     static double Exp(int x, int n)
     {
            double sum = 1;
            for (int j = 1; j <= n; j++)
            {
                sum = sum + (Math.Pow(x, j) / j);
            }
            return sum;
      }
}

Below is the output of above code:

Method Overloading

In Method Overloading, we define multiple methods with same name, but different parameters like number of parameters, different data types of parameters.

Below is a sample code:

class Program
{
    static void Main(string[] args)
    {
        AddNumbers(3, 4);
        AddNumbers(1.5, 6.7);
        AddNumbers(1256564, 3466757);
        AddNumbers("Hello", "3466757");
    }
    static void AddNumbers(int a, int b)
    { Console.WriteLine("{0} + {1} = {2}", a,b,a+b); }
        
    static void AddNumbers(double a, double b)
    { Console.WriteLine("{0} + {1} = {2}", a, b, a + b); }

    static void AddNumbers(long a, long b)
    { Console.WriteLine("{0} + {1} = {2}", a, b, a + b); }

    static void AddNumbers(string a, string b)
    { Console.WriteLine("{0} + {1} = {2}", a, b, a + b); }
}

Below is the output of above code:

Optional Parameters in C# methods

In C#, you can create methods that can take optional parameters. This allows the caller to call a method while omitting unnecessary arguments. In optional parameters, we assign a default value to a parameter of the method. In case we do not assign a value to that parameter, the control takes the default value of that parameter.

Below is a sample code:

class Program
{
    static void Main(string[] args)
    {
         Console.WriteLine("Optional Parameter Demo...");
         // We have passed only one parameter value in the method. Hence, it will take default value for another parameter.
         OptionalParameter("David");
         Console.WriteLine();
         // We have passed both the parameter values in the method. Hence, it will overwrite the default value and use this value.
         OptionalParameter("David", "US");
    }
    static void OptionalParameter(string name, string country="India")
    {
         Console.WriteLine("Name: " + name);
         Console.WriteLine("Country: " + country);
    }
}

Below is the output of above code:

Parameter Modifier (out, ref, params)

Parameter Modifiers are used to control how parameters are passed to the methods. There are three types of parameter modifiers: ref, out and params. If there is no modifier mentioned, it means it is passed value meaning the called method receives a copy of the original data. We cannot define overloaded method if it differs from another method only on out and ref.

out modifier
Output parameters must be assigned by the method being called, hence are passed by reference. We use out keyword to define output parameters.

class Program
{
     static void Main(string[] args)
     {
          int resultOut;
          AddNumbersOut(10, 20, out resultOut);
          Console.WriteLine("Value of result using out parameter: " + resultOut);
     }
     static void AddNumbersOut(int num1, int num2, out int sum)
     {
          sum = num1 + num2;
     }
}

If the called method fails to assign output parameters, a compiler error is raised.

ref modifier
The value is initially assigned by the caller and may be optionally reassigned by the called method. Data is passed by reference. No compiler error is generated if the called method fails to assign a ref parameter.

class Program
{
      static void Main(string[] args)
      {
          int resultRef=0;
          AddNumbersRef(10, 20, ref resultRef);
          Console.WriteLine("Value of result using out parameter: " + resultRef);
      }
      static void AddNumbersRef(int num1, int num2, ref int sum)
      {
          sum = num1 + num2;
      }
}

If caller method fails to assign the ref variable before passing it to the method, a compiler error is generated.

params modifier
This modifier allows you to send in a variable a number of arguments as a single logical parameter. A method can have a single params modifier, and it must be the final parameter of the method. Arguments marked with the params keyword can be processed if the caller sends in a strongly typed array or a comma-delimited list of items. These arguments are of same data type.

To understand this, lets create a method which can take any number of arguments and return the sum of those values.

class Program
{
     static void Main(string[] args)
     {
          int resultParams;
          AddNumbersParams(out resultParams, 10,20,30,40,50);
          Console.WriteLine("Value of result using out parameter: " + resultParams);}
     }
     static void AddNumbersParams(out int sum, params int[] nums)
     {
          sum=0;
          if (nums.Length == 0)
              sum = 0;
          for(int i=0;i<nums.Length;i++)
          {
              sum = sum + nums[i];
          }
     }
}

If you do not declare params as the last parameter, it will raise a compiler error.

Custom Methods and Parameters in C#

There are lots of in-built methods in C# that have their own functionality like Main() method, ToUpper(), String.Compare(string, string) etc. These methods can either return a value or not, or can have parameters or not. Methods are basically created for reuse, create once and we can use many times, anywhere in our program.

Basic syntax of a method in C# is:
returnType methodName(parameterList)
For example:

// The name of this method is AddNumbers which returns a value of type int and accepts two parameters, both of type int.
int AddNumbers(int num1, int num2)
{
     int sum = num1 + num2;
     return sum;
}
// The name of the method is SayHello. The return type of this method is void which means it does not return any value. 
// The parameter list is also empty, hence it does not accepts any parameter.
void SayHello()
{
    Console.WriteLine("Hellozz!");
}

Above are some of the ways you can create your own methods with/without parameters and with/without return values. The method names are normal variable names. We cannot have C# keywords as method names. Methods can have any number of parameters but can only return single value of any data type.

Calling/Invoking a Method
A method created is of no use until it is used anywhere in your program. A method can be used if it called somewhere in your program. Let’s use above created method in our program. Below is the sample code:

// In below class, there are three methods: Main() is the in-built method, AddNumbers() and SayHello() are custom methods.
class Program
{
        static void Main(string[] args)
        {
            // We are calling AddNumbers() method twice which indicate that we can reuse the methods.
            // We are passing two parameters of int type to AddNumbers() method which will return the sum of these two numbers.
            // We can use this returned value, in this case sum of two numbers, anywhere in our program.
            int sum = AddNumbers(20, 40);
            Console.WriteLine(sum);
            Console.WriteLine(AddNumbers(10, 34));
            SayHello();
        }
        static int AddNumbers(int num1, int num2)
        {
            int sum = num1 + num2;
            return sum;
        }
        static void SayHello()
        {
            Console.WriteLine("Hellozz!");
        } 
}

Below is the output of above code:

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started