Saturday, 15 March 2014

Getting previous page URL using ASP.NET with C#

string referer = Request.UrlReferrer.ToString();

Using Request.UrlReferrer, we can get the Previous page URL of the current request. Previous Page information is available in the Request.UrlReferrer property only if user is redirected to the current page from some other page and is available in the !Page.IsPostBack of Page Load event of the form. 

One thing to remember is that UrlReferrer will change to your pagename when you post back to the server.. so you should maybe store the value in ViewState on the first page load of the page if you are wanting to redirect the user to the previous page after a couple postbacks to the same page.

protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack) //check if the webpage is loaded for the first time.
            ViewState["PreviousPageURL"] = Request.UrlReferrer; 
            //Saves the Previous page url in ViewState

If you want to reach the previous page ,

if (ViewState["PreviousPage"] != null) //Check if the ViewState contains Previous page URL
           //Redirect to Previous page by retrieving the PreviousPage Url from ViewState.

ViewState is used for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.

The situations where it does work include the following methods of a browser loading a URL:
  • clicking on a straight HTML <a href> link;
  • submitting a form, using POST or GET, from a submit button, <input type=image> or client-side script (form.submit())

The situations where it doesn't work:
  • using Response.Redirect / Server.Transfer;
  • clicking on a Favorite, History, or the recently-typed URLs list;
  • clicking on 'Home' in IE's toolbar, or an item in IE's 'Links' toolbar;
  • using location.href or location.replace() in client-side JScript/JavaScript/VBScript;
  • using HierMenus (details);
  • typing the URL directly in the browser and hitting Enter or clicking 'Go';
  • launching a clickable URL from an e-mail or MS Office document;
  • using Response.AddHeader  or <meta http-equiv=refresh> to redirect;
  • loading the URL with XML

Wednesday, 29 January 2014

Dynamic SQL Performance comparison in SQL Server

Dynamic SQL statements

A dynamic SQL statement is constructed at execution time, for which different conditions generate different SQL statements. It can be useful to construct these statements dynamically when you need to decide at run time what fields to bring back from SELECT statements; the different criteria for your queries; and perhaps different tables to query based on different conditions.

These SQL strings are not parsed for errors because they are generated at execution time, and they may introduce security vulnerabilities into your database. Also, SQL strings can be a nightmare to debug, which is why I have never been a big fan of dynamically built SQL statements; however, sometimes they are perfect for certain scenarios.

NOTE: Most importantly, the Dynamic SQL Queries in a variable are not compiled, parsed, checked for errors until they are executed.

Declare a string variable, something like:

declare @sql varchar(5000)
Set that variable to be the completed SQL string you want (as a string, and not actually querying... so you embed the row-name you want using string concatenation).

Then call: exec(@sql)
There have been a lot of discussions on the usage of dynamic SQL in SQL server. Most of them were stressing on SQL injection. Will dynamic SQL cause any performance difference? Interesting question!! Shall we check with an example?

Following are two simple procedures created in Northwnd database to fetch company names. One using dynamic SQL and the other one without dynamic SQL.

The following SQL Server script that could be useful to collect the measures-

Does it mean that dynamic SQL is something that should be avoided ? Never meant that !! The tests were not exhaustive enough to prove that, and sp_executesql is not at all counted in these tests. The only point to emphasize here is that there could be performance implications while using dynamic SQL, and this should be known and counted during application development.

Tuesday, 28 January 2014

Multiple JOINs with Missing Operator Issue in MS Access

Join is used to retrieve rows from two or more tables by matching a field value that is common between the tables. The fields you join on must have similar data types, and you cannot join on MEMO or OLEOBJECT data types

if you want to do more than one JOIN, you have to use parenthesis in the FROM clause.

FROM MainTable
JOIN JointTable1 ON ...
JOIN JointTable2 ON ...
JOIN JointTable3 ON ...

you would have to do the following:

FROM ((MainTable
JOIN JointTable1 ON ...)
JOIN JointTable2 ON ...)
JOIN JointTable3 ON ...

the joins must be nested by using parentheses

Otherwise, you get a "Missing Operator" error.

