Thursday, March 29, 2012

How Dangerous Null values are in Sub query...


Recently I came across a strange problem while using simple sub query, everything was right but no data was returning.

DECLARE @Users TABLE (UserName VARCHAR(10))
DECLARE @ExcludeUsers TABLE (UserName Varchar(10))

INSERT INTO @Users
      SELECT 'User1' UNION SELECT 'User2'
     
INSERT INTO @ExcludeUsers
      SELECT 'User1' UNION SELECT NULL

SELECT * FROM @Users
SELECT * FROM @ExcludeUsers
SELECT * FROM @Users WHERE UserName NOT IN (SELECT UserName FROM @ExcludeUsers)

Here table1 (@Users) contains  two users
And table2  (@ExcludeUsers) contains one user and one NULL value

Now when we try to query the users that are not available in table2 (@ExcludeUsers) we find no rows due to one NULL value exists in table2 (@ExcludeUsers).

I have read on MSDN and found the reason as,

Any null values returned by subquery or expression that are compared to test_expression using IN or NOT IN return UNKNOWN. Using null values in together with IN or NOT IN can produce unexpected results.

So Any compare against NULL is always FALSE so we need to use IS NULL or IS NOT NULL.

 Happy Programming :)

Monday, December 26, 2011

Avoid "A potentially dangerous" error in MVC 2.0





When we need to post some HTML contents on server side, on form post in MVC 2.0, we can simplay write ValidateInput(false) above method declaration to avoid run time unhandled exception : "A potentially dangerous Request.Form value was detected from the client"


The complete syntax for the same is as follows


[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult Save(YourViewModel model)
{
}


Additionally we need to do following setting (only for net 4.0) along with above solution,


With asp.net 4, we will need to configure the validation mode in the web.config as well.


Set the following as a child of the <system.web> element:
<httpRuntime requestValidationMode="2.0"/>


Asp.Net 4 sets the requestValidationMode to 4.0 by default, which tells the system to perform request validation before the BeginRequst phase of the HTTP request. The validation will occur before the system reaches the action attribute telling it not to validate the request, thus rendering the attribute useless. Setting requestValidationMode="2.0" will revert to the asp.net 2.0 request validation behavior, allowing the ValidateInput attribute to work as expected.




Thanks for Reading
Happy Programming :)


Unescaping unicode characters in C# encoded in JavaScript


Recently I came across a problem where I need to post HTML content (through JSON) in AJAX call and was end up getting "A potentially dangerous Request.Form value was detected from the client"


This problem lead me to learn a new thing which I thought may helpful programmers in many cases.


The problem:


I used java script escape funnction to encode html contents which I need to decode on the server side.
JavaScript escape and unescape are very powerful functions, but they do have its various idiosyncrasies that do not work appropriately with the standard escaping methods in the serverside C# code.


The regualr methods we have on C# to handle escaping/unescaping are:

  • Uri.EscapeDataString
  • Uri.EscapeUriString
  • HttpUtility.UrlEncode
  • HttpUtility.URLPathEncode

but none of these return a properly unescaped string as escaped by the JavaScript conterpart. 

The solution:

Fortunately for us, Microsoft's own JScript libary has it's own, serverside implementation of the JavaScript encode/unencode methods, that do the job exactly as expected. They are exact equivalents.

  • Microsoft.JScript.GlobalObject.unescape(string escapedString) 
  • Server.UrlDecode(Microsoft.JScript.GlobalObject.unescape(string escapedString))

To use it in your code: Reference Micrtosoft.JScript.dll in your project.
Use the static methods in GlobalObject to do the escape/unescape


Thanks for Reading
Happy Programming :)

Wednesday, July 27, 2011

C# Version History

C# Version Wise Features


C# 2.0

  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)

C# 3.0

  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees

C# 4.0
New features Whitepaper


  • Dynamic binding
  • Named and optional arguments
  • Generic co- and contravariance

C# 5.0 (planned)

  • Asynchronous methods
  • Compiler as a service

Wednesday, January 19, 2011

Find Screen Resolution Using Javascript

You Can find screen Resolution in javascript using following code:

var screenW = 640, screenH = 480;
if (parseInt(navigator.appVersion) > 3) {
    screenW = screen.width;
    screenH = screen.height;
}
else if (navigator.appName == "Netscape"
    && parseInt(navigator.appVersion) == 3
    && navigator.javaEnabled()
   ) {
    var jToolkit = java.awt.Toolkit.getDefaultToolkit();
    var jScreenSize = jToolkit.getScreenSize();
    screenW = jScreenSize.width;
    screenH = jScreenSize.height;
}
document.write("screenW " + screenW );
document.write("screenH " + screenH );

