Translate

Thursday, 12 June 2014

Raiserror Vs Throw


Below table lists-out 10 major difference between RAISERROR and THROW with examples:


RAISERRORTHROW
Version of the Sql Server in which it is introduced?
Introduced in SQL SERVER 7.0. And as per BOL,Microsoft is suggesting to start using THROW statement instead of RAISERROR in New Applications.
RAISERROR can’t be used in the Sql Server 2014′s Natively compiled Stored Procedures.
Introduced in SQL SERVER 2012. THROW statement seems to be simple and easy to use than RAISERROR.
THROW statement can be used in the Sql Server 2014′s Natively Compiled Stored Procedure.
SYNTAX
RAISERROR
 ( { error_number | message
        | @local_variable }
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]
THROW
 [ { error_number
     | @local_variable },
   { message | @local_variable },
   { state | @local_variable } ]
[ ; ]
Can re-throw the original exception that invoked the CATCH block?
NO. It always generates new exception and results in the loss of the original exception details. Below example demonstrates this:
BEGIN TRY
  DECLARE @result INT
--Generate divide-by-zero error
  SET @result = 55/0
END TRY
BEGIN CATCH
--Get the details of the error
--that invoked the CATCH block
 DECLARE
   @ErMessage NVARCHAR(2048),
   @ErSeverity INT,
   @ErState INT
 SELECT
   @ErMessage = ERROR_MESSAGE(),
   @ErSeverity = ERROR_SEVERITY(),
   @ErState = ERROR_STATE()
 RAISERROR (@ErMessage,
             @ErSeverity,
             @ErState )
END CATCH
RESULT:
Msg 50000, Level 16, State 1, Line 19
Divide by zero error encountered.
NOTE:The actual line number of the code which generated Divided By Zero error here is 4, but the exception message returned by RAISERROR is showiung it as 19. Also the error number corresponding to divide by zero error is 8134 in the SYS.Messages table, but the one returned by RAISERROR is 50000.
YES. To Re-THROW the original exception caught in the TRY Block, we can just specify the THROW statement without any parameters in the CATCH block. Below example demonstrates this:
BEGIN TRY
  DECLARE @result INT
--Generate divide-by-zero error
  SET @result = 55/0
END TRY
BEGIN CATCH
    THROW
END CATCH
RESULT:
Msg 8134, Level 16, State 1, Line 4
Divide by zero error encountered.
With above example it is clear that THROW statement is very simple for RE-THROWING the exception. And also it returns correct error number and line number.
Causes the statement batch to be ended?
Example 1: In the below Batch of statements the PRINT statement after RAISERROR statement will be executed.
BEGIN
 PRINT 'BEFORE RAISERROR'
 RAISERROR('RAISERROR TEST',16,1)
 PRINT 'AFTER RAISERROR'
END
RESULT:
BEFORE RAISERROR
Msg 50000, Level 16, State 1, Line 3
RAISERROR TEST

AFTER RAISERROR
Example 2: In the below example all the statement’s after RAISERROR statement are executed.
BEGIN TRY
 DECLARE @RESULT INT = 55/0
END TRY
BEGIN CATCH
 PRINT 'BEFORE RAISERROR';
--Get the details of the error
--that invoked the CATCH block
 DECLARE
  @ErMessage NVARCHAR(2048),
  @ErSeverity INT,
  @ErState INT
 SELECT
  @ErMessage = ERROR_MESSAGE(),
  @ErSeverity = ERROR_SEVERITY(),
  @ErState = ERROR_STATE()
 RAISERROR (@ErMessage,
             @ErSeverity,
             @ErState )
 PRINT 'AFTER RAISERROR'
END CATCH
 PRINT 'AFTER CATCH'
RESULT:
BEFORE RAISERROR
Msg 50000, Level 16, State 1, Line 19
Divide by zero error encountered.

AFTER RAISERROR
AFTER CATCH
Example 1: In the below Batch of statements the PRINT statement after THROW statement will not executed.
BEGIN
    PRINT 'BEFORE THROW';
    THROW 50000,'THROW TEST',1
    PRINT 'AFTER THROW'
END
RESULT:
BEFORE THROW
Msg 50000, Level 16, State 1, Line 3
THROW TEST
Example 2: In the below example no PRINT statement’s after THROW statement are executed.
BEGIN TRY
  DECLARE @RESULT INT = 55/0   
END TRY
BEGIN CATCH
  PRINT 'BEFORE THROW';
  THROW;
  PRINT 'AFTER THROW'
END CATCH
  PRINT 'AFTER CATCH'
