Good news readers! I have been awarded with Microsoft Community Contributor [MCC] Award 2011 by Microsoft. Its truly said that credit should be given where its due.

Long live the community! :)

Last week, I needed to complete one task on which I am going to blog about in this entry. The task is "Create a control panel like webpage to control (Start/Stop) Window Services which are part of my solution installed on computer where the main application is hosted".

Here are the important points to accomplish:
[1] You need to add System.ServiceProcess reference in your application. This namespace holds ServiceController Class to access the window service.

[2] You need to check the status of the window services before you explicitly start or stop it.

[3] By default, IIS application runs under ASP.NET account which doesn't have access rights permission to window service. So, Very Important part of the solution is: Impersonation. You need to impersonate the application/part of the code with the User Credentials which is having proper rights and permission to access the window service.

If you try to access window service it will generate "access denied" error.

The alternatives are: You can either impersonate whole application by adding Identity tag in web.cofig as:
        <identity impersonate="true" userName="" password=""/>

This tag will be under System.Web section. the "userName" and "password" will be the credentials of the user which is having rights to access the window service. But, this would not be a wise and good solution; because you may not impersonate whole website like this just to have access window service (which is going to be a small part of code).

Second alternative is: Only impersonate part of code where you need to access the window service to start or stop it. I opted this one. But, to be fair; I am really unaware of the code part for impersonation. So, I just googled it and injected the code in my solution in a separate class file named as "Impersonate" with required static methods. In Impersonate class; impersonateValidUser() is the method to impersonate a part of code and undoImpersonation() is the method to undo the impersonation. Below is one example:

 Start/Stop Window Service from ASP.NET page

 You need to provide domain name (which is "." if you are working on your home computer), username and password of appropriate user to impersonate.

[4] Here, it is very important to note that: You need to have to store the Access Credentials (username and password) which you are going to user for impersonation; to some secured and encrypted format. I have used Machinekey Encryption to store the value encrypted value inside database.

[5] So now; The real part is to start or stop a window service. You are almost done; because ServiceController class has simple Start() and Stop() methods to start or stop a window service. A ServiceController class has parametrized constructor that takes name of the service as parameter.

Code to Start the window service:

Start/Stop Window Service from ASP.NET page 

Code to Stop the window service:

Start/Stop Window Service from ASP.NET page 

Isn't that too easy! ServiceController made it easy :) I have attached a working example with this post here to start/stop "SQLBrowser" service where you need to provide proper credentials who have permission to access to window service.

Start/Stop Window Service from ASP.NET page 

hope it would helps./.


I found this something interesting while wandering over community which I would like to share. The post is whole about: DBML is not considering the table field's "Default value or Binding" setting which is a NotNull. I mean the field which can not be null but having default value set needs to be set IsDbGenerated = true in DBML file explicitly.

Consider this situation: There is a simple tblEmployee table with below structure:

tblEmployee Image 

The fields are simple. EmployeeID is a Primary Key with Identity Specification = True with Identity Seed = 1 to autogenerate numeric value for this field. EmployeeName and their EmailAddress to store in rest of 2 fields. And the last one is "DateAdded" with DateTime datatype which doesn't allow NULL but having Default Value/Binding with "GetDate()". That means if we don't pass any value to this field then SQL will insert current date in "DateAdded" field.

So, I start with a new website, add a DBML file and dropped the said table to generate LINQ To SQL context class. Finally, I write a simple code snippet to insert data into the tblEmployee table; BUT, I am not passing any value to "DateAdded" field. Because I am considering SQL Server's "Default Value or Binding (GetDate())" setting to this field and understand that SQL will insert current date to this field.

        using (TestDatabaseDataContext context = new TestDatabaseDataContext())
        {
            tblEmployee tblEmpObjet = new tblEmployee();
            tblEmpObjet.EmployeeName = "KaushaL";
            tblEmpObjet.EmployeeEmailAddress = "kaushal@emaildomain.com";
            context.tblEmployees.InsertOnSubmit(tblEmpObjet);
            context.SubmitChanges();
        }

Here comes the twist when application give me below error:

Error Image 

This is something not expecting! From the error it clearly depicts that LINQ is passing NULL value to "DateAdded" Field while according to my understanding it should respect Sql Server's "Default value or Binding" setting for this field. A bit googling and I found very interesting related to this problem.

When we set Primary Key to any field with "Identity Specification" Property set to true; DBML set one important property "IsDbGenerated=true" for this field.

IsDbGenerated=True Setting in Dbml.Designer.cs file 

