Sunday, December 25, 2011

ASP.NET AJAX and Sys.Debug

ASP.NET includes tracing functionality that can be used to track different issues in an application. It can be used to easily inspect errors that have occurred, check sessions IDs, cookie values, ViewState size, server variables plus a lot more.

The ASP.NET AJAX client script library also includes basic tracing functionality that can be used to write trace messages to a console window (that show up while debugging) or to the actual page. The client-side tracing functionality can also be used to dump values contained within a JSON object so that they are easily viewed. All of this client-side tracing functionality is exposed by the Sys.Debug class. An example of using it to write a trace message to the console and dump the contents of an Album object is shown next:


Adding calls to Sys.Debug.trace() will cause the trace information to be shown in the Visual Studio .NET 2005 console window while debugging, but the trace information won't be shown in the page. In cases where you'd like to see the output of different trace statements directly in the page you can add a textArea tag and give it an id of TraceConsole :

<--textarea id="TraceConsole" -->

Monday, December 19, 2011

Permanent Redirections with Response.PermanentRedirect

To redirect a page request to another page ASP.NET ships with Response.Redirect() since the v1 that takes a string Url as the input parameter.

You will recall that this is not a permanent redirect, you know that to be able to make a permanent redirect you will have to do something like this

HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", StringUrl);

ASP.NET 4.0 now ships with a Response.PermanentRedirect() helper method that redirects the user permanently to a new page. Watch Joe’s quick hit video to see it in action.


Fortunately we don't need to wait for .NET 4.0 to have a fancy method like above, we can with the help of C# Extension methods, create a helper method today.


For example take a look at this code

public static void PermanentRedirect(this HttpResponse response, string StringUrl) {
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", StringUrl);
}

Now if you do a Response. you will see the static helper method in the intellisense.


Wednesday, December 14, 2011

Dll referencing conflict between GAC and Bin

Few days ago, I was looking a issue faced by my colleague. He was trying to retrieve some values from Mysql db, using stored procedure. The application was layer down in different projects i.e. Data Access project for database communication and so on.
When he passed collection of parameter to data access, there was a weird error popsup i.e. (cannot cast MySql.Data.MysqlParameter to MySql.Data.MysqlParameter). I was amazed to see, whats going on. I double checked that the reference was added there.
After spending some time closely, I saw a dll hell type thing i.e. the Website had Mysql dll in the bin folder as well as in GAC and the data access referred it from GAC. As a result: the dll of different versions creating problem in type casting mysqlparameter collection from one project to another. I removed the dll from bin folder so that same GAC dll would be used in both projects and it started working.
Always add the project references cleanly to avoid this type of thing. I hope this post would be useful for you guys.

Happy Coding.....

Wednesday, November 30, 2011

Using ASP.NET Session State in a Web Service

One of the most common challenges that Web developers encounter is maintaining state in the stateless world of HTTP. There have been a number of clever means used to get around the stateless issue, from reposting application data with each request, to using HTTP authentication to map requests to specific users, to using HTTP cookies to preserve the state of a series of requests. One particularly clever way of maintaining state that hides all the challenging work below is to simply use the Microsoft® ASP.NETSystem.Web.SessionState.HttpSessionState class. You can use the ASP.NET HttpSessionState class from a Web method just as you can from ASPX pages, but things work a little differently for Web methods.

For detail click here

Tuesday, November 29, 2011

Stop File Change Notification


I have added the following code in application start (Global.asax) to stop file change notifications, for root directory changes.

//FIX disable AppDomain restart when deleting subdirectory

//This code will turn off monitoring from the root website directory.

//Monitoring of Bin, App_Themes and other folders will still be operational, so updated DLLs will still auto deploy.

System.Reflection.PropertyInfo p = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

object o = p.GetValue(null, null);

System.Reflection.FieldInfo f = o.GetType().GetField("_dirMonSubdirs", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.IgnoreCase);

object monitor = f.GetValue(o);

System.Reflection.MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

m.Invoke(monitor, new object[] { });

Thank You and Happy Coding..... :)

Wednesday, November 16, 2011

Task Scheduler Class Library for .NET

Introduction

Task Scheduler is the Windows service that schedules and automatically starts programs. Windows Explorer presents a user interface to the service when you browse the %WINDIR%\TASKS folder, typically from the shortcut in the control panel. From the command line, the schtasks command and the old at command do the same. Programmers have a well-documented COM interface, but the .NET framework does not offer any wrapper for it. The present library provides that .NET wrapper.

Note: Since this library was created, Microsoft has introduced a new task scheduler (Task Scheduler 2.0) for Windows Vista. This library is a wrapper for the Task Scheduler 1.0 interface, which is still available in Vista and is compatible with Windows XP, Windows Server 2003 and Windows 2000.