RESULT:
BEFORE THROW
Msg 8134, Level 16, State 1, Line 2
Divide by zero error encountered.
CAN SET SEVERITY LEVEL?
YES. The severity parameter specifies the severity of the exception.NO. There is no severity parameter. The exception severity is always set to 16. (unless re-throwing in a CATCH block)
Requires preceding statement to end with semicolon (;) statement terminator?
NO.YES. The statement before the THROW statement must be followed by the semicolon (;) statement terminator.
CAN RAISE SYSTEM ERROR MESSAGE?
The SYS.MESSAGES Table will have both system-defined and user-defined messages. Message IDs less than 50000 are system messages.
YES. With RAISERROR we can raise the System Exception.
Example:
RAISERROR (40655,16,1)RESULT:
Msg 40655, Level 16, State 1, Line 1
Database ‘master’ cannot be restored.
NO. With THROW we can’t raise the System Exception. But when it used in CATCH BLOCK it can Re-THROW the system exception.Example: Trying to raise system exception (i.e. exception with ErrorNumber less than 50000).
THROW 40655, ‘Database master cannot be restored.’, 1
RESULT:
Msg 35100, Level 16, State 10, Line 1
Error number 40655 in the THROW statement is outside the valid range. Specify an error number in the valid range of 50000 to 2147483647
CAN RAISE user-defined message with message_id greater than 50000 which is not defined in SYS.MESSAGES table?
NO. If a msg_id is passed to RAISERROR, the ID must be defined in sys.messages.Example:
RAISERROR (60000, 16, 1)
RESULT:
Msg 18054, Level 16, State 1, Line 1
Error 60000, severity 16, state 1 was raised, but no message with that error number was found in sys.messages. If error is larger than 50000, make sure the user-defined message is added using sp_addmessage.
Now add the Message to SYS.MESSAGES Table by using the below statement:
EXEC sys.sp_addmessage 60000, 16, ‘Test User Defined Message’
Now try to Raise the Error:
RAISERROR (60000, 16, 1)
RESULT:
Msg 60000, Level 16, State 1, Line 1
Test User Defined Message
YES. The error_number parameter does not have to be defined in sys.messages.Example:
THROW 60000, ‘Test User Defined Message’, 1RESULT:
Msg 60000, Level 16, State 1, Line 1
Test User Defined Message
Allows substitution parameters in the message parameter?
By using the below statement add a sample test message with parameteres to the SYS.Messages Table:
EXEC sp_addmessage 70000,16,‘Message with Parameter 1: %d and Parameter 2:%s’
YES.The msg_str parameter can contain printfformatting styles.Example 1:
RAISERROR (70000, 16, 1, 505,‘Basavaraj’ )
RESULT:
Msg 70000, Level 16, State 1, Line 1
Message with Parameter 1: 505 and Parameter 2:Basavaraj
NO.The message parameter does not acceptprintf style formatting.Example 1:
THROW 70000, ‘Message with Parameter 1: %d and Parameter 2:%s’, 1, 505,’Basavaraj’
RESULT:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ‘,’.
Alternative Way of doing this is:
DECLARE @ErrorMsg NVARCHAR(2048) = FORMATMESSAGE(70000, 505, ‘Basavaraj’ );
THROW 70000, @ErrorMsg, 1
Example 2: Message manipulation is not allowed in the THROW statement
Below statement will fail
THROW 58000,‘String1′ + ‘ String2′,1
RESULT:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ‘+’.
We can solve such problems, we can prepare the message prior to the THROW statement and then pass it to throw statement as a variable. Below example illustrates this.
DECLARE @message NVARCHAR(2048)
SET @message = ‘String1′ + ‘ String2′;
THROW 58000, @message, 1
RESULT:
Msg 58000, Level 16, State 1, Line 3
String1 String2

Friday, 6 June 2014

Difference Between Repeater and DataList and GridView

Difference between DataList and Repeater

DataList
Repeater
Rendered as Table.
Template driven.
Automatically generates columns from the data source.
This features is not supported.
Selection of row is supported.
Selection of row is not supported.
Editing of contents is supported.
Editing of contents is not supported.
You can arrange data items horizontally or vertically in DataList by using property RepeatDirection.
This features is not supported.
Performance is slow as compared to Repeater
This is very light weight and fast data control among all the data control.

Difference between GridView and Repeater

GridView
Repeater
It was introduced with Asp.Net 2.0.
It was introduced with Asp.Net 1.0.
Rendered as Table.
Template driven.
Automatically generates columns from the data source.
This features is not supported.
Selection of row is supported.
Selection of row is not supported.
Editing of contents is supported.
Editing of contents is not supported.
Built-in Paging and Sorting is provided.
You need to write custom code.
Supports auto format or style features.
This has no this features.
Performance is very slow as compared to Repeater.
This is very light weight and fast data control among all the data control.

Difference between GridView and DataList

GridView
DataList
It was introduced with Asp.Net 2.0.
It was introduced with Asp.Net 1.0.
Built-in Paging and Sorting is provided.
You need to write custom code.
Built-in supports for Update and Delete operations.
Need to write code for implementing Update and Delete operations.
Supports auto format or style features.
This features is not supported.
RepeatDirection property is not supported.
You can arrange data items horizontally or vertically in DataList by using property RepeatDirection.
Doesn’t support customizable row separator.
Supports customizable row separator by using SeparatorTemplate.
Performance is slow as compared to DataList.
Performance is fast is compared to GridView.