BUT, when we set "Default Value or Biding" property for some field; we need to explicitly tell the DBML/LINQ to let it know that this field is having default binding at DB side that needs to be respected if I don't pass any value. So, the solution is: You need to explicitly set "IsDbGenerated=true" for such field to tell the LINQ that the field is having default value or binding at Sql Server side so, please don't worry if i don't pass any value for it.

You can select the field and set this property from property window in DBML Designer file or write the property in DBML.Designer.cs file directly.

Field with Default Value or Binding needs to be set IsDbGenerated = true in DBML file

 I have attached a working example with required table script with this post here. I hope this would be helpful for someone hunting for the same. Happy Discovery!


I got to answer a simple question over community forums.

Consider this: Suppose you are developing a webpage with few input controls and a submit button. You have placed some server validator controls like RequiredFieldValidator to validate the inputs entered by the user. Once user fill-in all the details and try to submit the page via button click you want to alert/confirm the submission like "Are you sure to modify above details?". You will consider to use javascript on click of the button.

Everything seems simple and you are almost done. BUT, when you run the page; you will see that Javascript alert/confirm box is executing first before server validators try to validate the input controls! Well, this is expected behaviour. BUT, this is not you want. Then?

The simple answer is: Call Page_ClientValidate() in javascript where you are alerting the submission. Below is the javascript example:

    <script type="text/javascript" language="javascript">
        function ValidateAllValidationGroups() {
            if (Page_ClientValidate()) {
                return confirm("Are you sure to modify above details?");
            }
        }
    </script>

Page_ClientValidate() function tests for all server validators and return bool value depends on whether the page meets defined validation criteria or not. In above example, confirm alert will only popup up if Page_ClientValidate() returns true (if all validations satisfy). You can also specify ValidationGroup inside this function as Page_ClientValidate('ValidationGroup1') to only validate a specific group of validation in your page.

        function ValidateSpecificValidationGroup() {
            if (Page_ClientValidate('ValidationGroup1')) {
                return confirm("Are you sure to modify above details?");
            }
        }

I have attached a sample example with this post here demonstrating both above cases. Hope it helps./.


This is something that might be annoying or irritating for end user. Obviously, It's impossible to prevent end user from closing the/any browser. Just think of this if it becomes possible!!!. That will be a horrible web world where everytime you will be attacked by sites and they will not allow to close your browser until you confirm your shopping cart and do the payment. LOL:) You need to open the task manager and might have to kill the running browser exe processes.

Anyways; Jokes apart, but I have one situation where I need to alert/confirm from the user in any anyway when they try to close the browser or change the url.

Think of this: You are creating a single page intranet asp.net application where your employee can enter/select their TDS/Investment Declarations and you wish to at-least ALERT/CONFIRM them if they are attempting to:
[1] Close the Browser
[2] Close the Browser Tab
[3] Attempt to go some other site by Changing the url
without completing/freezing their declaration.

So, Finally requirement is clear. I need to alert/confirm the user what he is going to do on above bulleted events. I am going to use window.onbeforeunload event to set the javascript confirm alert box to appear.

    <script language="JavaScript" type="text/javascript">
        window.onbeforeunload = confirmExit;
        function confirmExit() {
            return "You are about to exit the system before freezing your declaration! If you leave now and never return to freeze your declaration; then they will not go into effect and you may lose tax deduction, Are you sure you want to leave now?";
        }
    </script>

See! you are halfway done!. So, every time browser unloads the page, above confirm alert causes to appear on front of user like below:

User is trying to leave! Set confirm alert on browser(tab) close event!!

By saying here "every time browser unloads the page"; I mean to say that whenever page loads or postback happens the browser onbeforeunload event will be executed. So, event a button submit or a link submit which causes page to postback would tend to execute the browser onbeforeunload event to fire!

So, now the hurdle is how can we prevent the alert "Not to show when page is being postback" via any button/link submit? Answer is JQuery :)

Idea is, you just need to set the script reference src to jQuery library and Set the window.onbeforeunload event to null when any input/link causes a page to postback.

Below will be the complete code:

