Tuesday, August 17, 2010

LINQ to SQL – Generic Insert

Currently I’m working on a project’s data layer code. I’ve chosen LINQ to SQL for this purpose and created a helper library to perform CRUD operations in an easy and generic way.

Following is the code which insert any database object using LINQ:

   1: public static void Insert<T>(T entityData) where T : class
   2: {
   3:     using (TransactionScope trans = new TransactionScope())
   4:     {
   5:         using (App_Data.DBDataContext db = new App_Data.DBDataContext())
   6:         {
   7:             db.GetTable<T>().InsertOnSubmit(entityData);
   8:             db.SubmitChanges();
   9:             trans.Complete();
  10:         }
  11:     }
  12: }

Technorati Tags:

Few noteworthy points:

  • I’m using transaction scope but we can omit that, because for single update or insert, LINQ already provides transaction support. This is only required while making multiple inserts or updates
  • Conditional generics are used because GetTable<T>() requires T to be a reference type
  • Just like above method, update and delete can also be implemented

Usage

  • Suppose you have a database table Order
  • In LINQ to SQL, this table is represented as a class, in which table columns are represented as properties
  • To insert a new record for Order
    • Create new object of Order – Order orderNewObject = new Order();
    • Fill orderNewObject properties with desired values
    • Pass this new object to Insert method like this - Insert<Order>(orderNewObject);

Using above method we can easily perform database operation without even writing a single T-SQL statement.

Cheers!

Wednesday, August 11, 2010

SQL Server - NULL

There is a bit of inconsistency in the way SQL Server treats (read it as implements) NULLs. Following are some noteworthy points related to implementation and usage of NULL values in SQL Server:

  • 3 possible values of logical expression
    • TRUE
    • FALSE
    • UNKNOWN
  • UNKNOWN occurs when a logical expression involves NULL
    • NULL > 2 is UNKNOWN
    • NULL = NULL is UNKNOWN
    • X + NULL is UNKNOWN
    • (NOT (UNKNOWN)) IS UNKNOWN
  • Query filters (ON, WHERE, HAVING) treat UNKNOWN as FALSE
  • CHECK constraint treat UNKNOWN as TRUE
  • During comparison NULL = NULL is treated as not equal
  • UNIQUE constraint, UNION, EXCEPT, SORTING and GROUPING treats NULLs as equal

This information is quite handy when you are writing TSQL queries targeting data with NULL values.

Cheers!
Currently Playing – Not Afraid by Eminem

Technorati Tags: ,,

del.icio.us Tags: ,,

Thursday, June 24, 2010

Windows Azure – Custom configuration settings

Few days back, I received a question on our internal Azure discussion DL regarding, how we can have settings defined in a web configuration file implemented in a web role. In simple terms, how we can have configuration file in a Windows Azure application.

This is how we can do this;

During development

  • ServiceDefinition.csdef – Add name of your custom configuration

image

  • ServiceConfiguration.cscfg – Add value to your custom configuration

image

  • Now, use this custom configuration in code

image

When you publish this project, generated ServiceConfiguration.cscfg will have your custom configuration key value pair. You can also modify this after you deploy your app in the cloud.

Technorati Tags: ,

~pEaCe~

Saturday, May 1, 2010

Post Back from AJAX Update Panel

Recently, while working on a dev assignment I needed to make a complete post back (with page refresh) from a button control placed inside AJAX Update Panel. Exact problem was like this. There is a webpage on which I require AJAX functionality. Also, there is one button on whose click I want to make a post back. That button is also placed inside AJAX update panel and anything placed inside update panel by default does a Ajax callback. Sample web page is shown below:

image

Initially I thought of moving my Post Back Call button outside of AJAX update panel but that would have ruined my UI design. I was trying different options when I stumbled upon UpdatePanel’s child element <Triggers>. <Triggers> provides another child element <asp:PostBackTrigger /> with an attribute ControlID. We can specify from which control we want to make a post back call using this ControlID. Below code sample shows how to do this in ASP.NET.

image

This is quite simple to understand. Button btnPostBackCall will now make a complete call back. I recommend further reading on this topic from:

Currently Listening To: Heartbreak Warfare by John Mayer
~eNjOy~

Friday, March 12, 2010

WCF – Exception Handling in Asynchronous Operations