.trim() in JavaScript not working in IE

Add the following code to add trim functionality to the string.
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Thursday, 5 June 2014

Close/kill the session or capture the time when the browser or tab is closed

<script language="javascript" type="text/javascript">
        var isClose = false;

        //this code will handle the F5 or Ctrl+F5 key
        //need to handle more cases like ctrl+R whose codes are not listed here
        document.onkeydown = checkKeycode
        function checkKeycode(e) {
            var keycode;
            if (window.event)
                keycode = window.event.keyCode;
            else if (e)
                keycode = e.which;
            if (keycode == 116) {
                isClose = true;
            }
        }
        function somefunction() {
            isClose = true;
        }

        //<![CDATA[

        function bodyUnload() {


            if (!isClose) {
                var request = GetRequest();
                request.open("GET", "SessionClear.aspx", true);
                request.send();
            }
        }
        function GetRequest() {
            var request = null;
            if (window.XMLHttpRequest) {
                //incase of IE7,FF, Opera and Safari browser
                request = new XMLHttpRequest();
            }
            else {
                //for old browser like IE 6.x and IE 5.x
                request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
            }
            return request;
        }
        //]]>
    </script>
</head>
<body onbeforeunload="bodyUnload();" onmousedown="somefunction()">

Monday, 2 June 2014

Extension Methods in .NET

Why Extension Method: Another question is, why do we need to use the extension methods, we can create our own methods in client application or in other class library and we can call those methods from the client application but the important point is, these methods would not be the part of that class (class of the third party dll). So adding the extension methods in the class, you are indirectly including another behavior in that class. I am talking about the class which is the part of the third party dll (Most Important).

So when you create your own extension methods for specific types those methods would be accessible for that type.

This can be easily understood by the following diagram:

ExMtd1.gif

(I am object of the class)

After some time, client application wants to add another behavior in that class; let's say 'talk' then extension methods can be used to add this extra behavior in that class without altering any code.

ExMtd2.gif

Implementation: The following is the structure of the third party class, which is not accessible to the developer. This class contains a method 'Walk'.
public class Class1{
    public String Walk()
    {
        return "I can Walk";    }}
Now it's time to create the Extension Method. Just use the following steps:

Step 1: Create the Static Class

Step 2: Create the Static Method and give any logical name to it. 

Step 3: In the Extension Method Parameter, just pass this along with the object type and 
the object name as given below:

ExMtd3.gif

The client application can access both the method "Walk" and the extension method "TalkExtMethod":
Class1 obj = new Class1 ();
Obj.TalkExtMethod ()  
obj.Walk ()


Benefits: There may be various benefits of using the Extension Methods in your code. Let's say you are using the method1 () of the class in the third party dll and the object instantiation has failed due to another reason; then you will get the object reference error while calling the method1 () if you did not handle the null reference check.
Class1 obj = GetClass1Object ();//If the obj is null, you will get the object reference errorobj.Method1();

Although the following code is safer than previous one but the problem is you will have to include this check every time when you call the Method1 and if the developer forgets to include this check in the code then the program throws an object reference error.
Class1 obj = GetClass1Object ();if (obj!= null)
{
    obj.Method1 ();
}

If we use the extension method to solve this problem we get outstanding results. Instead of checking the null reference every time in the code we handle it in the extension methods which is called by the client application.
public static string Method1ExtMethod(this Class1 objClass)
{
    //If the obj is not null, then call the Method1()
    if (objClass! = null)
    {
        return objClass.Method1 ();
    }
    return string.Empty;    
}
Class1 obj = GetClass1Object ();//Don't include any check whether the object is null or notobj.Method1ExtMethod()

What is Extension Methods


1.Extension methods allow an existing type to be extended with new methods without altering the definition of the original type. 
2.An extension method is a static method of a static class, where the this modifier is applied to the first parameter. 
3.The type of the first parameter will be the type that is extended.

Example:


public static class StringHelper
{
public static bool IsCapitalized (this string s)
{
if (string.IsNullOrEmpty(s)) return false;
return char.IsUpper (s[0]);
}
}



4.The IsCapitalized extension method can be called as though it were an instance method on a string.

String s = "Perth“;
Console.WriteLine (s.IsCapitalized());

5.An extension method call, when compiled, is translated back into an ordinary static method call.
Console.WriteLine (StringHelper.IsCapitalized (s));


Ambiguity and Resolution about Extension Methods


1.An extension method cannot be accessed unless the namespace is in scope.

2.Any compatible instance method will always take precedence over an extension method.

3. If two extension methods have the same signature, the extension method must be called as an ordinary static method to disambiguate the method to call. 

4.If one extension method has more specific arguments, however, the more specific method takes precedence.

Example :-

static class StringHelper
{
public static bool IsCapitalized (this string s) {...}
}
static class ObjectHelper
{
public static bool IsCapitalized (this object s) {...}
}

bool test1 = "Perth".IsCapitalized();
bool test2 = (ObjectHelper.IsCapitalized ("Perth"));