Skip to main content

Explore Action Filters in Asp.Net MVC Applications

What is Action Filters

In the Asp.Net MVC application there are controllers, each controller defines action methods that generally have one to one relation ship with views or each actions use performs on the page.
User actions means we can say like clicking on buttons, links or submitting a form. When this kind of action performs request is routed to controller and finds the action method.
Now if we want to perform some action, calculate login or check some values either before calling an action method or after action method completes Action Filters are used.

Asp.Net MVC provides actions filters which we can say custom attributes which provides facility to perform some behavior at pre-action or post-action time of controller action method.

Now lets see the available types of the Action filter in Asp.Net MVC

Action Filter Types

Asp.Net MVC provides 4 types of action filters like Authorization filter, Action filter, Result filter and Exception filter. Please find the below description for each type of action filter.

Authorization filter

Generally it is used to implement authorization and authentication for action method, It is related to security of the application whether to execute action method or not, it also check for the authentication and request property.
As an example you can see AuthorizeAttribute class for Authorization action filter.

Action filter

Generally it is used to perform some extra processing, like before executing any action method we want to check like user is logged in or not, or user has enough permission to execute this action method or not.
If session expired and we want to transfer request to login page etc.

Result filter

Generally it is used to perform extra processing of the result like modifying the response that means if we want to execute a login before or after the view result get executes we can use this filters.
As an example you can see OutputCacheAttribute class for result filter.

Exception filter

It executes when ever there is an unhanded exception thrown by anywhere in the action method. Exception filters can be used for the tasks like logging an error or displaying an error page 404
As an example you can see HandleErrorAttribute class for exception filter.

Explore the SQL Server Cursors basics

Cursor is the database object in MS SQL Server to retrieve the data from the result set one row at a time either in backward direction or forward direction. Generally in T-SQL command it will direct operates on all the rows of result at one time, so when ever we want to process based on the condition 1 by 1 for our process or data is dependent on the previous actions cursor is the suitable feature to use.

Now lets see the Life cycle of the cursor as below

Declare the cursor

Like any other object we need to declare the cursor first, we can declare the cursor by defininf SQL statement which returs a result set.

Open the cursor

Once cursor is declared we can open and populate by executing the SQL statement defined in the cursors.

Fetch records one by one from the Cursor

One cursor is opened we can fetch rows one by one or in a block for the data manipulation.

Close Cursor

One we have fetched all the rows and manipulated data as required we need to close the cursor explicitly.

Deallocate Cursor

One we have close the cursor at the end, we need to delete the cursor definition and free all the system resources associated with the cursor.

Cursor Syntax

Declare Cursor SQL Command is used to declare the cursor with provided options. There are some options we need to use while declaring the curosr which impact on the performance of cursor.

The complete syntax of declaring a cursor is as below


DECLARE name_of_cursor CURSOR
[LOCAL | GLOBAL] -- Local or global define the scope of the cursor, default it is local only
[FORWARD_ONLY | SCROLL] -- It defines the direction of the cursor either forward or backward
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD] -- It define the basic type of cursor
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] -- It define the locks
FOR Select_Query -- Here you can define select or update statement as required
FOR UPDATE [field1,field2,field3 ....., fieldn] -- Here provide the list of fields/columns to updated

Syntax to Open a Cursor

A SQL cursor can be either opened locally or globally. By default it is opened locally.

OPEN [GLOBAL] name_of_cursor

Syntax to Fetch rows from Cursor

Fetch statement provides different different options to retrieve the rows from the cursor. Default NEXT option is applied.


FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
FROM [GLOBAL] name_of_cursor
INTO @Name_Of_Variable[1,2,3,4, .....n]

Syntax to Close the Cursor

Close statement closed the cursor explicitly.


CLOSE name_of_cursor -- Once it is closed then it can be reopen

Syntax to Deallocate Cursor at the end

Deallocate statement delete the cursor definition and free all the system resources associated with the cursor.

DEALLOCATE name_of_cursor -- Once cursor is deallocated it can not be open again.

See the sample data as below from which we will retrieve the data using cursor.

