Encryption and decryption using C#.net

      Encryption is the process of translating plain text data into something that appears to be random and meaningless.

Decryption is the process of translating random and meaningless data to plain text.


    Use the using statement on the following namespaces: 
·         System
·         System.Security
·         System.Security.Cryptography
·         System.Text
·         System.IO

      There are many modern cryptographic methods used for encryption and decryption and it is classified in to two classes of key based algorithms.

1.  Symmetric Algorithm
a.       Same key is used for both Encryption and Decryption. The key will be kept as secret.
b.       Symmetric Ciphers is divided into Stream and Block Ciphers.
                  i.      Stream Ciphers – It encrypts a single bit of plain text at a time.
                 ii.      Block Ciphers –   It takes number of bits and encrypts them as a single unit.
2.  Asymmetric Algorithm
a.       Different key is used for Encryption and Decryption. It is also called as public Key algorithm.
b.       Encryption key is public and the Decryption key will be kept as secret.
c.       By using this asymmetric algorithm, anyone can encrypt the message by using encryption key but
          the message can be decrypted only by using decryption key.



1. Triple DES
      Triple DES was designed to replace the original Data Encryption Standard (DES) algorithm, which hackers eventually learned to defeat with relative ease. At one time, Triple DES was the recommended standard and the most widely used symmetric algorithm in the industry.
      Triple DES uses three individual keys with 56 bits each. The total key length adds up to 168 bits, but experts would argue that 112-bits in key strength is more like it.
      Despite slowly being phased out, Triple DES still manages to make a dependable hardware encryption solution for financial services and other industries.
2. RSA
      RSA is a public-key encryption algorithm and the standard for encrypting data sent over the internet. It also happens to be one of the methods used in our PGP and GPG programs.
      Unlike Triple DES, RSA is considered an asymmetric algorithm due to its use of a pair of keys. You’ve got your public key, which is what we use to encrypt our message, and a private key to decrypt it. The result of RSA encryption is a huge batch of mumbo jumbo that takes attackers quite a bit of time and processing power to break.
3. Blowfish
      Blowfish is yet another algorithm designed to replace DES. This symmetric cipher splits messages into blocks of 64 bits and encrypts them individually.
      Blowfish is known for both its tremendous speed and overall effectiveness as many claim that it has never been defeated. Meanwhile, vendors have taken full advantage of its free availability in the public domain.
      Blowfish can be found in software categories ranging from e-commerce platforms for securing payments to password management tools, where it used to protect passwords. It’s definitely one of the more flexible encryption methods available.
4. Twofish
      Computer security expert Bruce Schneier is the mastermind behind Blowfish and its successor Twofish. Keys used in this algorithm may be up to 256 bits in length and as a symmetric technique, only one key is needed.
      Twofish is regarded as one of the fastest of its kind, and ideal for use in both hardware and software environments. Like Blowfish, Twofish is freely available to anyone who wants to use it. As a result, you’ll find it bundled in encryption programs such as PhotoEncrypt, GPG, and the popular open source software TrueCrypt.
5. AES
      The Advanced Encryption Standard (AES) is the algorithm trusted as the standard by the U.S. Government and numerous organizations.
       Although it is extremely efficient in 128-bit form, AES also uses keys of 192 and 256 bits for heavy duty encryption purposes.
      AES is largely considered impervious to all attacks, with the exception of brute force, which attempts to decipher messages using all possible combinations in the 128, 192, or 256-bit cipher. Still, security experts believe that AES will eventually be hailed the de facto standard for encrypting data in the private sector.







SQL in detail

Difference between writing SQL query and stored procedure ?

SP is execute more faster than query statement.
SP, is already compiled Object.
Query is Sql Statement where as SP batch of Sql Statement.

In a query memory management is more high than the SP.

Stored procedure execute server side that's why it reduces network traffic. SQL query also executes on server also but if you have big query then it will take more time comparison to Stored Procedure to traverse from client side to server.

TRUNCATE and DELETE in SQL