Yesterday, I got a query regarding how to handle exceptions in case of asynchronous web service operations. Precise question was,

I am calling a WCF service using Asynchronous way,  the service may execute for some time, meanwhile if any exception occurred in the service side how can I come to know what happened in the service side?

I am not able to get the status in the Async Method.

There is a pretty simple solution available for this problem.

When the asynchronous method throws an exception, proxy catches it and when the client calls End Operation the proxy re-throws that exception object so that client can handle the exception. If a COMPLETION CALLBACK is provided, WCF calls that method immediately after the exception is received. Exception thrown is compliant with the fault contract and type of exception. Following code snippet shows how to do this;

Contract Code

public interface ICalculator
{
[OperationContract]
[FaultContract(typeof(Exception))]
double Add(double n1, double n2);
}



Service Code




public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
throw new FaultException<Exception>(new Exception("Gaurav is sending exception"));
return n1 + n2;
}
}



Client Code




class Client
{
static void Main()
{
Console.WriteLine("Press <ENTER> to terminate client once the output is displayed.");
Console.WriteLine();

GauravCalculator.CalculatorClient calcService = new GauravCalculator.CalculatorClient();
int sum = 0;
AsyncCallback completion = (result) =>
{
try
{
sum = (int)calcService.EndAdd(result);
Console.WriteLine("Sum is :" +sum.ToString());
calcService.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
};
calcService.BeginAdd(10, 10, completion, null);

Console.WriteLine();
}



Using this method you can receive any service side exceptions on client side.

~pEaCe~


Currently Listening to: Bekaraar from Pathshala (new Lucky Ali song)

Wednesday, March 3, 2010

GO – SQL Server

While working on SQL Server we all encounter GO statement quite often. Till today GO statement for me was just an indication sent out to SQL Server utilities about end of a batch of Transact - SQL.

Today while going through MSDN I found a new (surprising) thing about GO. Go can actually take an integer argument. Yes! it is true. Go takes an optional integer argument. Something like this,

GO [count]

As per MSDN,

count is a positive integer. The batch preceding GO will execute the specified number of times.

What this means is, suppose you have a script like the one below,

INSERT INTO TestGO VALUES (10, 'testing go')
GO 5000

Here, INSERT statement will be executed 5000 times and you will end up inserting 5000 records in table.

~eNjOy LiFe~
Currently Listening to: In the summer time - SHAGGY

Friday, February 19, 2010

Back from Redmond

Few weeks back I visited Microsoft office in Redmond, WA. That trip turned out to be a super roller coaster ride. Day I landed in our office some unexpected very high priority work came up and we started work on it without wasting any time. I got to work with some top technical and management guys.

During my work I interacted with various Microsoft GM’s and members of top leadership team. I also got a chance to work with SQL Server Query Optimization Engine team members like Lubor Kollar. Lubor is the one who designed partitioned tables and CTEs in SQL Server. He suggested few query optimization points related to my work as well. On my last day in Redmond, he gifted me one of his latest book on Query Optimization. Awesome! book.

First 2 weeks were quite hectic in terms of work. We worked for almost 12 hrs daily and yes we worked on weekends too. After first 2 weeks we got time to visit some really nice places in Redmond. We visited Snoqualmie, Mount Reiner and Seattle Downtown.

This year I’m concentrating on WCF, SQL Server Query Optimization and some misc stuff like power shell. I’ll continue posting blog entries related to these.

Friday, January 8, 2010

IIS 7.0 – Site Vs. Application Vs. Virtual Directory

Another thing with IIS 7.0 which always bothers me is exact difference between web site , application and virtual directory. There is lot of verbose information present online related to this topic. After going through few good web links I managed to prepare a summary of the differences, that is easy to understand and remember.

[ Note: It is highly possible that you might get this information from MSDN or IIS web logs as I prepared it from there :) ]

Introduction
  • A site contains one or more applications, an application contains one or more virtual directories, and a virtual directory maps to a physical directory on a computer
  • A site contains all the content, both static and dynamic, that is associated with that site.
  • Each site must contain at least one application, which is named the root application.
  • Each application (including the root application) must contain at least one virtual directory, which is named the root virtual directory. These objects work together to form the site.
  • An application can have several virtual directories, and each one will be served by the same App Domain as the application to which they belong.
Site
  • Container for applications and virtual directories, and you can access it through one or more unique bindings.
  • The binding includes two attributes important for communication: the binding protocol and the binding information (combination of IP address, port, and optional host header)
  • A site may contain more than one binding
  • In addition to containing applications (which contain virtual directories) and specifying bindings, the following configuration settings belong to the site:
        • Limits: configure settings to limit the amount of bandwidth, the number of connections, or the amount of time allowed for connections to a site.
        • Logging: configure settings for handling and storage of log files for the site.
        • Failed request trace logs: configure settings for logging failed-request traces for the site
APPLICATION
  • Group of files that delivers content or provides services over protocols
  • Application's path becomes part of the site's URL
  • In addition to belonging to a site, an application belongs to an application pool, which isolates the application from applications in other application pools on the server.
VIRTUAL DIRECTORY
  • Map to a physical directory on a local or remote server
  • Directory name then becomes part of the application's URL
  • An application can have more than one virtual directory
  • For example, you might use a virtual directory when you want your application to include images from another location in the file system, but you do not want to move the image files into the physical directory that is mapped to the application's root virtual directory.

I hope! things are much clearer now.

eNjOy cOdInG!!
Currently Listening to: John Lennon - Happy Xmas (War Is Over)

Thursday, January 7, 2010

IIS 7.0 – Classic and Integrated pipeline

While creating a new app pool, users are required to choose framework version and pipeline type. I was not sure about the difference between available pipeline types. I spent some time on this topic and reading MSDN articles. this is what I understood:

Classic Pipe Line in IIS 7.0