Wednesday, 21 August 2013

Avoid sharing of same session across multiple tabs using

By default all browsers share session state between multiple tabs. So if you logged into one tab with particular site and open internal link of the same site in new tab, you need not to worry to login again. It will automatically declare you as logged in user.

When open different tabs, those tab will share same session if user access same web app in different tabs. same as sign out process also.

this is normal behavior of browser (shared single session on multiple tab).

Tab based browser – session handling

if you need each tab will get unique ID and it will looks like it is another visitor, try this code

    <sessionState cookieless="true"
      regenerateExpiredSessionId="true" />

Wednesday, 10 July 2013

What is the difference between a field and a property in C#?

Fields and properties look the same, but they are not. Properties are methods and as such there are certain things that are not supported for properties, and some things that may happen with properties but never in the case of fields.

Here's a list of differences:

  • Fields may be used as input to out/ref arguments. Properties may not.

  • A field will always yield the same result when called multiple times (if we leave out issues with multiple threads). A property such as DateTime.Now is not always equal to itself.

  • Properties may throw exceptions - fields will never do that.

  • Properties may have side effects or take a really long time to execute. Fields have no side effects and will always be as fast as can be expected for the given type.

  • Properties support different accessibility - fields do not (but fields can be made readonly)

  • When using reflection the properties and fields are treated as different MemberTypes so are located differently (GetFields vs GetProperties for example)

  • The JIT Compiler may treat property access very differently to field access. It may however compile down to identical native code but the scope for difference is there.

  • An important difference is that interfaces can have properties but not fields

  • Properties may run for a very long time, have side effects, and may even throw exceptions. Fields are fast, with no side effects, and will never throw exceptions. Due to side effects a property may return a different value for each call (as may be the case for DateTime.Now, i.e. DateTime.Now is not always equal to DateTime.Now). Fields always return the same value.

  • Fields may be used for out / ref parameters, properties may not. Properties support additional logic – this could be used to implement lazy loading among other things.

  • Using Properties, you can throw an event, when the value of the property is changed (aka. PropertyChangedEvent) or before the value is changed to support cancelation.

  • public class Person {
     private string _name;
     public event EventHandler NameChanging;    
     public event EventHandler NameChanged;
     public string Name{
         return _name;
         _name = value;
     private void OnNameChanging(){
       EventHandler localEvent = NameChanging;
       if (localEvent != null) {
     private void OnNameChanged(){
       EventHandler localEvent = NameChanged;
       if (localEvent != null) {

  • In the background a property is compiled into methods. So a Name property is compiled into get_Name() and set_Name(string value). You can see this if you study the compiled code. So there is a (very) small performance overhead when using them. Normally you will always use a Property if you expose a field to the outside, and you will often use it internally if you need to do validation of the value.

The remote server returned an error: (500) Internal Server Error

When the remote server returns an error, then it means that the remote server noticed something bad. When the error is 500, that means it's an internal error, meaning internal to the service - the service threw an exception that was not caught.

The remote server don't return the correct HTML, so it throw errors.

Check Windows event viewer logs you might get more information on the reason of the 500 error.

Thursday, 16 May 2013

How to know whether record is updated or not

When you do an update, it's immediately return rows updated: It Return Number of Records Affected

@@ROWCOUNT - Returns the number of rows affected by the last statement and Return type of @@ROWCOUNT is int.

The following example executes an UPDATE statement and uses @@ROWCOUNT to detect if any rows were changed

UPDATE Tbl_EmpProfile  SET JobTitle = 'Executive' WHERE EMPID = 5001
PRINT 'Warning: No rows were updated';

You can set this @@rowcount to some other variable and use them for further processing.


UPDATE Tbl_EmpProfile  SET JobTitle = 'Executive' WHERE EMPID = 5001
SET @rows = @@rowcount

using Stored Procedure, Register an out parameter for the stored procedure, and set the value based on @@ROWCOUNT if using SQL Server. Use SQL%ROWCOUNT if you are using Oracle.

if you have multiple INSERT/UPDATE/DELETEs, you'll need a variable to store the result from @@ROWCOUNT for each operation.