Thursday, 24 September 2015

ACID Properties

When a transaction processing system creates a transaction, it will ensure that the transaction will have certain characteristics. The developers of the components that comprise the transaction are assured that these characteristics are in place. They do not need to manage these characteristics themselves. These characteristics are known as the ACID properties. ACID is an acronym for atomicity, consistency, isolation, and durability.

Atomicity

The atomicity property identifies that the transaction is atomic. An atomic transaction is either fully completed, or is not begun at all. Any updates that a transaction might affect on a system are completed in their entirety. If for any reason an error occurs and the transaction is unable to complete all of its steps, the then system is returned to the state it was in before the transaction was started. An example of an atomic transaction is an account transfer transaction. The money is removed from account A then placed into account B. If the system fails after removing the money from account A, then the transaction processing system will put the money back into account A, thus returning the system to its original state. This is known as a rollback.

Consistency

A transaction enforces consistency in the system state by ensuring that at the end of any transaction the system is in a valid state. If the transaction completes successfully, then all changes to the system will have been properly made, and the system will be in a valid state. If any error occurs in a transaction, then any changes already made will be automatically rolled back. This will return the system to its state before the transaction was started. Since the system was in a consistent state when the transaction was started, it will once again be in a consistent state.
Looking again at the account transfer system, the system is consistent if the total of all accounts is constant. If an error occurs and the money is removed from account A and not added to account B, then the total in all accounts would have changed. The system would no longer be consistent. By rolling back the removal from account A, the total will again be what it should be, and the system back in a consistent state.

Isolation

When a transaction runs in isolation, it appears to be the only action that the system is carrying out at one time. If there are two transactions that are both performing the same function and are running at the same time, transaction isolation will ensure that each transaction thinks it has exclusive use of the system. This is important in that as the transaction is being executed, the state of the system may not be consistent. The transaction ensures that the system remains consistent after the transaction ends, but during an individual transaction, this may not be the case. If a transaction was not running in isolation, it could access data from the system that may not be consistent. By providing transaction isolation, this is prevented from happening.

Durability

A transaction is durable in that once it has been successfully completed, all of the changes it made to the system are permanent. There are safeguards that will prevent the loss of information, even in the case of system failure. By logging the steps that the transaction performs, the state of the system can be recreated even if the hardware itself has failed. The concept of durability allows the developer to know that a completed transaction is a permanent part of the system, regardless of what happens to the system later on.


Summary
In this article I try to clear concept of ACID Properties. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Thursday, 10 September 2015

ASP.NET View State

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields.

Scenarios
View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. This information includes any non-default values of controls.
You can also use view state to store application data that is specific to a page.

FeaturesView state is a repository in an ASP.NET page that can store values that have to be retained during postback. The page framework uses view state to persist control settings between postbacks.

You can use view state in your own applications to do the following:

  • Keep values between postbacks without storing them in session state or in a user profile.
  • Store the values of page or control properties that you define.
  • Create a custom view state provider that lets you store view state information in a SQL Server database or in another data store.
For example, you can store information in view state that your code can access during the page load event the next time that the page is sent to the server.
Summary
In this article I try to clear concept of View State. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Saturday, 5 September 2015

Triggers -- SQL Server

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. It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action no the table that they are assigned to.

Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them. 
Basically, triggers are classified into two main types:

1) After Triggers (For Triggers)
2) Instead Of Triggers

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:
a) AFTER INSERT Trigger.
b) AFTER UPDATE Trigger.
c) AFTER DELETE Trigger.

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be attaching several triggers.
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);

I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The main purpose of this audit table is to record the changes in the main table. This can be thought of as a generic audit trigger.
Now, create the audit table as:
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) After Insert Trigger
This trigger is fired after an INSERT on the table. Let’s create the trigger as:

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=i.Emp_ID from inserted i; 
select @empname=i.Emp_Name from inserted i; 
select @empsal=i.Emp_Sal from inserted i; 
set @audit_action='Inserted Record -- After Insert Trigger.';

insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER INSERT trigger fired.'
GO

The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies the table name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the same.
In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been inserted. I have selected the fields from the logical inserted table from the row that has been inserted into different variables, and finally inserted those values into the Audit table.
To see the newly created trigger in action, lets insert a row into the main table as:
insert into Employee_Test values('Chris',1500);
Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the Employee_Test_Audit as:
6 Chris 1500.00 Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700
(b) AFTER UPDATE Trigger
This trigger is fired after an update on the table. Let’s create the trigger as:

CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test] 
FOR UPDATE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=i.Emp_ID from inserted i; 
select @empname=i.Emp_Name from inserted i; 
select @empsal=i.Emp_Sal from inserted i;

if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';

insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER UPDATE Trigger fired.'
GO