<head runat="server">
    <title></title>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script language="JavaScript" type="text/javascript">
        window.onbeforeunload = confirmExit;
        function confirmExit() {
            return "You are about to exit the system before freezing your declaration! If you leave now and never return to freeze your declaration; then they will not go into effect and you may lose tax deduction, Are you sure you want to leave now?";
        }
        $(function() {
            $("a").click(function() {
                window.onbeforeunload = null;
            });
            $("input").click(function() {
                window.onbeforeunload = null;
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div></div>
    </form>
</body>
</html>


So, By this post I have tried to set the confirm alert if user try to close the browser/tab or try leave the site by changing the url. I have attached a working example with this post here. I hope someone might find it helpful.

EDIT [26-February-2011]: I would like to edit this post here. I missed out to write that any control event that may cause a postback needs to be checked and set window.onbeforeunload = null; like I have set for Button Click or Hyperlink Click.

For Example, IF you have a  Select/DropDownList control which is causing a postback then you need to set window.onbeforeunload = null; on click of "select" as below:

             $("select").click(function() {
                window.onbeforeunload = null;
            });


In this post; I am going little offbeat this time. We all use skype for professional contacts. We create categories to manage our contacts. We create chat groups/Conversation for a group discussion/chat. Whenever a new instant message come, skype gives instant popup notification at the bottom right corner near taskbar. This just like any other messanger.

Sometimes, you would not like to get unwanted notification popup for the discussion on which you are not interested on. Don't worry! You don't need to leave the conversation becase the group/friends are important for you. :) There is one setting related to this in skype where you can set some words in which you are interested on which you want skype to give notification popup if any instant message by any group member contains any of those words.

Below Image shows the setting popup message where you need to enter the preferred words followed by space

 

 

So, finally :) I will only get popup notification if any of my friends write message which contains any of above words in it. Enjoy your conversation!

At end, I also want to conclude that the similar setting is available for single contact conversation window also.

In this blog entry, I am making a small note of ?? Operator. I think many of you may already have idea on this. Sometimes, it happens with me that I come across some basic things which I think I should be aware of from my academic or fresher level. ?? is one of them :)

So, The scene how I came across to find for ?? operator is: I was thinking of modifying a field of a table design which was not nullable and I needed to  make it nullable with -1 as default value in Sql Server. But, then what should be done for previous records which already have NULL stored in them. First, I thought to manually run an update query to make NULL values to -1. But, I somehow don't like the idea to be comfortable via hurting the existing data in the table. So? I thought like we have ISNULL() and COALESC() functions in Sql Server to manage and replace with NULL values. I googled to find any equivalent in C#. And There it is !!!!

?? Operator is called null-coalescing operator and its is used to define a default value for NULL result or Nullable types that you may arise in your code.

Here is one simple example in above case:
Int64? NullableFieldInfoFromDb = //--some value which can be null
if((NullableFieldInfoFromDb ?? -1) == -1)
    //--some code to follow

see here! I dont have to bother for previous NULL vlues which are already there in the database for this field because IF the code came across the NULL value then ?? Operator will replace it with -1 value. This way I didnt have to check/test it for both NULL and -1 values in if(...) condition.

Second is one interesting situation when I needed it.
I need to implement one validation check that user should not be able to enter/input duplicate family members via UI provided to them. Here only option/way to put such type of validation check in my situation is:
Check for all these fields: Suffix + FirstName + MiddleName + LastName; against the user input. But, here Suffix and MiddleName fields are Nullable fields which can create problem/exception if I directly use them to match in where condition in a LINQ Query.

So, below is the RIGHT Query which helped me to validate duplicate family members:

bool isFamilyMemberExists =
    (from x in context.FamilyRecords
     where (x.Suffix ?? string.Empty).Trim().ToLower().Equals(txtSuffixField.Text.Trim().ToLower()) &&
     x.FirstName.ToLower().Equals(txtFirstNameField.Text.Trim().ToLower()) &&
     (x.MiddleName ?? string.Empty).Trim().ToLower().Equals(txtMiddleNameField.Text.Trim().ToLower()) &&
     x.LastName.ToLower().Equals(txtLastNameField.Text.Trim().ToLower()) &&
     (x.Relationship ?? string.Empty).Trim().ToLower().Equals(cmbRelationCodeField.SelectedValue.ToLower())
     select x.FamilyRecordID).Any();
if (isFamilyMemberExists)
    //-- Raise Error "The Member is already exists.";


What I did in above Query is use ?? Operator to replace NULL values with "" empty string so even NULL values in the data for suffix and Relationship field would not cause any exception.

So :) now I am aware of NULL-Coalescing C# Operator equivalent to ISNULL() and COALESC() functionalities in Sql Server. I still hope that many things will come that will feel to me similarly - "I should have already known about this thing earlier!!". But, anyways I am happy to know someting late then to unaware totally.