Wednesday, September 1, 2010

Asp.Net 4.0 : The new <%: %> syntax

Asp.Net 4.0 introduces new code expression syntax (<%: %>) that renders output same like <%= %> but automatically encodes contents before rendering.


For example:

Let’s say we have "myContent" variable to be displayed on the web page.
For that we can write <%= Server.HtmlEncode(myContent) %>.
This works fine but developer often forgot to write Server.HtmlEncode() method and opens the door for Cross-site script injection (XSS) and HTML encoding attacks.
With asp.net 4.0 we can write the same code as <%: myContent %> which looks concise :)
So we can say <%= Server.HtmlEncode(myContent) %> is same as <%: myContent %>.

Thursday, August 5, 2010

ClientIDMode Property for generated ClientID in ASP.NET 4.0

ClientIDMode Property for generated ClientID

Every asp.net control is rendered as an HTML element and a corresponding ClientId is generated for it.If we want to reference the generated HTML element in javascript we must know the Id attribute of the generated element. The ID attribute in HTML that is rendered for Web server controls is generated based on the ClientID property of the control.

Until ASP.NET 4, we do not have much control over the generated Id of the Control. The new ClientIDMode property lets you specify more precisely how the client ID is generated for controls.

Possible settings for ClientIDMode are following:

* AutoID - Generated ClientID is similar to earlier versions of ASP.NET.Difficult to predict generated Id values.
* Static - This specifies that the ClientID value will be the same as the ID. For example if our label control has id HeaderLabel then the ClientId will also have value of HeaderLabel
* Predictable - This setting is used mostly in controls that are inside Data Bound Controls. The ClinetId value is generated by concatenating the ClinetId value of the parent naming container with the ID value of the control. This setting works in conjunction with the ClientIDRowSuffix property

If specified the value of the data field specified in the ClientIDRowSuffix property is added at the end.

For instance if we have StudentName Label inside ListView1 Student Name labels ClinetIDMode is set to Predictable and ClientIDRowSuffix is set to "ID" then StudentName labels' generated client id's will be as :

ListView1_ StudentName _1
ListView1_ StudentName _2
ListView1_ StudentName _3
ListView1_ StudentName _4

* Inherit - The control inherits the ClientIDMode setting of its parent control. This is the default value for control

Permanent Redirect in Asp.net 4.0: Response.RedirectPermanent

Response.RedirectParmanent is an extension function introduced in .NET 4.0.
The main motive of it is to indicate the Response Code to the Search Engine that the page is moved permanently. The Response.Redirect generates Response code as 302 whereas RedirectParmanent returns 301.

Thus say you have a page, and which is included to search engine for a long time, if you use Response.Redirect() it will not change this effect to the search engine(taking this a temporary change), while if you use Response.RedirectParmanent() it will take it as permanent.

In case of Server.Transfer() the actual response is actually been updated. There is no effect to the search engine, and search engine will think the output is coming from the same page that is called upon. Let us give an example :

Say you have 2 pages (Page 1 and Page 2) where Page1 redirects to Page2
In case of

1. Response.Redirect() : Search Engine will take this redirection as Temporary(Status 301) and always keep Page1 in its cache.
2. Response.RedirectParmanent() : Search Engine will take this a permanent redirection(Status 302) and will remove Page1 from its database and include Page2 for better performance on search.
3. Server.Transfer() : Search Engine will be unaware of any redirection been took place (Status 200) and will keep Page1 to its database. It will think Page1 is producing the output response of Page2.

When to use:
Response.Redirect is perfect when your page is temporarily changed and will be changed to original within a short span of time.
Response.RedirectParmanent() when you are thinking of deleting the Page1 totally after the search engines changes its cache.
Server.Transfer() when you are thinking of keeping the page for ever, and to let search engine unaware of this redirection.

Response.RedirectPermanent do the same thing as following code does.

Response.Status = "301 moved permanently";
Response.AddHeader("location", newPath);
Response.End();

Thursday, June 3, 2010

Disable content copy using java script

You can prevent copy of content from your page by using following java script:


document.oncontextmenu = function() { alert("Copy not allowed"); return false; }
window.onload = function() {
document.onselectstart = function() { return false; } // ie
document.onmousedown = function() { return false; } // mozilla
}


If you want to disable copy for perticular element you can use following java script

window.onload = function() {
var element = document.getElementById('content');
element.onselectstart = function () { return false; } // ie
element.onmousedown = function () { return false; } // mozilla
}