The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical table updated like the logical table inserted. We can obtain the updated value of a field from the update(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Let’s update a record column and see what happens.
update Employee_Test set Emp_Sal=1550 where Emp_ID=6
This inserts the row into the audit table as:
6 Chris 1550.00 Updated Record -- After Update Trigger. 2008-04-26 12:38:11.843

(c) AFTER DELETE Trigger
This trigger is fired after a delete on the table. Let’s create the trigger as:

CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test] 
AFTER DELETE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=d.Emp_ID from deleted d; 
select @empname=d.Emp_Name from deleted d; 
select @empsal=d.Emp_Sal from deleted d; 
set @audit_action='Deleted -- After Delete Trigger.';

insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER DELETE TRIGGER fired.'
GO

In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audit table. Let’s fire a delete on the main table. A record has been inserted into the audit table as:
6 Chris 1550.00 Deleted -- After Delete Trigger. 2008-04-26 12:52:13.867
All the triggers can be enabled/disabled on the table using the statement
ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL
Specific Triggers can be enabled or disabled as:
ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete

This disables the After Delete Trigger named trgAfterDelete on the specified table.

ii) Instead Of Triggers
These can be used as an interceptor for anything that anyone tried to do on our table or view. If you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the trigger)

INSTEAD OF TRIGGERS can be classified further into three types as:
a) INSTEAD OF INSERT Trigger.
b) INSTEAD OF UPDATE Trigger.
c) INSTEAD OF DELETE Trigger.

Let’s create an Instead Of Delete Trigger as:
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test] 
INSTEAD OF DELETE
AS
declare @emp_id int;
declare @emp_name varchar(100);
declare @emp_sal int;

select @emp_id=d.Emp_ID from deleted d;
select @emp_name=d.Emp_Name from deleted d;
select @emp_sal=d.Emp_Sal from deleted d;

BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO

This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction will be committed. Now, let’s try to delete a record with the Emp_Sal >1200 as:
delete from Employee_Test where Emp_ID=4
This will print an error message as defined in the RAISE ERROR statement as:
Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200

And this record will not be deleted.
**In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.

Summary
In this article I try to clear the concept of Triggers. I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Saturday, 29 August 2015

DataSet and DataReader

Generally we have a question in our mind, what are the differences between DATASET and DATAREADER and when to us them.
So today we will try to clear your doubt.
DataSet is a collection of in memory tables and datareader provides the ability to expose the data from database.
Both are very widely used in asp.net applications to get/fetch the data from the database. But for a scalable, fast, and reliable application one has to know the best practices in developing application.

DataSet
We should use when the application is:
* Windows application
* Not too large data
* Returning multiple tables
* If, to be serialized
* Disconnected architecture
* To return from a WCF service
* To send across layers
* Caching the data
* Do not need to open or close connection

