Wednesday, March 19, 2014

Entity Framework: Change SQLServer Command timeout



By adding in a few code in the DBContect we can increase SQLServer Command timeout

 public class WeedingContext : DbContext
    {
        public WeedingContext()
            : base("WeddingDb")
        {
            // Get the ObjectContext related to this DbContext
            var objectContext = (this as IObjectContextAdapter).ObjectContext;

            // Sets the command timeout for all the commands
            objectContext.CommandTimeout = 180;
        }

Tuesday, March 12, 2013

SQL XML - CROSS APPLY V/S OUTER APPLY


Hello Friends,


I was working on an XML data in SQL and I was confused when using CROSS APPLY OR OUTER APPLY.

So I tried to find the difference and felt this is worth to share.

Please Take a look forward and find the difference between CROSS APPLY and OUTER APPLY


The APPLY operator comes in two variants, CROSS APPLY and OUTER APPLY. 
CROSS APPLY is equivalent to an INNER JOIN expression and 
OUTER APPLY is equivalent to a LEFT OUTER JOIN expression.

Sample XML

DECLARE @Xml AS XML =
 '<Child1 Data="Child1-Data">
          <Child2 Data="Child2-Data-1">
                <Child3 Data="Child3-Data" />
         </Child2>
         <Child2 Data="Child2-Data-2">
        </Child2>
</Child1>'


Cross Apply : Cross apply is basically use inner join of two xml collection

SELECT Child1.value('@Data', 'VARCHAR(MAX)') AS [Child1]
              ,Child2.value('@Data', 'VARCHAR(MAX)') AS [Child2]
           ,Child3.value('@Data', 'VARCHAR(MAX)') AS [Child3]
FROM @Xml.nodes('Child1') d1(Child1)
                CROSS APPLY Child1.nodes('Child2') d2(Child2)
                CROSS APPLY Child2.nodes('Child3') d3(Child3)

Output

Child1
Child2
Child3
Child1-Data
Child2-Data-1
Child3-Data

Outer Apply: Outer apply basically uses left outer join of two XML collections

SELECT Child1.value('@Data', 'VARCHAR(MAX)') AS [Child1]
              ,Child2.value('@Data', 'VARCHAR(MAX)') AS [Child2]
           ,Child3.value('@Data', 'VARCHAR(MAX)') AS [Child3]
FROM @Xml.nodes('Child1') d1(Child1)
                OUTER APPLY Child1.nodes('Child2') d2(Child2)
                
OUTER  APPLY Child2.nodes('Child3') d3(Child3)
Output

Child1
Child2
Child3
Child1-Data
Child2-Data-1
Child3-Data
Child1-Data
Child2-Data-2
NULL


Here you can see, we don't have data in Child3 (See Sample XML) for second node
 So In CROSS APPLY It will not select that row.
 and In OUTER APPLY it will select the row but display NULL in that row.

Friday, June 15, 2012

Easy way to generate random character string for password in SQL Server


Hi Friends!

I was searching for generating random character string for password in SQL Server and goggled a lot.

I have found various stored procedures and functions to generate random character password (it was really big procedures/functions !!)  So I have given a thought and an idea strike on my mind and then I have found following, the most simplest way to generate random character string of password.

SELECT 
LEFT(UPPER(NEWID()), 2) + 
LEFT(LOWER(NEWID()), 2) + 
LEFT(UPPER(NEWID()), 2) + 
LEFT(LOWER(NEWID()), 2)

The above is very basic form to generate random character string for password. you can customize this according to your requirement (like variable password length and etc.)

Happy Programming :)

Wednesday, May 30, 2012

jQuery 1.4.x Ajax traditional option



I have a very simple jQuery code that basically sends an array of integer back to my ASP.NET MVC Controller class.

jQuery code

$.ajax({
   type: 'POST',
   url: "/MyController/MyAction",
   data: { myArray: ids }
});

My controller action:

public void MyAction (int[] myArray) {
   // do stuff here ...
}

But upon upgrading to jQuery 1.4.x, it does not work anymore. The param "myArray" in MyAction is always null.

During debugging, I found out that somehow it sent the post data as "myArray[]" instead of "myArray". 

We cannot name a parameter name with brackets in C# so simply renaming the parameter name in MyAction won't work.

After some readings, it turns out that this is a change in the jQuery 1.4 release - it changes the way it does param serialization. But, jQuery also provides a new flag in $.ajax to override the default behavior (and go back to use the old way of param serialization): the "traditional" option in 

$.ajax. So here is my revised code:

$.ajax({
   type: 'POST',
   url: "/MyController/MyAction",
   data: { myArray: ids },
   traditional: true
});

You can read more about the new param serialization here.

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 );