  • Works just like IIS 6.0
  • All requests pass through the IIS pipeline first, and then if the file extension is mapped to ASP.NET ISAPI extension, then the request is handed to aspnet_isapi.dll and passes through the ASP.NET request pipeline.
  • If the file is static file, ASP or PHP, it is handled by something else.

Integrated Pipeline IIS 7.0

  • Allows http modules to participate in all requests
  • This works also for static contents, PHP pages and image
  • Provides unified request processing, regardless of handler
  • For example, managed Forms Authentication can be used for all content, including ASP pages, CGIs, and static files.

Cheers!!!

Saturday, December 19, 2009

Windows Live Writer

This is my first post on blog spot using windows live write. There is no special content in this post. I wanted to check if all plug-ins will work as they are supposed to work.

  • Image

1

  • One Two
    Three Four
  • Map

Map picture

  • Code
using System;
internal class MySampleClass
{
void MySampleClass()
{
//Do nothing;
}
}





Let’s see how all these things reflects back to my blog spot blog.

Friday, December 18, 2009

Linked In - Sophisticated version of Monster job

I’m using linked-in from past one year now and initially I felt it is a nice networking tool for people looking to connect with people with similar appetite towards technology. Suppose, if I’m looking out for a mentor, it is actually tough to achieve this using linked in. What best you can do is this, message your friends and ask them if they know anybody who can mentor you and keep doing this till you get a nice mentor. Another point that I notice nowadays is that, I get random messages from people asking for recommendations. Few days back I got one message asking me to recommend him. Surprisingly, I never worked with that guy and my knowledge about his work is ZERO. I don’t know why people do these things. Linked in is becoming a place full of false recommendations which is very sad. I always make a point that I never make any false recommendations. I think it is bad for the industry. I feel it is becoming sophisticated version of monster job or naukri.

//Currently Watching - Biography Leonardo Da Vinci
//Cheers!!

Sunday, December 6, 2009

SQL Server - Size of Index Table for Each Index

I'm a regular reader of Pinal's SQL Authority blog. Few days back, he posted a puzzle to find index size of each index on table. I was able to solve the puzzle and my solution was one of the two solutions selected by Pinal.

Check it out from here

//Cheers!
//Currently listening to - Thirteen by Danzing

System.Transaction.IsolationLevel

A little amusing observation,
IsolationLevel enumeration defined in the System.Transactions namespace looks something like this:
public enum IsolationLevel
{
Unspecified,
ReadUncommitted,

RepeatableRead,
ReadCommitted,
Serializable,
Chaos,
Snapshot
}
By definition, chaos means -"a state of extreme confusion and disporder. " Initially I was not able to understand what is the whole purpose of having this option (that too with a funny name)
After doing some reading (on MSDN) and talking (with peer devs), this is what I understood.

Chaos Isolation Level - Behaves the same way as Read Uncommited, with additional features as stated below:

  • It permits viewing uncommitted changes by other transactions
  • It checks any other uncompleted update transactions with higher restrictive isolation levels to ensure not to raise any conflics i.e. any oending changes from more highly isolated transactions cannot be overwritten
  • Rollback is not supported in this isolation level

If you want to perform read operations over once per transaction, then go for the Chaos isolation level

Chaos isolation level is present in SSIS as well. Select the task or container on which you want to set the isolation level. Then go to the properties and set the property named IsolationLevel to Chaos.

//Cheers!
//Currently listening to: Put your hands up (Radio Edit) by Wet Fingers

Sunday, November 1, 2009

Visual Studio 2010 Beta 2

From last few weeks I'm using VS 2010 for my daily coding work. Apart from lot of feature add-ons, this time VS got a new look. Check out these captures;
  • Visual Studio 2010 Beta 2 - Splash Screen

  • New Startup Screen




VS 2010 Rocks!!!
Scott Gu is running a series on VS 2010 and .Net 4.0 new features. Do check them out at his blog
Cheers!

Wednesday, October 7, 2009

Simplest way to prevent Phishing Attack on IE 8

Phishing attacks are becoming common these days. Recently there was a massive phishing attack reported on Hotmail. There are few easy ways by which we can prevent phishing attacks.

I use IE 8 as my default browser and it provides a nice feature known as Smart Screen Filter which helps us in identifying phishing attacks. There is also a online publication provided by Microsoft that helps in identifying phishing attacks.

I follow a simple funda while browsing web sites, whenever I require entering important information like user name, password or financial information, I look at the IE 8's address bar and identify the actual domain name of the URL. IE 8 highlight the domain name by marking it black in color while rest of the url remains grey. This helps a lot. Screen shot of Windows Live login screen is shown below.

Happy Surfing!

Saturday, September 26, 2009

Library Design - Documenting Exceptions

I’m sure most of you might already know but I thought of sharing this. If we are coding for a class library then we should always try to explicitly provide exception type that our code (method) will throw. If we provide exception values in XML Comments then those exceptions will appear in intellisense while we are using that library method. This will be handy for developers using our library. I remember this is also mentioned somewhere in framework design guidelines.
  • Method definition: Explicit exception details provided

  • Method Usage: Intellisense contains list of exceptions

Cheers!
Currently Playing : PROTOTYPE

Monday, June 8, 2009

Functional Programming

Few days back while reading about F# I got hold of a nice old article on Functional Programming. Check it out here

I'm on my F# journey from past few weeks. Let us see how far this goes.

Wednesday, May 20, 2009

SQL Server 2008 - Policy Based Management

Few days back I posted an article on MSDN related to SQL Server 2008 Policy Based Management. Check it our if you are interested in Server 2008 new features.

Sunday, April 26, 2009

New definition to C#

If anyone asksus , what is C#, what will be our answer? All of us will say, C# is an Object Oriented Language targeting .NET run time. Today this definition of C# is only 10% correct or you can say 10% complete. Surprised! read ahead.

Few days back, I was listening to Anders Hejlsberg's PDC 2008 presentation on C# 4.0. There he formulated a new definition for C#.
C# is a multi-paradigm language that covers functional, imperative, generic, object oriented and component oriented disciplines.

C# 2.0 introduced some concepts of functional languages like anonymous methods and then came LINQ. F#, a pure functional language, makes extensive use of anonymous methods to achieve its goal. C# 4.0 will introduce new features that makes it interoperable with domain specific languages targeting .Net run time.

Some important links:

Currently Listening - Feel the Rush by Shaggy
~eNjOy CoDiNg~

Saturday, April 18, 2009

Places where I'm blogging

Connected Information Security Group blog. This is now closed as our team name is changed.
http//blogs.msdn.com/cisg/

Our team got a new name, Information Security Tools, hence a new blog site,
http://blogs.msdn.com/securitytools/

My good old blogspot account where I started blogging few years back.
http://fun-with-blackhawk.blogspot.com/

I'll use security tools blog for topics related to my work and application security and for all other things I'll use my blogspot account.

Cheers!