Code snippet using dataset:
public DataSet GetRecord(Guid id, string procedureName)
{
DataSet resultSet = new DataSet();
SqlConnection connection = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(procedureName, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters["pID"].Value = id.ToString();
IDataAdapter adapter = new SqlDataAdapter(command);
try
{
adapter.Fill(resultSet);
}
catch (Exception ex)
{
throw new PerformanceException(ex.Message, ex.InnerException);
}
return resultSet;
}


DataReader
DataReader is a stream which is readonly and forward only. It fetches the record from databse and stores in the network buffer and gives whenever requests. DataReader releasese the records as query executes and do not wait for the entire query to execute. Therefore it is very fast as compare to the dataset. It releases only when read method is called.
Its usages:
* Web application
* Large data
* Returning multiple tables
* For Fast data access
* Needs explicitly closed
* Output parameter value will only available after close
returns only a row after read

Code sample for DataReader:
public SqlDataReader GetRecord(Guid id, string procedureName)
{
SqlDataReader resultReader = null;
SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(procedureName, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters["pID"].Value = id.ToString();
try
{
connection.Open();
resultReader = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
if (resultReader != null || connection.State == ConnectionState.Open)
{
resultReader.Close();
connection.Close();
}
throw new PerformanceException(ex.Message, ex.InnerException);
}
return resultReader;
}


Summary
In this article I try to clear concept of DataSet and DataReader. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Tuesday, 25 August 2015

Boxing and Unboxing

Boxing is name given to the process whereby a value type is converted into a reference type. When you box a variable, you are creating a reference variable that points to a new copy on the heap. The reference variable is an object, and therefore can use all the methods that every object inherits, such as, ToString(). 
This is what happens in the following code:
int i = 67;                              // i is a value type 
object o = i;                            // i is boxed
System.Console.WriteLine(i.ToString());  // i is boxed

You will encounter unboxing when you use classes designed for use with objects: for example, using an ArrayList to store integers. When you store an integer in the ArrayList, it's boxed. When you retrieve an integer, it must be unboxed.
This is what happens in the following code:
System.Collections.ArrayList list = new System.Collections.ArrayList();
                                    // list is a reference type 
int n = 67;                         // n is a value type
list.Add(n);                       // n is boxed
n = (int)list[0];                  // list[0] is unboxed
Summary
In this article I try to clear concept of Boxing and Unboxing. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Thursday, 20 August 2015

Value and Reference Types

Unlike some programming languages you might be familiar with, C# has two varieties of data types: value and reference.
It's important to know the difference if performance is important to your application, or if you are interested in how C# manages data and memory.
When a variable is declared using one of the basic, built-in data types or a user defined structure, it is a value type. An exception is the string data type, which is a reference type.
A value type stores its contents in memory allocated on the stack. For example, in this case the value 42 is stored in an area of memory called the stack.:
Example:
int x = 42;

When the variable x goes out of scope because the method in which it was defined has finished executing, the value is discarded from the stack.
Using the stack is efficient, but the limited lifetime of value types makes them less suited for sharing data between different classes.

In contrast, a reference type, such as an instance of a class or an array, is allocated in a different area of memory called the heap. In the example below, the space required for the ten integers that make up the array is allocated on the heap.
Example:
int[] numbers = new int[10];

This memory isn't returned to the heap when a method finishes; it's only reclaimed when C#'s garbage collection system determines it is no longer needed. There is a greater overhead in declaring reference types, but they have the advantage of being accessible from other classes.

Summary
In this article I try to clear concept of Value and Reference Types. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Sunday, 19 July 2015

Differnce between ExecuteScalar, ExecuteReader and ExecuteNonQuery

Today we are going discuss most common doubts among DotNetDevelopers.
Differnce between ExecuteScalar, ExecuteReader and ExecuteNonQuery

ExecuteScalar is going to be the type of query which will be returning a single value. An example would be selecting a count of the number of active users.

ExecuteReader gives you a data reader back which will allow you to read all of the columns of the results a row at a time. An example would be getting all of the information for each user in the system so you could display that information.

ExecuteNonQuery is any SQL which isn't returning values really, but is actually performing some form of work like inserting deleting or modifying something. An example would be updating a user's personal information in the database.
Summary
In this article I try to clear difference between ExecuteSaclar, ExecuteReader and Execute NonQuery I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Friday, 6 March 2015

File Upload


 Today we will discuss how to  in asp.net webpage. It’s a very simple script to disable right click event. You can disable the right click event in whole website by adding this script in master page.

On upload button click:
 
protected void btn_upload_Click(object sender, EventArgs e)
    {
        if (fp_id_img.HasFile)
        {
            if (fp_id_img.PostedFile.ContentType == "image/jpeg" || fp_id_img.PostedFile.ContentType == "image/jpg" || fp_id_img.PostedFile.ContentType == "image/gif" || fp_id_img.PostedFile.ContentType == "image/png")
            {
                string img_id = Guid.NewGuid().ToString().Substring(0, 10);
                filepath = "~/Images/Id_proof_img/" + img_id + Class1.Getextention(fp_id_img.FileName);
                filename = Path.GetFileName(fp_id_img.FileName);
               fp_id_img.SaveAs(Server.MapPath(filepath));
                Image2.Visible = true;
                Image2.ImageUrl = filepath;

                string msg1 = string.Empty;
                msg1 = "Picture uploaded successfully";
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg1 + "');", true);
                return;
               
            }
            else
            {
                string msg1 = string.Empty;
                msg1 = "Only jpeg,jpg,gif,png can be Uploaded!";
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg1 + "');", true);
                return;
            }
        }

    }


In class file following extension must be added.
#region extension
    public static string Getextention(string Filename)
    {
        string _extention;
        int index;
        index = Filename.IndexOf('.');
        _extention = Filename.Substring(index);
        return _extention;

    }
    #endregion



Summary
In this article I try to expose File Upload in asp.net. I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Sunday, 1 March 2015

Disable Right Mouse Click using JavaScript

Today we will discuss how to disable mouse right click using JavaScript in website or asp.net webpage. It’s a very simple script to disable right click event. You can disable the right click event in whole website by adding this script in master page.

<script type="text/javascript">
if (document.layers)
 {
    //Capture the MouseDown event.
    document.captureEvents(Event.MOUSEDOWN);

    //Disable the OnMouseDown event handler.
    document.onmousedown = function ()
 {
        return false;
    };
}
else {
    //Disable the OnMouseUp event handler.
    document.onmouseup = function (e) {
        if (e != null && e.type == "mouseup")
           {
            //Check the Mouse Button which is clicked.
            if (e.which == 2 || e.which == 3)
           {
                //If the Button is middle or right then disable.
                return false;
            }
        }
    };
}

//Disable the Context Menu event.
document.oncontextmenu = function ()
 {
    return false;
};
</script>




Above script has to be copied in the head section of the Master Page or ASP.NET (ASPX) page and it can also be placed within the ContentPlaceHolder of the Content Page.
The script disables the following three events in order to disable the Right Click in browsers.
 OnMouseDown
The script first checks whether the document has layers, and if yes then the OnMouseDown event is captured and inside its event handler the event is cancelled by using return false.


 OnMouseUp
And if the document does not have layers then inside the OnMouseUp event handler, first the Mouse Button that was clicked is determined and if the Button is Middle or Right then the event is cancelled using return false.
 OnContextMenu
The OnContextMenu event is cancelled using the OnContextMenu event handler.

Summary
In this article I try to expose disabling mouse right click property. I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.