Here is the MSDN link for NULL-Coalesc Operator: ?? Operator (C# Reference) And here is another link on a good use of this operator while working with LINQ to SQL: The C# ?? null coalescing operator (and using it with LINQ) by ScottGu. I came across this nice example while googling for ??/such functionality.

hope it helps./.

This blog entry is in continuation with my first post on Part 1: LINQ Tips & Tricks [Things to get you started efficiently]

Continuing to share some other important tips that you can take care of while developing with LINQ.

[9] Loading Options while working with tables in Relationships

You always need to struggle for performance as a LINQ Developer; perhaps because to understand better how internal mechanism works.

using (BEDataContext context = new BEDataContext())
{
var customers = from cust in context.Customers
select cust;
foreach (var customer in customer)
Response.Write(customer.CustomerAddresses.Count().ToString());
}

 

In above example, you will see in Sql Server Profiler that for each customer one query will be executed additional each times to get the total addresses count for that customer when you enumerates in foreach loop. Now, consider below re-written snippet:

using (BEDataContext context = new BEDataContext())
{
var customers = from cust in context.Customers
select cust;
DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Customers>(A => A.CustomerAddresses);
context.LoadOptions = dataLoadOptions;
foreach (var customer in customer)
Response.Write(customer.CustomerAddresses.Count().ToString());
}

Simply in above example, with DataLoadingOptions we are infect just telling LINQ Query engine that while it fetches the Customer data; also fetch associated CustomerAddresses table record count for that particular Customer. The benefit is; only ONE query will be executed to get the final result.

[10] Overriding Database Modification Statements

If you have been thinking that using LINQ to SQL in your environment is not possible, perhaps because of requirements to use stored procedures for all modifications to the database, then you would be interested in knowing that the actual code that gets called to make the updates, including inserts and deletes, can be overridden.

Overriding the code called to insert, update, and delete is as simple as defining the appropriately named partial method with the appropriate signature. When you override this way, the DataContext change processor will call your partial method implementation for the database update, insert, or delete.

Example:

Think of having Northwind database dbml context class, and then partial class can be created as:

public partial class BEDataContext : System.Data.Linq.DataContext
{
partial void InsertPerson(Person instance)
{
Console.WriteLine("Insert override method called for Person {0}.", instance.FirstName);
}
partial void UpdatePerson(Person instance)
{
Console.WriteLine("Update override method was called for Person {0}.", instance.FirstName);
}
partial void DeletePerson(Person instance)
{
Console.WriteLine("Delete override method was called for Person {0}.", instance.FirstName);
}
}

 

Notice that the signature of the partial methods are [ACTION][EntityName] where ACTION is INSERT | UPDATE | DELETE and EntityName is “Person”. Once you call SubmitChanges() method then these partial methods will be called. IF you want default behavior to occur then you can simply call this.ExecuteDynamicInsert(Person instance), ExecuteDynamicUpdate(Person instance) and ExecuteDynamicDelete(Person instance) respectively for insert, update and delete. Please note that here it is developer’s responsibility to handle concurrency conflicts.

[11] Proper usage of Translate<T> method

There are some limitations I faced with LINQ to SQL. Probably it’s possible that I am unaware of the proper method but you will find over the net that it’s a common problem LINQ developer faced mostly with Dynamic Queries which are executed with “exec” statement in Stored Procedures. So, the problem is regarding- Stored Procedure having Dynamic “Select” Queries. When you try to drop a Stored Procedure (which contains Dynamic Sql Query or Queries or having Temporary tables) from Solution Explorer to dbml file it’s quite possible that instead of generating correct return type for the method it generates “int” as the return type of that method.

What should be done in this case then? There are alternatives. One of which is using Translate<T> method. Translate<T> is similar to ExetureQuery method. The method actually translates the query results in to sequence of objects. The difference is- we pass Sql statement string as parameter in ExecuteQuery method while in Translate<T> we pass System.Data.Common.DbDataReader like SqlDataReader.

So, the Question is how this method would help to generate correct sequence of object while the Stored Procedure contains Dynamic Select Query? The idea is you can simply create and execute SqlCommand for that Stored Procedure and initialize SqlDataReader with ExecuteReader() method which you can further pass to Translate<T> method to have correct result.

Example:

using(SqlConnection sqlCn = new SqlConnection(ConfigurationManager.ConnectionStrings["NWind"].ConnectionString))
{
sqlCn.Open();
SqlCommand sqlCmd = new SqlCommand("usp_DynamicSelectQuerySP", sqlCn);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
using (NWindDataContext context = new NWindDataContext())
IEnumerable<Customer> custs = context.Translate<Customer>(sqlReader);
foreach (Customer c in custs)
Console.WriteLine("ID = {0} : Name = {1} : Contact = {2}", c.CustomerID, c.CompanyName, c.ContactName);
sqlCn.Close();
}

 

Another situational usage of Translate<T> method is for integrating LINQ to SQL code into existing ADO.NET code.

[12] Stored Procedures return type with Dynamic Sql or Temporary tables

This is regarding the possible problem/situation I already talked about in previous point. Working with the Stored Procedure along with; LINQ to SQL dbml need a way for figuring out what will be the return type of the method created by that stored procedure. To do this without actually running the actual stored procedure; it uses the SET FMTONLY command set to ON so that SQL Server can just parse the stored procedure for correct return type. But, this parsing does not extend or generate proper return types if there are any Dynamic Sql or temporary tables being used. So you must change the return type from the scalar integer to known type you want it to be. What happening is, when the stored procedure is dragged and dropped on the DBML designer, Visual Studio is generating wrong signature for the stored procedure return typ. That is, instead of returning a result set as output, an integer value is set as return type.

So, finally here is the alternative when correct return type is not being generated in LINQ to SQL dbml designer file.

Hack/possible solution is:

  • Delete the stored procedure method from dbml file as well as drop it from database. Create a dummy stored procedure with the similar signatures, parameters (if any), output fields (if any) and select fields that Dynamic Sql consists of. This can be a simple select statement without any panic or conditions; a simplified version of the same SP.
  • Once you create it; drag & drop it on dbml and you notice that dbml designer now have correct return type for the method just because now the dummy SP doesn’t have dynamic Sql. That’s it.
  • Now you can remove/alter the dummy SP with the actual one that contains Dynamic Sql.

[13] Setting DataContext.ObjectTrackingEnabled Property

ObjectTrackingEnabled Property tells the LINQ to SQL to track or not to track the original value and object identity for the DataContext. We can understand that tracking the original values would be only requiring when you are inseting, updating or deleting the records (DML operations) and certainly not at the time of retrieval or simple at the time of selecting the records. That means, we do not need to bear the heavy cost of object tracking service. So, if we set it off/false then it improves performance at retrieval time, because there are fewer items to track.

Example:

using (NWindDataContext context = new NWindDataContext())
{
context.ObjectTrackingEnabled = false;
}

Here is one exception point to be noted is that: Deferred LINQ Queries require object tracking to be enabled true.

[14] Try to separate DataContext dbml class

This might not be possible in almost cases but you can think of separating database objects as a single unit of work and create separate DataContext classes. Since we consider DataContext dbml class as a whole database and not as a single unit of work/module we used to put all the tables, methods in one DataContext class only. Separating DataContext based on workspace would minimize in-memory cost of those database objects as well as object tracking cost would be minimized.

[15] UpdateCheck Property usage (Concurrency Check)

LINQ to SQL supports Concurrency Check with sql timestamp column. The property name is “UpdateCheck” for each field of the database object. You can turn this off, if it’s not required to improve the performance. To access/change it, open the dbml file select the table object’s fields for which you don’t want to have UpdateCheck and press F4 to open the property dialog box. You will find last property option “UpdateCheck” with possible options: “Never”, “Always” and “When Changed” with default “Always” option.

[16] Only fetch records that are required

Take a simple example of binding a gridview. You are paginating the records as usual to any application then consider using powerful LINQ to SQL standard operators/methods like Take & Skip.

Example:

public List<Employee> GetEmployee(int PageIndex, int PageSize)
{
using (NwindDataContext context = new NwindDataContext ())
{
return context. Employee
.Take< Employee >(PageSize)
.Skip< Employee >(PageIndex * PageSize)
.ToList< Employee >();
}
}

hope the tips would help./.

Reference: Apress: Pro LINQ: Language Integrated Query in C# 2010

more to come on EF & LINQ.

While my development with LINQ I got around some helps, links, small tips and tricks which makes life much easier, improves query formulation capabilities and speedup the program execute performance. Here I am sharing some of the tips I found as a LINQ Developer.

[1] Use the var Keyword When Confused

Use var keyword as return type especially when you are capturing sequence of anonymous classes. For example, joining of 2 tables and retrieving a sequence of records containing (some/few) fields of both the tables. I appreciate the developers who understand and know exactly what data type is contained in the sequence they are retrieving. But, anyhow you get stuck and don’t know the sequence IEnumerable<T> holds what data type T; then var is the good choice.

[2] Use the Cast or OfType Operators for Legacy Collections

You notice that LINQ standard operators and methods always been called only on the type of collections/sequence which are implementing IEnumerable <T> interface. Something trivial to know that none of the legacy Collection types which are inside System.Collection namespace implements IEnumerable <T> interface. Then how would you use LINQ operators and methods against them? The answer is: Cast and OfType LINQ operators.

//--Cast Example:
//--create a legacy collection of type ArrayList.
ArrayList nameList = new ArrayList();
nameList.Add("Kaushal");
nameList.Add("Pooja");
nameList.Add("Naman");

IEnumerable<string> firstnames = nameList.Cast<string>().Where(n => n.Length > 5);
foreach (string name in firstnames)
Response.Write(name);


//--OfType Example:
//--create a legacy collection of type ArrayList.
ArrayList nameList = new ArrayList();
nameList.Add("Kaushal");
nameList.Add("Pooja");
nameList.Add("Naman");

IEnumerable<string> firstnames = nameList.OfType<string>().Where(n => n.Length > 5);
foreach (string name in names)
Response.Write(name);

Both will result in “Kaushal” here.

[3] Don’t Assume a Query Is Bug-Free

Check out this example:

var names =
from fullname in person
where fullname.EndsWith("Parik")
select fullname;
foreach (var name in names)
Console.WriteLine(name);

By looking at the above example; it appears that query execution is occurring just when names variable of type var is initialized, but that is not the case. The reason is LINQ queries are often “deferred” and not executed when it appears to be executing when you are calling them. Because “Select” and “Where” statements are deferred operators, above query will not be executed until you enumerate it. The query is merely being declared, or defined, but not performed in the very first statement of above example. Query execution will happen when foreach statement is executed. So, finally we can say that above query that we have written is “deferred”! So, keep twice watch on your queries, they might be culprit for slow performance or internal exception.

[4] Take Advantage of Deferred Query

Now as we are families that Deferred Queries don’t execute until you enumerate them. Ultimately Deferred Query returns an IEnumerable<T> can be enumerated over, time and time again, obtaining the latest data from the data source. You don’t need to actually call or, as we earlier pointed out, declare the query again.

[5] Use the DataContext Log

This is something similar with using “Sql Server Profiler” tool we are using when working with our database to debug the query execution. You can always use “SQL Server Profiler” to view the Sql query generated by LINQ, but there is a DataContext.Log Property that you can assign to a TextWriter to view the generated Sql query. Remember that your LINQ DataContext class inherits from System.Data.Linq.DataContext, which means LINQ DataContext class is already having some pre-defined in-built functionality like this Log property.

using (NorthwindDataContext context = new NorthwindDataContext())
{
context.Log = new DebuggerWriter();

Customer customer = context.Customers.Single<Customer>
(c => c.CustomerID.Equals("KPN1"));
}

[6 ] Always Consume DataContext Class object inside using(…) statement

The DataContext dbml class implements IDisposable interface; so, its always good practice to declare and use the DataContext class inside using(…) scope sothat object will be disposed immediately after the defined scope. This is something looks a minor thing but later on in a heavy database operation related application you may end up with “Maximum Connection Pooling reached” error if DataContext objects don’t disposed correctly.

Example:

using (NWindDataContext context = new NWindDataContext())
{
var fullnames = from names in context.Persons
where names.FirstName.ToLower().EndsWith("parik")
select names;
//--further code
}

[7] Use the LINQ Forum

Got stuck somewhere? Don’t forget that is a community forum dedicated to LINQ at MSDN com (http://www.linqdev.com). This community forum is monitored by Microsoft developers, and you will find a wealth of knowledgeable resources and threads there.

[8 ] Use tool like LinqPad

The success behind a LINQ application that you develop lies behind the performance of the query that you formulate. You can use any third party tool like I prefer to use LINQPad (by Joseph Albahari) while my development with LINQ. Actually, quick since a long time after I got to know about this tool and I was impressed so much that I thought to why not I get aware something about such nice and intelligent tool before. Life would have become easier!

hope the tips would help./.

Reference: Apress: Pro LINQ: Language Integrated Query in C# 2010

more to come on EF & LINQ.

This is one of my posts based on LINQ subject on which I gratefully able to work a lot since last one and half year and I am hoping for myself to have some of good posts on EF & LINQ. In this post, I am going a bit theoretical here.

As the name implies, LINQ is all about querying for the data and retrieving the resultant sequence of the same. Queries which return set of matching objects or subset of fields of matching an object or set of objects. The result or the return set of object by the LINQ is called “sequence”. This “sequence” generally be of type IEnumerable <T> where T is the data type of the object stored in the sequence. For example, if you have a sequence of integers, they would be stored in a variable of type IEnumerable<int>.


LINQ to Objects
LINQ to Objects is the API dedicated to working with querying objects, arrays and in-memory data collections. Example is, querying a string Array.

Example:
string[] greetings = {"Hi Kaushal Parik", "Hi Pooja Parik", "Hi Naman Parik"};
var items =
    from s in greetings
    where s.StartsWith("Naman")
    select s;

foreach (var item in items)
    Console.WriteLine(item);

Result will be: Hi Naman Parik


LINQ to Dataset
LINQ to Dataset is the name given to the LINQ API for Datasets. LINQ to Dataset is the faster and easier way to query cached data in Datasets. This is specifically useful when we need to query on consolidated data from one of more data sources. LINQ to Dataset doesn’t mean to replace ADP.NET 2.0 but its build/extended upon ADO.NET 2.0 architecture. So, existing ADO.NET 2.0 code will continue to run functionally correct in a LINQ to Dataset application.

Example:
DataSet ds = new DataSet();
var employees = from e in ds.Tables[0].AsEnumerable()
                select new
                {
                    eid = e.Field<string>("EmployeeID"),
                    ename = e.Field<string>("FullName"),
                    esalary = e.Field<string>("Salary")
                };


LINQ to SQL
LINQ to SQL is the name given to the IQueryable<T> API that allows LINQ queries to work with Microsoft’s SQL Server database. This requires you to have reference of the System.Data.Linq dll assembly in your project.

Example:
var customers =
    from c in dbContext.Customers
    where c.City.Equals("Ahmedabad")
    select c;

foreach (var cust in custs)
    Console.WriteLine("{0}", cust.CompanyName);


LINQ to XML
LINQ to XML is the name given to the LINQ API dedicated to working with XML. This requires you to have reference of the System.Xml.Linq dll assembly in your project

Example:
using System;
using System.Linq;
using System.Xml.Linq;

XElement customers = XElement.Parse(
    @"<customers>
        <customer>
            <id>1</id>
            <name>kaushal parik</name>
        </customer>
        <customer>
            <id>2</id>
            <name>Pooja parik</name>
        </customer>
        <customer>
            <id>3</id>
            <name>Naman parik</name>
        </customer>
    </customers>");

var names =
    from cust in customers.Elements("customer")
    where (string) book.Element("author") == "Joe Rattz"
    select cust.Element("name");

foreach(var name in names)
    Console.WriteLine(name.Value);


LINQ to Entities
LINQ to Entities is the name given to the LINQ API that is used to interface with a database. LINQ to Entities separates physical database and the entity object model by injecting logical mapping in between them which simply results in greater flexibility.

hope this helps./.

more to come on EF & Linq.

Somasegar has announced on his blog entry that Visual Studio 2010 Service Pack 1 Beta is available and now ready for download!

MVP Groups and MSDN subscribers can download the beta immediately with general availability on December 9,2010. It is even exciting to know that SP 1 Beta comes with a “go live” license which means you can start using the product for production related work (but I still wonder why they released it as "Beta" then!).

The focus is on improving the overall experience in a few important areas, such as unit testing, support for GPU acceleration in C++ applications, and offline help. Some of the improvements that come with Service Pack Beta 1:

  •     Help Viewer
  •     .NET 3.5 Unit Testing for
  •     IntelliTrack support for 64bit and SharePoint projects
  •     Performance Wizard for Silverlight
  •     Silverlight Tools for Visual Studio 2010 4
  •     VB runtime compiler switch

Detailed information about the subject as well as download links for subscribers and for general developers can be found at Jason zander blog.

Any issues if you may arise with it can be submitted at Microsoft Connect. Some minor issues found here and here regarding download and installation.

UPDATE [10-December-2010]: Scott Hanselman blogged on SP1 Beta Release yesterday which contains informative updates on "whats new" and "updation/bug fixes" details concentrated in this release. Check out here: Visual Studio Explosion! - VS2010 SP1 *BETA* Released and Context

Update: The article has been selected as "Article of the day" on 3rd Feb 2011 at official asp.net (http://www.asp.net) site

Recently I came across a very interesting situation thru that I came to know that the order in which the codeSubDirectories defined is very important.

We define codeSubDirectories section inside <Compilation /> section of web.config file in any asp.net application specially when we are having Class files in different languagues (C# & VB.NET) at the same time inside App_Code folder. So, the practice is to create different language folders inside App_Code and put the appropriate language class files inside those folders and define those folder names in <codeSubDirectories />  section.

Another possible situation is- when you want to seperate App_Code class files according to Modules of your application; You separete class files in different folder and put them in appropriate namespaces.

Below is one example on how you define codeSubDirectories section; if suppose for example, you having 3 folder in your application's App_Code folder namely mySubDir1, mySubDir2 and mySubDir3 respectively.
<compilation>
   <codeSubDirectories>
     <add directoryName="mySubDir1"/>
     <add directoryName="mySubDir2"/>
     <add directoryName="mySubDir3"/>
   </codeSubDirectories>
</compilation>

According to MSDN documentation: <codeSubDirectories /> Defines an ordered collection of subdirectories that contains files to compile at run time. Subdirectory names are relative to the App_Code directory. The build order is inferred from the top-down order of the codeSubDirectories collection. The App_Code directory is built last. However, there are no build order dependencies, which means that the build order is not significant.
I think that what is documented above is somewhat misleading or may be I am mis-interpreting it because the documentation says "the build order is not significant".

Anyways, the problem that I was facing is: I was not able to access the namespace/class defined in some other folder in some fix pattern. A google search helped me to know: If we take above example. It's not just a list but its an "Ordered" list. That means if you try to acccess Namespaces which are defined inside mySubDir2,mySubDir3 in mySubDir1 then you won't able to do that. The reason is mySubDir1 is defined very first in the CodeSubDirectories list.

Finally, conclusion in above example is:
[1] Classes inside mySubDir1: you won't be able to access class/namespaces which are defined inside mySubDir2 and mySubDir3. Reason: mySubDir1 is first in CodeSubDirectories order and won't recognize the other classes which are further defined in other directoires.
[2] Classes inside mySubDir2: you will be able to access class/namespaces which are defined inside mySubDir1 and mySubDir2 but you wont be able to access class/namespaces which are defined inside mySubDir3. Reason is mySubDir3 is defined as last inm order.
[3] Classes inside mysubDir3: you will be able to access ALL class/namespaces which are defined in mySuibdir1, mySuibdir2 and mySuibdir3. Reason is because mySubDir is very last in the codeSubDirectories order.

Isn't that strange! This was a new thing to know for me :)
So, when you come around a situation when you need to use mySubDir3's Classes and namespaces inside mySubDir1 classes, then best solution to follow WAP model OR create separate dll class libraries.

Below is the graphical representation of what I am saying in this blog entry:

codeSubDirectories Element in web.config file (Order does matters!)

hope it helps./.

I prefer to use fiddler which is an awsome tool for tracing up the http trafic, to test the performance script result OR to generate the Visual Basic web test script for performance testing. While working on one of my live site it helped me a lot as a web debugger. BUT, unfortunately when I tried to test my localsite (http://localhost/mySite) then fiddler didn't show me http traffic/session of my local sites. Just after investing few minutes on google I came to know about the fix of adding a "dot" in front of localhost! and guess, it worked!! Now, fiddler was showing me localhost site's traffic result.

The idea is: instead of browsing your localhost site as:

http://localhost/mySite

Browse the site with a "dot" infront of localhost as:

http://localhost./mySite  OR  http://127.0.0.1./mySite (notice the "dot" that I have written in there in the address)

That's It! and fiddler started crawling my localhost site's session. The small trick would help people who just consider this tool a junk on first trial for their localhost sites.The root cause of this problem is: Internet Explorer and the .NET Framework are bydefault set not to send requests for Localhost through any proxies, and as a proxy, Fiddler will not receive such traffic.

You can also try another work-a-round by checking off a checkbox which says "Bypass proxy server for local addresses" which can be found at Internet Exploerer > Tools menu > Internet Options > Connections > Lan Settings > "Bypass proxy server for local addresses" Checkbox.

The issue has been documeted here as a known issue if anybody interested.

Happy Hunting!

For those developers who are looking forward for Silverlight 5; there is one great new that: at the Silverlight FireStarter event MS unveiled the next release of Silverlight (that is version 5 beta); the next version of its rich Internet platform and previewed key features of the upcoming beta technology at its Silverlight Firestarter educational event for developers. The Sikverlight beta 5 version is having significantly added new features and other media capabilities, which make easier for developers to create premium media experiences and deliver RIA across browsers, desktops and devices.

For more information on Announcing Silverlight 5; Check out ScottGu's Blog entry here: Announcing Silverlight 5

And here is the detailed list of new features and enhancements announced in this version: New Features Announced for Silverlight 5 Beta

friends, I didn't remember about the real source where i got it but I found one handy sheet for common operation in Linq To SQL.

I thought you guys will find it useful too. I have also attached PDF file with this blog entry which contains all the examples ni both C# and VB.NET.

Hope it helps./.

Linq To SQL Sheet

More Posts Next page »