SQL Delete Statement
The DELETE Statement is used to delete rows from a table.

Syntax of a SQL DELETE Statement

DELETE FROM table_name [WHERE condition];



SQL TRUNCATE Statement
The SQL TRUNCATE command is used to delete all the rows from the table and free the space containing the table.

Syntax to TRUNCATE a table:

TRUNCATE TABLE table_name;



Difference between DELETE and TRUNCATE Statements:

DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.

TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.



Filters in MVC

In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides filters for this purpose.

ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes. Filters can be applied to an action method or controller in a declarative or programmatic way. 


Types of Filters

ASP.NET MVC framework provides five types of filters.
  1. Authentication filters - Authentication filter runs before any other filter or action method. Authentication confirms that you are a valid or invalid user. Action filters implements the IAuthenticationFilter interface. 
  2. Authorization filters - These are responsible for checking User Access.These filters used to implement authentication and authorization for controller actions.
  3. Action filters - Action Filter is an attribute that you can apply to a controller action or an entire controller. This filter will be called before and after the action starts executing and after the action has executed.
  4. Result filters - These filters contains logic that is executed before and after a view result is executed. 
  5. Exception filters - These filters can be used as an exception filter to handle errors raised by either your controller actions or controller action results.

Following diagram shows how these filters interact in filter pipeline during request and response life cycle.






Difference Between IEnumerable, ICollection and IList


    IList
    IList exists in System.Collections Namespace.
    IList is used to access an element in a specific position/index in a list.
    Like IEnumerable, IList is also best to query data from in-memory collections like List, Array etc.
    IList is useful when you want to Add or remove items from the list.
    IList can find out the no of elements in the collection without iterating the collection.
    IList supports deferred execution.
    IList doesn't support further filtering.

    IEnumerable
    IEnumerable exists in System.Collections Namespace. 
    IEnumerable can move forward only over a collection, it can’t move backward and between the  
     items.
    IEnumerable is best to query data from in-memory collections like List, Array etc.
    IEnumerable doesn't support add or remove items from the list.
    Using IEnumerable we can find out the no of elements in the collection after iterating the
    collection.
    IEnumerable supports deferred execution.
    IEnumerable supports further filtering.

ICollection 

The ICollection interface is inherited from the IEnumerable interface which means that any class that implements the ICollection interface can also be enumerated using a foreach loop. In the IEnumerable interface we don't know how many elements there are in the collection whereas the ICollection interface gives us this extra property for getting the count of items in the collection. The ICollection interface contains the following: 
Count Property
IsSynchronized Property
SyncRoot Property
CopyTo Method
The Count property is used for maintaining the count of elements in the list whereas the IsSysnchronized and SyncRoot properties help to make the collection thread-safe. The CopyTo method copies the entire collection into an array.

Temporary Tables in SQL Server

Temporary tables are stored in tempdb. They work like a regular table in that you can perform the operations select, insert and delete as for a regular table. Scope of the Local Temporary Table is the session in which it is created and they are dropped automatically once the session ends and we can also drop them explicitly. If a Temporary Table is created within a batch, then it can be accessed within the next batch of the same session.

There are two types of temporary tables; one is local and the other is global.


Local Temporary Tables 

Local temporary tables are the tables stored in tempdb. Local temporary tables are temporary tables that are available only to the session that created them. These tables are automatically destroyed at the termination of the procedure or session. They are specified with the prefix #


Creating local temporary table : -

create table #table_name
(
  column_name varchar(20),
  column_no int
)


Global temporary tables 

These are also stored in tempdb. Global temporary tables are temporary tables that are available to all sessions and all users. They are dropped automatically when the last session using the temporary table has completed. They are specified with the prefix #, for example ##table_name.


Creating Global Temporary Table : -

create table ##GlobalTemporaryTable
(
  column_name varchar(20),
  column_no int
)


Storage Location of Temporary Table

Temporary tables are stored inside the Temporary Folder of tempdb. Whenever we create a temporary table, it goes to the Temporary folder of the tempdb database. tempdb -> temporary tables.