The full cursor example

SET NOCOUNT ON

DECLARE @ID int
DECLARE @Title varchar(100)
DECLARE @ISBN varchar(100)
Declare @Price Decimal

DECLARE all_book CURSOR
STATIC FOR
SELECT Id,Title,Isbn,Price from Books

OPEN all_book
IF @@CURSOR_ROWS > 0
BEGIN
FETCH NEXT FROM all_book INTO @ID,@Title,@ISBN,@Price

WHILE @@Fetch_status = 0
BEGIN
Print 'Id :'+Convert(VarChar(20),@ID) + ', Price :'+Convert(VarChar(20),@Price)+ ', Title :'+@Title + ', ISBN :'+@ISBN

FETCH NEXT FROM all_book INTO @ID,@Title,@ISBN,@Price
END
END

CLOSE all_book
DEALLOCATE all_book
SET NOCOUNT OFF

When you run the cursor you will see the below out put.

Summary

in this article we have see the basic concept and syntax of the SQL Server Cursor. I hope it will help you to understand the cursors. i would like to have feedback from my blog readers

Serialization & Deserialization using JSON In C#

Introduction

The very useful method of converting JSON object to .Net object and .Net object to Json object is using the JsonConvert. It converts Json objects to .Net object and with the Same property with value and .Net objects to equivalent JSON object.

In this article we will see how to serialize .NET type objects into JSON object and then deserialize data in the JSON format back into .NET types using the JsonConvert class.

What is JSON?

JSON (JavaScript Object Notation) is one lightweight and efficient data exchange format or we can say like JSON is most desirable data encoding format which allows fast exchanges of small amounts of data between client browsers and web services or web api.

JsonConvert

JsonConvert class is in the namespace “Newtonsoft.Json” and for this namespace you need to add reference of Newtonsoft.Json dll or nuget package. You can install a Newtonsoft.Json nuget package by command “Install-Package Newtonsoft.Json” in package manager console.

If we want to convert .Net object to Json object then the SerializeObject() method will be used and when we want to convert Json object back to .Net object then DeserializeObject() method will be used from the JsonConvert class

JSON Serialization

Now lets see the JSON Serialization process with code example, we have an instance of Customer class as below

public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNo { get; set; }
}

Now create an object of Customer class and initilize value of each properties. Then call SerializeObject() of JsonConvert class with passing Customer object.
See the below codesnippet

// Serializaion .Net Object
Customer customer = new Customer();
customer.Id = 1;
customer.Name = "Tarun Dudhatra";
customer.Email = "email@address.com";
customer.PhoneNo = "5*9*9 5*8*5";

// Convert Customer object to JOSN encoded format
string jsonDataString = JsonConvert.SerializeObject(customer);

Console.Write(jsonDataString);
Console.ReadKey();

It will return the JSON string as below

{"Id":1,"Name":"Tarun Dudhatra","Email":"email@address.com","PhoneNo":"5*9*9 5*8*5"}

JSON Deserialization

See the below JSON Deserialization process with code example, we have same Customer class string as below

{"Id":2,"Name":"FirstName LastName","Email":"email@address.com","PhoneNo":"5*9*9 5*8*5"}

Now call the DeserializeObject() of JsonConvert class and pass the object type of Customer so it will deserialize it into Customer Class.
See the below codesnippet

Deserializaion JSON Object

string JSONObject = @"{ 'Id':2,'Name':'FirstName LastName','Email':'email@address.com','PhoneNo':'5*9*9 5*8*5'}";

Customer customer = JsonConvert.DeserializeObject<Customer>(JSONObject);

Console.WriteLine( "Id : " + customer.Id);
Console.WriteLine( "Name : " + customer.Name);
Console.WriteLine( "Email: " + customer.Email);
Console.WriteLine( "Phone: " + customer.PhoneNo);
Console.ReadKey();

It will print the below out put on the screen

Id : 2
Name : FirstName LastName
Email: email@address.com
Phone: 5*9*9 5*8*5

That’s it, in my upcoming article we will see other interesting stuff like this.