Thursday, 11 September 2014

What is a Trigger

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:-

(i) After Triggers (For Triggers)
(ii) Instead Of Triggers

(i) 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.

Collapse | Copy Code

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:-
Collapse | Copy Code

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) AFTRE INSERT Trigger
This trigger is fired after an INSERT on the table. Let’s create the trigger as:-
Collapse | Copy Code

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 :
Collapse | Copy Code

 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:-
Collapse | Copy Code

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:-
Collapse | Copy Code

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.
Collapse | Copy Code

 update Employee_Test set Emp_Sal=1550 where Emp_ID=6

This inserts the row into the audit table as:-
Collapse | Copy Code

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:-
Collapse | Copy Code

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:-
Collapse | Copy Code

 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
Collapse | Copy Code

ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL

Specific Triggers can be enabled or disabled as :-
Collapse | Copy Code

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 anyonr 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.

(a) Let’s create an Instead Of Delete Trigger as:-
Collapse | Copy Code

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:-

Collapse | Copy Code

delete from Employee_Test where Emp_ID=4

This will print an error message as defined in the RAISE ERROR statement as:-

Collapse | Copy Code

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.

Tuesday, 9 September 2014

ASP.NET – JSON – Serialization and Deserialization

I was looking around for a simple example which would just do a object serialization to a JSON format, and then deserializing back to the original object. I found few examples on MSDN, but did seem to be too long to try. Here I’ve given a simple code which would make your understanding easy, and simpler.
 
Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.
 
What is JSON?
 
JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.
 
Okay, I understood a little about JSON. Give me an example!
 
I know an example will get your understanding much better. Below is a simple example of how an object can be expressed in JSON notation. Let’s take a classical example of a Person object, and expressing myself as an object.
{
   “firstName”: “Rakki”,
   “lastName”:”Muthukumar”,
   “department”:”Microsoft PSS”,
   “address”: {
      “addressline1”: “Microsoft India GTSC”,
      “addressline2”: “PSS - DSI”,
      “city”: “Bangalore”,
      “state”: “Karnataka”,
      “country”: “India”,
      “pin”: 560028
   }
   “technologies”: [“IIS”, “ASP.NET”,“JavaScript”,“AJAX”]
}
In the above example, address is another object inside my Person, and technologies is an array or strings.
 
Express this as a simple .NET class, please!
 
Here is a simple example.
public class Address
{
    public string addressline1, addressline2, city, state, country;
    public int pin;
}
 
public class Person
{
    public string firstName, lastName, department;
    public Address address = new Address();
    public string[] technologies;
}
I get it. Now what? JSON Serialization / Deserialization?
 
I’m sure you do not want me to write what is serialization, and deserialization here. I’ll touch upon how to use System.Web.Script.Serialization.JavaScriptSerializer to convert an existing object into a JSON string.
JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Rakki";
p1.lastName = "Muthukumar";
p1.department = "Microsoft PSS";
p1.address.addressline1 = "Microsoft India GTSC";
p1.address.addressline2 = "PSS - DSI";
p1.address.city = "Bangalore";
p1.address.state = "Karnataka";
p1.address.country = "India";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };
 