Delete the temporary table using the drop command as follows:

DROP TABLE #temporaryTable

SQL JOIN

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.


Different SQL JOINs :

INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables

What is a Trigger

A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data.

Basically, triggers are classified into two main types:
1. After Triggers (For Triggers)
2. Instead Of Triggers

1. After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:

AFTER INSERT Trigger : This trigger is fired after an INSERT on the table.
AFTER UPDATE Trigger : This trigger is fired after an update on the table.
AFTER DELETE Trigger : This trigger is fired after a delete on the table.


2. Instead Of Triggers
INSTEAD OF TRIGGERS can be classified further into three types as:

INSTEAD OF INSERT Trigger.
INSTEAD OF UPDATE Trigger.
INSTEAD OF DELETE Trigger.

We can categorize the triggers in SQL Server in mainly three types:
Data Definition Language (DDL) Triggers.
Data Manipulation Language (DML) Triggers.
Logon Triggers.

REST services in MVC 4



REST stands for Representational State Transfer. What it says is that any request in/over HTTP should be one of the following types:

    GET – Get a resource from a server
    POST – Post/Insert/Input some information on a server
    PUT – Update some information on a server
    DELETE – Delete some information on a server

In REST architecture there is always a client and a server where the communication is always initiated by the client.

An important concept of REST is the uniform interface. The uniform interface contains a set of methods that can be understood by both the client and the server. In the HTTP uniform interface the important methods are GET, POST, PUT, DELETE, HEAD and OPTIONS. It is important to choose the right method for the right operation. For ex. if the client is going to get the resource from the server then they should use GET method. Likewise the DELETE method should be used to delete the resource and other methods has to be used appropriately based upon the action performed on the server. I wrote an article about using HTTP methods in REST applications and you can read it here.



ASP.NET MVC - Life Cycle

MVC has two life cycles −
  • The application life cycle
  • The request life cycle


The Application Life Cycle

The application life cycle refers to the time at which the application process actually begins running IIS until the time it stops. This is marked by the application start and end events in the startup file of your application.

The Request Life Cycle

It is the sequence of events that happen every time an HTTP request is handled by our application.

The entry point for every MVC application begins with routing. After the ASP.NET platform has received a request, it figures out how it should be handled through the URL Routing Module.

All routes have an associated route handler with them and this is the entry point to the MVC framework.




The MVC framework handles converting the route data into a concrete controller that can handle requests. After the controller has been created, the next major step is Action Execution. A component called the action invoker finds and selects an appropriate Action method to invoke the controller.

If the result is not a view, the action result will execute on its own. This Result Execution is what generates an actual response to the original HTTP request.

The MVC Programming Model

MVC is a framework for building web applications using a MVC (Model View Controller) design:
  • The Model is the part of the application that handles the logic for the application data.
    Often model objects retrieve data (and store data) from a database
    The View is the parts of the application that handles the display of the data.
    Most often the views are created from the model data.
    The Controller is the part of the application that handles user interaction.
    Typically controllers read data from a view, control user input, and send input data to the model.
      
  • Web Forms vs MVC

    The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is a lightweight, highly testable framework, integrated with all existing ASP.NET features, such as Master

    What is Razor?

  • Razor is a markup syntax for adding server-based code to web pages
  • Razor has the power of traditional ASP.NET markup, but is easier to learn, and easier to use
  • Razor is a server side markup syntax much like ASP and PHP
  • Razor supports C# and Visual Basic programming languages
  • Pages, Security, and Authentication

ASP.NET - Validators

ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or contradictory data don't get stored.
ASP.NET provides the following validation controls:
  • RequiredFieldValidator
  • RangeValidator
  • CompareValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary

Difference between WCF and ASP.NET Web Service

WCF
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another.

Web Services 
A Web Service is programmable application logic accessible via standard web protocols. One of these web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.


Difference between WCF and ASP.NET Web Service

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContraact] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions