ASP.NET – How to call a server-side method from client-side JavaScript

Decoding the Web

Introduction

This is a tutorial on how to call a server-side ASP.NET method from a client-side JavaScript method.

If you are wondering when that could become useful, imagine the following scenario:

A Web Application having an implemented authentication system.
Users log in with their username and password.
At any point the user is able to log out by clicking on the respective “Log Out” button.
On the server-side, the log out action would trigger a cleaning up process of user’s temp data.

However, the user instead of clicking on the “Log Out” button, may simply close the browser window. Now since HTTP is a stateless protocol, the server-side cannot directly detect the user’s action. Therefore the client-side (browser) would have to notify the server that the user is closing the window.

A solution to this problem would be to call a JavaScript function when the client-side “onUnload” event…

View original post 397 more words

Converting Linq Expressions to T-SQL

devioblog

In my post about a Batch Update command for Linq To SQL, the code I presented uses a method ToMSSqlString() which has not yet been defined.

The method converts a Linq Expression to a T-SQL expression by evaluating the current node of the expression tree and evaluation the node’s children:

public static class ExpressionExtensions { public static string ToMSSqlString(this Expression expression) { switch (expression.NodeType) { case ExpressionType.Add: var add = expression as BinaryExpression; return add.Left.ToMSSqlString() + " + " + add.Right.ToMSSqlString(); case ExpressionType.Constant: var constant = expression as ConstantExpression; if (constant.Type == typeof(string)) return "N'" + constant.Value.ToString().Replace("'", "''") + "'"; return constant.Value.ToString(); case ExpressionType.Equal: var equal = expression as BinaryExpression; return equal.Left.ToMSSqlString() + " = " + equal.Right.ToMSSqlString(); case ExpressionType.Lambda: var l = expression as LambdaExpression; return l.Body.ToMSSqlString(); case ExpressionType.MemberAccess: var memberaccess = expression as MemberExpression; // todo: if column aliases are used, look up ColumnAttribute.Name return "[" +…

View original post 74 more words

Obtain query string in jquery

function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash
= hashes[i].split('=');
vars
.push(hash[0]);
vars
[hash[0]] = hash[1];
}
return vars;
}

For example, if you have the URL:



http://www.example.com/?me=myValue&name2=SomeOtherValue

This code will return:

{
"me" : "myValue",
"name2" : "SomeOtherValue"
}

and you can do:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];

jQuery – Correct way to check if object is null or Empty

jQuery – Correct way to check if object is null or Empty

Yesterday, I ran into a interesting and frustrating situation where for couple of minutes I was not able to find out what’s wrong with my code. But I learned something new. Let me first give you an idea about what I was working on. I was creating a function, which first checks of div element object. If not found, then create a new div element and insert in DOM otherwise just update the html of div.
Below is the jQuery code.

01 $(document).ready(function () {
02     function UpdateHTML()
03     {
04         var $dvElement = $('#dvElement');
05         if (!$dvElement)
06         {
07             $("<div />", {
08                 id: 'dvElement',
09                 html: 'Added Just now'
10             }).appendTo('body');
11         }
12         else
13             $dvElement.html('Updated HTML');
14     }
15 });

When this function is called, it does nothing. In the first call, it should create a div but it was not. When I debugged, I found that it is always going in else part of the condition. The condition (!$dvElement) always returning false. Wooo..Confused…
Every time when we pass a selector to jQuery function, it will always return a jQuery object. So whether the div exist or not, an object is returned. And when we test the jQuery object inside if statement, it will always be TRUE.
To fix the above code, we need to find out whether the object is empty. And there are 2 ways to fix this.

  • length property: Returns number of elements in object
  • $.isEmptyObject(Object): Returns true if the object doesn’t define any methods or properties.

So fix is,

01 $(document).ready(function () {
02     function UpdateHTML()
03     {
04         var $dvElement = $('#dvElement');
05         if (!$dvElement.length)  // OR !$.isEmptyObject($dvElement)
06         {
07             $("<div />", {
08                 id: 'dvElement',
09                 html: 'Added Just now'
10             }).appendTo('body');
11         }
12         else
13             $dvElement.html('Updated HTML');
14     }
15 });

T-SQL Cursor vs Merge

Today we’ll have a look at Microsoft SQL Server programming and specifically the CURSOR and MERGE statements.

A cursor can be used to loop through a set of rows programmatic-ally.  Their use is discouraged because they tend to perform poorly.  It’s usually faster to work with a set of records instead of ‘walking through’ a table, one row at a time.

Let’s have a look at the difference in performance between a cursor and the merge statement. 

Imagine a table with stock prices (dbo.Securities) that is updated with new prices every day.
After each update, we want to move SecurityID, Price and PriceDate to the dbo.PriceHistory table. 

We will need to check if the combination of SecurityID and PriceDate exists in the target table.  If it doesn’t then we will INSERT a new row.  If it does exist then we will have to UPDATE the existing record. 

We could write a stored procedure that uses a cursor as follows:

CREATE PROCEDURE dbo.SP_InsertPriceHistory AS
SET NOCOUNT ON;
DECLARE @MySecID int;
DECLARE @MyDate date;
DECLARE @MyPrice numeric(12,4);

DECLARE MyCur CURSOR FAST_FORWARD
  FOR SELECT Securityid, Price, PriceDate
  FROM dbo.Securities ORDER BY SecurityID;
OPEN MyCur;
FETCH NEXT FROM MyCur INTO @MySecID, @MyPrice, @MyDate;
WHILE @@FETCH_STATUS = 0
BEGIN
  –Check if record exists
    

  IF EXISTS (SELECT * FROM dbo.PriceHistory

             WHERE PriceDate = @MyDate and SecurityID = @MySecID)
    BEGIN
      –Record exists – Update
      UPDATE dbo.PriceHistory SET PriceDate = @MyPrice
        WHERE (SecurityID = @MySecID AND PriceDate = @MyDate);
    END
  ELSE
    BEGIN
       
      –Record does not exist – Insert
      INSERT INTO dbo.PriceHistory (SecurityID, PriceDate, Price)
        VALUES(@MySecID, @MyDate, @MyPrice);
        
    END
  FETCH NEXT FROM MyCur INTO @MySecID, @MyPrice, @MyDate;
END
CLOSE MyCur;
DEALLOCATE MyCur;


We can achieve the same result using the Merge statement.  The stored procedure might look like this:

CREATE PROCEDURE dbo.SP_InsertPriceHistory AS
SET NOCOUNT ON;

MERGE INTO dbo.PriceHistory AS TGT
  USING dbo.Securities AS SRC
  ON SRC.SecurityID = TGT.SecurityID AND

    SRC.PriceDate = TGT.PriceDate
  WHEN MATCHED THEN

    UPDATE SET TGT.Price = SRC.Price;
  WHEN NOT MATCHED 
THEN
    INSERT VALUES(SRC.SecurityID, SRC.PriceDate, SRC.Price);


SQL server will check for a match between the source and target table by comparing both the SecurityID and PriceDate columns.

If there is a match then it will run the code after WHEN MATCHED THEN

If there is no match then it means that no price is stored for this particular security on this date and it will run the code after WHEN NOT MATCHED THEN

Not only is this code easier to read, it is also much faster.  
 
For more details on Merge have a look at Merge on Microsoft technet. 

PS we can slightly improve the performance of both stored procedures by checking if an update is really necessary.  We can do this by comparing the price of the source with the price of the target table.  If the price is the same then we can skip the update.

SQL Server Exception Handling by TRY…CATCH

Like C#, SQL Server also has an exception model to handle exceptions and errors that occurs in T-SQL statements. To handle exception in Sql Server we have TRY..CATCH blocks. We put T-SQL statements in TRY block and to handle exception we write code in CATCH block. If there is an error in code within TRY block then the control will automatically jump to the corresponding CATCH blocks. In Sql Server, against a Try block we can have only one CATCH block.

TRY..CATCH Syntax



  1. BEGIN TRY



  2. --T-SQL statements



  3. --or T-SQL statement blocks



  4. END TRY



  5. BEGIN CATCH



  6. --T-SQL statements



  7. --or T-SQL statement blocks



  8. END CATCH




Error Functions used within CATCH block

  1. ERROR_NUMBER()

    This returns the error number and its value is same as for @@ERROR function.

  2. ERROR_LINE()

    This returns the line number of T-SQL statement that caused error.

  3. ERROR_SEVERITY()

    This returns the severity level of the error.

  4. ERROR_STATE()

    This returns the state number of the error.

  5. ERROR_PROCEDURE()

    This returns the name of the stored procedure or trigger where the error occurred.

  6. ERROR_MESSAGE()

    This returns the full text of error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

Exception handling example



  1. BEGIN TRY



  2. DECLARE @num INT, @msg varchar(200)



  3. ---- Divide by zero to generate Error



  4. SET @num = 5/0



  5. PRINT 'This will not execute'



  6. END TRY



  7. BEGIN CATCH



  8. PRINT 'Error occured that is'



  9. set @msg=(SELECT ERROR_MESSAGE())



  10. print @msg;



  11. END CATCH



  12. GO







  1. BEGIN TRY



  2. DECLARE @num INT



  3. ---- Divide by zero to generate Error



  4. SET @num = 5/0



  5. PRINT 'This will not execute'



  6. END TRY



  7. BEGIN CATCH



  8. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;



  9. END CATCH;



  10. GO






Note

  1. A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19.
  2. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the CATCH block is ignored.
  3. Each TRY block is associated with only one CATCH block and vice versa
  4. TRY and CATCH blocks can’t be separated with the GO statement. We need to put both TRY and CATCH blocks within the same batch.
  5. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using @@TRANCOUNT function in Sql Server.
  6. XACT_STATE function within the TRY..CATCH block can be used to check whether a open transaction is committed or not. It will return -1 if transaction is not committed else returns 1.

Difference Between Constant and ReadOnly and Static

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.

Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.


  1. public const int X = 10;


A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.


  1. void Calculate(int Z)

  2. {

  3. const int X = 10, X1 = 50;

  4. const int Y = X + X1; //no error, since its evaluated a compile time

  5. const int Y1 = X + Z; //gives error, since its evaluated at run time

  6. }


You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.


  1. const MyClass obj1 = null;//no error, since its evaluated a compile time

  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time


Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.


  1. class MyClass

  2. {

  3. readonly int X = 10; // initialized at the time of declaration

  4. readonly int X1;

  5.  

  6. public MyClass(int x1)

  7. {

  8. X1 = x1; // initialized at run time

  9. }

  10. }


Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.

Static

The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.


  1. class MyClass

  2. {

  3. static int X = 10;

  4. int Y = 20;

  5. public static void Show()

  6. {

  7. Console.WriteLine(X);

  8. Console.WriteLine(Y); //error, since you can access only static members

  9. }

  10. }


Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can’t be parameterized and public. Static constructor is always a private default constructor which is used to initialize static fields of the class.

Convert Enum to Dictionary C#

While working through ,I have always faced problems where only of i could convert an enum to Dictionary. Here's how you do it.

Code:
/// <summary>
/// Converts Enumeration type into a dictionary of names and values
/// </summary>
/// <param name="t">Enum type</param>
public static IDictionary<string, int> EnumToDictionary(this Type t)
{
    if (t == null) throw new NullReferenceException();
    if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");
    string[] names = Enum.GetNames(t);
    Array values = Enum.GetValues(t);
    return (from i in Enumerable.Range(0, names.Length)
            select new { Key = names[i], Value = (int)values.GetValue(i) })
                .ToDictionary(k => k.Key, k => k.Value);
}

Example:
var dictionary = typeof(UriFormat).EnumToDictionary();
/* returns
key => value
SafeUnescaped => 3
Unescaped => 2
UriEscaped => 1
*/

Creating Custom Validation using IValidatableObject (DataAnnotation) in ASP.NET MVC

.NET Framework provides a set of inbuilt data validation using DataAnnotation. 

But there might be cases where you might need to validate with your custom rules. Example of such case is like when you need to compare two values and one must be greater than (or less than another).

Here’s how you do it. 

You can change your Validate Function as per your need.
public class ViewModel: IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    [Required]   
    public DateTime EndDate { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (EndDate < StartDate)
       {
           return new ValidationResult(“EndDate must be greater than StartDate”);
       }
    }
}
Happy Coding!