string str = js.Serialize(p1);
Above code just creates a Person object, and assign some values. Look at the last line where we are actually doing a serialization – means dumping the contents of the object to a JSON notation. Below is the string produced by the above code:
{"firstName":"Rakki","lastName":"Muthukumar","department":"Microsoft PSS","address":{"addressline1":"Microsoft India GTSC","addressline2":"PSS - DSI","city":"Bangalore","state":"Karnataka","country":"India","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}
It is the same as how we defined the object before – but in a single line. Now, you have successfully converted your object into a JSON string.
Now how do I deserialize it?
 
Before going into how to deserialize it, let’s just understand when you might want to deserialize the object. Classical example is a JSON object returned from a web service, or from your client side javascript code, and you will be able to deserialize it in the server side to use the received object. 
Person p2 = js.Deserialize<Person>(str);
Response.Write(p2.lastName);
p2.lastName would contain “Muthukumar” if your deserialization works fine. I suggest you to use the Deserialize<T> method since it will reduce the type casting you might be doing if you use DeserializeObject() method which returns a System.Object.

Monday, 8 September 2014

Accessing ASP.NET Session variable using Javascript:

 //Set Session Value
<script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

//Get Session Value



<script type="text/javascript">
    function GetUserName()
    {
        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Wednesday, 3 September 2014

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#


DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:
Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable

DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.

protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();
}



DataReader
===========
DataReader is like a forward only recordset. It fetches one row at a time so very less network cost compare to DataSet(Fethces all the rows at a time). DataReader is readonly so we can't do any transaction on them. DataReader will be the best choice where we need to show the data to the user which requires no transaction. As DataReader is forward only so we can't fetch data randomly. .NET Data Providers optimizes the datareader to handle huge amount of data.

DataSet
=======
DataSet is an in memory representation of a collection of Database objects including tables of a relational database schemas.
DataSet is always a bulky object that requires a lot of memory space compare to DataReader. We can say that the DataSet is a small database because it stores the schema and data in the application memory area. DataSet fetches all data from the datasource at a time to its memory area. So we can traverse through the object to get the required data like querying database.

Sunday, 24 August 2014

SQL Server Database BackUp Using Query

DECLARE @name VARCHAR(50) -- database name  DECLARE @path VARCHAR(256) -- path for backup files  DECLARE @fileName VARCHAR(256) -- filename for backup  DECLARE @fileDate VARCHAR(20) -- used for file name
DECLARE   @path  VARCHAR(50)= 'D:\op\Cooper\DB\OKTest\'
DECLARE  @fileDate VARCHAR(50)= CONVERT(VARCHAR(20),GETDATE(),112) 

DECLARE  @filename  VARCHAR(100)=null
DECLARE db_cursor CURSOR FOR  SELECT name FROM master.dbo.sysdatabases WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases
 OPEN db_cursor   FETCH NEXT FROM db_cursor INTO @name  
 WHILE @@FETCH_STATUS = 0   BEGIN          SET @fileName = @path + @name + '_' + @fileDate + '.BAK'         BACKUP DATABASE @name TO DISK = @fileName 
        FETCH NEXT FROM db_cursor INTO @name   END  
 CLOSE db_cursor   DEALLOCATE db_cursor

Saturday, 23 August 2014

HTTP Handler in ASP.NET 3.5

 What is HTTP handler: Every request into an ASP.NET application is handled by a specialized component known as an HTTP handler. The HTTP handler is the most important ingredient while handling ASP.NET requests.


HttpHanlder is the low level Request and Response API to service incoming Http requests. All handlers implement the IHttpHandler interface. There is no need to use any extra namespace to use it as it contains in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.


Each incoming HTTP request received by ASP.NET is ultimately processed by a specific instance of a class that implements IHTTPHanlder. IHttpHanlderFactory provides the infrastructure that handles the actual resolution of URL requests to IHttpHanlder instances. In addition to the default IHttpHandlerFactory classes provided by ASP.NET, developers can optionally create and register factories to support rich request resolution.

Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the handler for web Page creates the page and control objects, runs your code, and renders the final HTML.

ASP.NET default handlers:

  1. Page Handler (.aspx) - Handles Web pages
  2. User Control Handler (.ascx) - Handles Web user control pages
  3. Web Service Handler (.asmx) - Handles Web service pages
  4. Trace Handler (trace.axd) - Handles trace functionality
Why we need to create our own HTTP Handler: Sometime we need to avoid ASP.NET full page processing model, which saves lot of overheads, as ASP.NET web form model has to go through many steps such as creating web page objects, persisting view state etc. What we are interested into is to develop some low level interface that provides access to objects like Request and Response but doesn't use the full control based web form model discussed above.

Examples:

  1. Dynamic image creator - Use the System.Drawing classes to draw and size your own images.
  2. RSS - Create a handler that responds with RSS-formatted XML. This would allow you to add RSS feed capabilities to your sites.
  3. Render a custom image,
  4. Perform an ad hoc database query,
  5. Return some binary data.
These examples extend the ASP.NET architecture but bypass the web-page model. The result is a leaner, more efficient component.

Where HTTP handlers are defined: All HTTP handlers are defined in the <httpHandlers> section of a configuration file which is nested in the <system.web> element.

<httpHandlers>
<add verb="*" path="trace.axd" validate="true" type="System.Web.Handlers.TraceHandler"/>
<add verb="*" path="*.config" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.cs" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.aspx" validate="true" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>

  1. Trace.axd : this handler is meant for rendering HTML page with a list of all the recently collected trace output, and this is handled by TraceHandler
  2. .config: Handled by HttpForbiddenHandler
  3. .cs: Handled by HttpForbiddenHandler
  4. .aspx: Handled by PageHandlerFactory, which isn't a HTTP handler rather it's a class that will create the appropriate HTTP handler.
What is HTTP module: Help in processing of page request by handing application events , similar to what global.asax does. A request can pass through many HTTP modules but is being handled by only one HTTP handlers.

Http1.gif

Use of HTTP Modules:

  1. ASP.NET uses HTTP modules to enable features like caching, authentication, error pages etc.
  2. <add> and <remove> tags can be used to add and inactive any http module from <httpmodule> section of a configuration file.
<httpModules>
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication"
type="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"/>
</httpModules>

Note:

  1. HTTP handler plays same role what ISAPI extension
  2. HTTP module plays same role what ISAPI filters does.
How to write custom HTTP handler:

Step 1: What all we need to know before writing handlers

There are two type of handler you actually can make

  1. Synchronous handler , which implement IHttpHandler interface
  2. Asynchronous handler, which implement IHttpAsyncHandler. With asynchronous handlers additional requests can be accepted, because the handler creates a new thread to process each request rather than using the worker process
Further these Interfaces require us to implement the ProcessRequest method and the IsReusable property.
  1. The ProcessRequest method handles the actual processing for requests made.
    ASP.NET calls this method when a request is received. It's where the HTTP handlers perform all the processing. You can access the intrinsic ASP.NET objects (such as Request, Response, and Server) through the HttpContext object that's passed to this method.
     
  2. Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.
    After ProcessRequest() finishes its work, ASP.NET checks this property to determine whether a given instance of an HTTP handler can be reused. If it returns true, the HTTP handler object can be reused for another request of the same type current. If it returns false, the HTTP handler object will simply be discarded.
Step 2: Create a ASP.NET web application and name it: SimpleHTTPHanlder

Step 3: Add a class and name it "SimpleHandler"

Step 4: Write below code

Http2.gif

Here we are implementing IHttpHandler

Full code look like below

public class SimpleHandler : IHttpHandler
    {
        #region IHttpHandler Members
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            HttpResponse response = context.Response;
            response.Write("<html><body><h1>Wow.. We created our first handler");
            response.Write("</h1></body></html>");
        }
        #endregion
    }

Step 5: Configuring HTTP handler in configuration file;

We will add our handler in <httpHandlers> section

<httpHandlers>         
<add verb="*" path="vishal.nayan" type="MyHttpHandler.SimpleHandler,MyHttpHandler"/>
</httpHandlers>


Now here we need to understand what these attributes means
  1. Verb: indicates whether the request is an HTTP POST or HTTP GET request (use * for all requests).
  2. Path : indicates the file extension that will invoke the HTTP handler
  3. Type: identifies the HTTP handler class. This identification consists of two portions. First is the fully qualified class name , That portion is followed by a comma and the name of the DLL assembly that contains the class
Step 6: How to run our Handler

Well, visual studio doesn't allow us directly to run the handler, rather we need to run the project first and then explicitly type URL to request for handler, so in our case it is;

http://localhost:3238/myhttphandler/vishal.nayan

Http3.gif

Now, can we create HTTPHanlder without configuring web.config file. Well yes. In visual studio we have a new item template to accomplish this. For this we can use the recognized extension .ashx. All requests that end in .ashx are automatically recognized as requests for a custom HTTP handler.

Http4.gif

What is leeching: sites that steal bandwidth by linking to resources on your server .i.e. giving an image URL path from their server to your server, so when user tries to access that image, it's actually using your server resources.

Problem Scenario: As stated above, when any request for image is originated from same website then it's ok, but if the request is coming from another website, then there is a potential problem, as it is creating more work for your web server and reducing the bandwidth.

Solution: HTTP handler will refuse to serve the image or they substitute a dummy image if the referrer header indicates that a request originates from another site.

Add a generic handler from existing item and name it ImageHandler.ashx. Write the code below;

public class ImageHandler : IHttpHandler
{
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            string imageURL = null;
            // Perform a case-insensitive comparison.
            if (request.UrlReferrer != null)
            {
                if(String.Compare(request.Url.Host, request.UrlReferrer.Host,true,CultureInfo.InvariantCulture) ==0)
                {
                    // The requesting host is correct.
                    // Allow the image (if it exists).
                    imageURL = request.PhysicalPath;
                    if (!File.Exists(imageURL))
                    {
                        response.Status = "Image Not Found";
                        response.StatusCode = 404;
                    }
                    else
                    {
                    }
                }
            }
            if (imageURL == null)
            {
                // No valid image was allowed.
                // Use the warning image instead.
                // Rather than hard-code this image, you could
                // retrieve it from the web.config file
                // (using the <appSettings> section or a custom
                // section).
                imageURL = context.Server.MapPath("~/images/notallowed.gif");
            }
            // Serve the image
            // Set the content type to the appropriate image type.
            response.ContentType = "image/" + Path.GetExtension(imageURL).ToLower();
            response.WriteFile(imageURL);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
}

Now its time to configure it. For this handler to protect image files, you need to register it to deal with the appropriate file types. Here are the web.config settings that set this up for the .gif and .jpg file types only.

<add verb="*" path="*.gif" type="SimpleHTTPHanlder.ImageHandler,SimpleHTTPHanlder"/>
<add verb="*" path="*.jpg" type="SimpleHTTPHanlder.ImageHandler,SimpleHTTPHanlder"/>

Now this configuration setting will only allow jpg and gif images, after checking it the request is originating from same website.

So now when we have to request any image , we simple type image URL and we can see that
http://localhost:3238/images/areng.jpg

Http5.gif

The one which is not available, is greeted by not found image. Say for this image request which doesn't exists;
http://localhost:3238/images/areds.jpg

Http6.gif

So by this HTTP handler for images, we can restrict any request which is not coming from our web site and also increase performance by quicker response time.

Friday, 22 August 2014

How to get Asp.Net TreeView Selected Node Text In Java Script/ Client End


 Add In C#
 if (!IsPostBack)
        {
 SqlTree.Attributes.Add("onclick", "return OnTreeClick(event)");
       }


In Default .aspx

<script type="text/javascript">
function OnTreeClick(evt)
 {      
   var src = window.event != window.undefined ? window.event.srcElement : evt.target;
   var nodeClick = src.tagName.toLowerCase() == "a";
     if (nodeClick)
      {
        //innerText works in IE but fails in Firefox (I'm sick of browser anomalies), so use innerHTML as well
        var nodeText = src.innerText || src.innerHTML;
      Alert(nodeText);
      }
    return false; //comment this if you want postback on node click
 }

    </script>



    <div style="border:1px solid; height:260px; width:260px; overflow:auto; padding:3px 3px 3px 3px;" >
                                                                        <asp:TreeView ID="SqlTree"
                                                                CssClass="example3" Style="text-align: left; vertical-align:top;"
                                                                          NodeWrap="true"   ShowLines="true"  ShowExpandCollapse="true" runat="server" Width="250px"  Height="250px"
                                                                >
                                                                        </asp:TreeView></div>