The library is an expanded version of a package written by CodeProject.com member David Hall. See his article. In the original work, David demonstrated how a collection of COM interfaces could be tamed into a logical class library in the .NET style. This new version offers many improvements, including the elimination of COM memory leaks. Fixing the memory leak problem required the adoption of an incompatible class hierarchy, but, for clients in transition, the original hierarchy remains available as a kind of differently organized view of the same objects. It is deprecated, however, because of the leaks. A later section on compatibility gives more detail.

Documentation is contained in an HTML help file, MSDN-style, which is downloaded along with the library. The documentation is intended to be self-contained and sufficient for any client to use the library. MSDN documents the COM interface on which the library is based. It is worth consulting when the library's documentation lacks.

The second download contains the source code for the library and for a C# test application that also serves as sample code. The test application is a trivial command line interpreter that operates on scheduled tasks. It can easily be modified to insert whatever tests you may want to make.

This article introduces the library's class hierarchy and also describes some of the changes that were made from the original version.

Contents

Classes
Sample Code
Changes from Version 1
Compatibility with Version 1
Changes in Internals
History

Classes

The complete class hierarchy is illustrated by the following diagram, drawn to the standard David Hall set in his article. The abstract class StartableTrigger makes the hierarchy a bit more complicated than I'd like, but is included for completeness. For most purposes, clients can more simply consider the various concrete trigger classes as direct subclasses of Trigger .

Class Diagram

ScheduledTasks

A ScheduledTasks object represents the Scheduled Tasks folder on a particular computer. This may be either the local machine or a named machine on the network to which the caller has administrative privileges. In the machine's Scheduled Tasks folder, Windows keeps information for each scheduled task in a file with a *.job extension. All tasks in the folder are said to be "scheduled," regardless of whether they will actually ever run.

// Get a ScheduledTasks object for the computer named "DALLAS" ScheduledTasks st = new ScheduledTasks(@"\\DALLAS");

You use a ScheduledTasks object to access the individual tasks. Each task has a name, the same as its file name without the extension. From the ScheduledTasks object you can obtain the names of all the tasks currently scheduled. There are methods to create, open and delete tasks, all of which use the task's name.

// Get an array of all the task names string[] taskNames = st.GetTaskNames();

A ScheduledTasks object holds a COM interface. When you are finished using the object, call its Dispose()method to release the COM interface.

// Dispose the ScheduledTasks object to release COM resources. st.Dispose();

Task

A Task object represents an individual scheduled task that is open for access. Its properties determine what application the task runs and the various other items you can see in the Explorer user interface. One such property is its TriggerList, another class discussed below. After creating a Task or opening and modifying a Task, it must be saved to record the new state in its file. You can save it under its current name or you can provide a new name. Saving with a new name is like "Save As" in a Windows application: the open Task remains associated with the new name. There is no public constructor for Task. A Task can only be created by a ScheduledTasks object using itsOpen() or Create() methods.

// Open a task named "foo" from the local computer's scheduled tasks ScheduledTasks st = new ScheduledTasks(); Task t = st.OpenTask("foo");

A Task retains COM interfaces. When you are finished using a Task, call its Close() method to release the interfaces.

// Close the Task object to release COM resources. t.Close();

TriggerList

A TriggerList is a collection of Trigger objects. Every Task has a TriggerList that can be obtained from a get-only property. There are no public constructors for TriggerList. Every TriggerList is associated with aTask and is constructed along with the Task, so a TriggerList can only be obtained from its Task object.

// Get the triggers for the local task "foo". ScheduledTasks st = new ScheduledTasks(); Task t = st.OpenTask("foo"); TriggerList tl = t.Triggers;

A TriggerList becomes invalidated when its task is closed. (Further access causes an error.)

Trigger

Triggers are conditions which, when satisfied, cause a task to run. In the Explorer UI, triggers are called "schedules." There are several types of triggers and different data is appropriate for different types. Thus, theTrigger class is actually an abstract class from which an assortment of concrete classes is derived. Each concreteTrigger class has unique constructors that specify the particular type of condition it represents. To set a new trigger for a task, construct a Trigger of the appropriate variety and then add it to the task's TriggerList .

// Add a trigger to run task "foo" at 4:30 pm every day Trigger tg = new DailyTrigger(16, 30);  // hour and minute ScheduledTasks st = new ScheduledTasks(); Task t = st.OpenTask("foo"); t.Triggers.Add(tg); t.Save();

When a new Trigger is created, it is not associated with any Task or TriggerList and is said to be unbound. An unbound Trigger does not hold any COM resources and has no special usage protocol. When a Trigger is added to a TriggerList, it is then said to be bound and it remains so unless it is removed from that collection. A boundTrigger holds a COM interface. The COM interface is released when the corresponding Task is closed, so no special care is required on the part of the client. The distinction between unbound and bound Triggers rarely comes up in client code, but the following points are the essence:

  • A Trigger can only be in one TriggerList at a time. Therefore a bound Trigger can�t be added or assigned to a TriggerList because it is already in one. To put the same Trigger in a secondTriggerList, use Clone() to create an unbound copy.
  • A bound Trigger object can�t be used after its task is closed. (Further access causes an error.)
For detail click here

Tuesday, November 15, 2011

Unable to debug The binding handle is invalid VS2005

If you are trying to debug in Visual Studio 2005 and and not able to use breakpoints and getting unable to debug - the binding handle is invalid error in VS 2005 than follow these steps to fix this error.


Go control panel of your windows OS

Double click on Administrative tools > services

Now in services window > look for Terminal Services

Right click on it ans select properties > check it's startup type > it might be disabled

Restart the service and change startup type to Automatic

This should fix your problem ...

Tuesday, October 18, 2011

Transaction deadlock and time out issue in Linq to Sql

When your database tables start accumulating thousands of rows and many users start working on the same table concurrently, SELECT queries on the tables start producing lock contentions and transaction deadlocks. This is a common problem in any high volume website. As soon as you start getting several concurrent users hitting your website that results in SELECT queries on some large table like aspnet_users table that are also being updated very frequently, you end up having one of these errors:

Transaction (Process ID ##) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Or,

Timeout Expired. The Timeout Period Elapsed Prior To Completion Of The Operation Or The Server Is Not Responding.

The solution to these problems are – use proper index on the table and use transaction isolation level Read Uncommitted or WITH (NOLOCK) in your SELECT queries. So, if you had a query like this:

SELECT * FORM aspnet_users
where ApplicationID =’xxx’ AND LoweredUserName = 'someuser'

You should end up having any of the above errors under high load. There are two ways to solve this:

SET TRANSACTION LEVEL READ UNCOMMITTED;

SELECT * FROM aspnet_Users
WHERE ApplicationID =’xxx’ AND LoweredUserName =
'someuser'

Or use the WITH (NOLOCK):

SELECT * FROM aspnet_Users WITH (NOLOCK)
WHERE ApplicationID =’xxx’ AND LoweredUserName =
'someuser'

The reason for the errors are that since aspnet_users is a high read and high write table, during read, the table is partially locked and during write, it is also locked. So, when the locks overlap on each other from several queries and especially when there’s a query that’s trying to read a large number of rows and thus locking large number of rows, some of the queries either timeout or produce deadlocks.

Linq to Sql does not produce queries with the WITH (NOLOCK) option nor does it use READ UNCOMMITTED. So, if you are using Linq to SQL queries, you are going to end up with any of these problems on production pretty soon when your site becomes highly popular.

For example, here’s a very simple query:

using (var db = new DropthingsDataContext())

{

var user = db.aspnet_Users.First();

var pages = user.Pages.ToList();

}

DropthingsDataContext is a DataContext built from Dropthings database.

When you attach SQL Profiler, you get this:





You see none of the queries have READ UNCOMMITTED or WITH (NOLOCK).

The fix is to do this:

using (var db = new DropthingsDataContext2())

{

db.Connection.Open();

db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");

var user = db.aspnet_Users.First();

var pages = user.Pages.ToList();

}

This will result in the following profiler output




As you see, both queries execute within the same connection and the isolation level is set before the queries execute. So, both queries enjoy the isolation level.

Now there’s a catch, the connection does not close. This seems to be a bug in the DataContext that when it is disposed, it does not dispose the connection it is holding onto.

In order to solve this, I have made a child class of the DropthingsDataContext namedDropthingsDataContext2 which overrides the Dispose method and closes the connection.

class DropthingsDataContext2 : DropthingsDataContext, IDisposable

{

public new void Dispose()

{

if (base.Connection != null)

if (base.Connection.State != System.Data.ConnectionState.Closed)

{

base.Connection.Close();

base.Connection.Dispose();

}

base.Dispose();

}

}

This solved the connection problem.

There you have it, no more transaction deadlock or lock contention from Linq to SQL queries. But remember, this is only to eliminate such problems when your database already has the right indexes. If you do not have the proper index, then you will end up having lock contention and query timeouts anyway.

There’s one more catch, READ UNCOMMITTED will return rows from transactions that have not completed yet. So, you might be reading rows from transactions that will rollback. Since that’s generally an exceptional scenario, you are more or less safe with uncommitted read, but not for financial applications where transaction rollback is a common scenario. In such case, go for committed read or repeatable read.

There’s another way you can achieve the same, which seems to work, that is using .NET Transactions. Here’s the code snippet:

using (var transaction = new TransactionScope(

TransactionScopeOption.RequiresNew,

new TransactionOptions()

{

IsolationLevel = IsolationLevel.ReadUncommitted,

Timeout = TimeSpan.FromSeconds(30)

}))

{

using (var db = new DropthingsDataContext())

{

var user = db.aspnet_Users.First();

var pages = user.Pages.ToList();

transaction.Complete();

}

}

Profiler shows a transaction begins and ends:









The downside is it wraps your calls in a transaction. So, you are unnecessarily creating transactions even for SELECT operations. When you do this hundred times per second on a web application, it’s a significant over head.

Some really good examples of deadlocks are given in this article.

Earn Money ! Affiliate Program
Open Directory Project at dmoz.org