Tuesday, June 15, 2004

Language portable T-SQL

I was reading a very informative article on MSDN. Thought it was worth sharing. This talks about writing Language portable T-SQL statements. Would not the idea of building globalization logic in T-SQL Stored Procedures be interesting...at least for me it is...if you are also interested...to have a look at the page...just follow this link http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsqldev/html/sqldev_06112004.asp

Fetching multiple result sets in a data reader, with command type as text.

Multiple result sets can be fectched by using 2 queries separated by a semicolon.
If multiple result sets are returned, the DataReader provides the NextResult method to iterate through the result sets in order, as shown in the following code example.
[In Visual Basic.Net]

Dim myCMD As SqlCommand = New SqlCommand("SELECT CategoryID, CategoryName FROM Categories;SELECT EmployeeID, LastName FROM Employees", nwindConn)
nwindConn.Open()

Dim myReader As SqlDataReader = myCMD.ExecuteReader()

Dim fNextResult As Boolean = True
Do Until Not fNextResult
Console.WriteLine( myReader.GetName(0) & myReader.GetName(1))

Do While myReader.Read()
Console.WriteLine(myReader.GetInt32(0) & myReader.GetString(1))
Loop

fNextResult = myReader.NextResult()
Loop

myReader.Close()
nwindConn.Close()

Role of HTTP.SYS in IIS

The Hypertext Transfer Protocol (HTTP) listener is implemented as a kernel-mode device driver named HTTP.sys. HTTP.sys is part of the networking subsystem of Windows. However, HTTP.sys is utilized as a core component of IIS 6.0.
By running HTTP.sys as a kernel-mode component, IIS 6.0 delivers the following two performance enhancements, which are not included when running HTTP listener as a user-mode component:
• By dispatching directly to the correct process from the kernel, requests are served with less context-switching overhead.
• By enabling the kernel-mode cache, requests for cached returns can be served without switching to user mode.
How HTTP.sys Works
When you create a Web site in IIS, the site is registered with HTTP.sys, which then routes Web requests to the user-mode process that is running the Web site. HTTP.sys also sends responses back to the client. Other than retrieving a stored response from its internal cache, HTTP.sys does not process the requests it receives. Therefore, no application-specific code is ever loaded into kernel mode. As a result, application-specific code bugs cannot affect kernel-mode processes or lead to system failures.
HTTP.sys provides other services that IIS uses, including the following:
• Managing Transmission Control Protocol (TCP) connections.
• Routing HTTP requests to the correct request queue.
• Caching of responses in kernel mode.
• Performing all text-based logging for the WWW service.
• Implementing Quality of Service (QoS) functionality, which includes connection limits, connection time-outs, queue-length limits, and bandwidth throttling.

The role of http.sys is to route the HTTP requests to user mode applications. But it doesn’t process the request. It also caches the server’s response.

Creating a strongly typed DataSets

Given an XML Schema that complies with the XML Schema definition language (XSD) standard, you can generate a strongly typed DataSet using the XSD.exe tool provided with the .NET Framework SDK.
The following code shows the syntax for generating a DataSet using this tool.
xsd.exe /d /l:CS XSDSchemaFileName.xsd /n:XSDSchema.Namespace
In this syntax, the /d directive tells the tool to generate a DataSet, and the /l: tells the tool what language to use (for example, C# or Visual Basic .NET). The optional /n: directive tells the tool to also generate a namespace for the DataSet called XSDSchema.Namespace. The output of the command is XSDSchemaFileName.cs, which can be compiled and used in an ADO.NET application. The generated code can be compiled as a library or a module.

How does Update Command of Data Adapter object work?

The Update method of the DataAdapter is called to resolve changes from a DataSet back to the data source. The Update method, like the Fill method, takes as arguments an instance of a DataSet, and an optional DataTable object or DataTable name. The DataSet instance is the DataSet that contains the changes that have been made, and the DataTable identifies the table from which to retrieve the changes.
When you call the Update method, the DataAdapter analyzes the changes that have been made and executes the appropriate command (INSERT, UPDATE, or DELETE). When the DataAdapter encounters a change to a DataRow, it uses the InsertCommand, UpdateCommand, or DeleteCommand to process the change. This allows you to maximize the performance of your ADO.NET application by specifying command syntax at design-time and, where possible, through the use of stored procedures. You must explicitly set the commands before calling Update. If Update is called and the appropriate command does not exist for a particular update (for example, no DeleteCommand for deleted rows), an exception will be thrown.
Command parameters can be used to specify input and output values for an SQL statement or stored procedure for each modified row in a DataSet.
If your DataTable maps to or is generated from a single database table, you can take advantage of the CommandBuilder object to automatically generate the DeleteCommand, InsertCommand, and UpdateCommand of the DataAdapter.
The Update method will resolve your changes back to the data source, however other clients may have modified data at the data source since the last time you filled the DataSet. To refresh your DataSet with current data, use the DataAdapter and Fill the DataSet again. New rows will be added to the table, and updated information will be incorporated into existing rows. The Fill method determines whether a new row will be added or an existing row will be updated by examining the primary key values of the rows in the DataSet and the rows returned by the SelectCommand. If the Fill method encounters a primary key value for a row in the DataSet that matches a primary key value from a row in the results returned by the SelectCommand, it updates the existing row with the information from the row returned by the SelectCommand and sets the RowState of the existing row to Unchanged. If a row returned by the SelectCommand has a primary key value that does not match any of the primary key values of the rows in the DataSet, the Fill method adds a new row with a RowState of Unchanged.
Note If the SelectCommand returns the results of an OUTER JOIN, the DataAdapter will not set a PrimaryKey value for the resulting DataTable. You will need to define the PrimaryKey yourself to ensure that duplicate rows are resolved correctly.

Why are Web Services Stateless ?

Web Services are not supposed to hold state between calls. Web Services address a branch of architecture which is called the Service Oriented Architecture (SOA). By definition, SOA is based on applications exposing services for other applications or users to consume. When we talk about services, we referrer to an atomic unit of consumable service. In a typical scenario, web services are implemented at a use-case level. A service Façade layer would be introduced over the business layer (sometimes over the business façade). This service façade would be exposed as the service layer (as web service calls). Each service exposed (method in your web service) is meant to be atomic – the service should take in all the details that would be required to invoke the all business functionality in the right sequence. And hence you don’t have the concepts of state sharing. You may now ask how transactions can be maintained across web service calls! Web service transactions is not yet supported – several standards are being proposed but it’s actual implementation is far off.
In conclusion,
1. You should design your web service in such a way that it does not require to share state between calls.
2. In the worst case, your application should take care of data management by persisting data in the database. State sharing should not be considered.

Technically, speaking… Because Web Services uses the stateless HTTP Protocol, Web Services by default does not support state. Yet you can do this by building additional logic in your code.

Assembly Manifests and Metadata

MetaData:
Metadata is binary information describing your program that is stored either in a common language runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is inserted into one portion of the file, while your code is converted to Microsoft intermediate language (MSIL) and inserted into another portion of the file.
Metadata stores the following information:
Description of the assembly.
Identity (name, version, culture, public key).
The types that are exported.
Other assemblies that this assembly depends on.
Security permissions needed to run.
Description of types.
Name, visibility, base class, and interfaces implemented.
Members (methods, fields, properties, events, nested types).
Attributes.
Additional descriptive elements that modify types and members.

Assembly Manifest:
Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.

Usage of ValidateRequest page attribute

<% @ Page validateRequest="True" %>
Validate Request attribute is yet another feature that Dot Net Fx 1.1 offers, to build secure enterprise applications. By default for all the ASPX pages that we design, this attribute is set to true. You can find this setting in the machine level configuration file (<%Install Root%>/Framework/V<%version#%>/CONFIG/Machine.config file), under the pages element. This would be set to true. Once this is set to true, ASP.NET scans / checks all the inputs posted back from the page / cookies / query strings for potentially malicious input. This featured can be turned off at page level by setting this attribute to false, if the application demands some kinds of inputs be allowed. Dot Net Fx 1.0 does not provide a similar feature. But the IIS URLScan ISAPI Filter does a similar job. Basically both these features help to mitigate the threat of XSS (Cross-site scripting) by rejecting potentially malicious input.

Sunday, June 13, 2004

Identifying the control that caused PostBack in ASP.NET

I was wondering, how to find out the actual control, that caused a Page submit (postback).
We can actually use the hidden __EVENTTARGET field, in the Pages request object to find out the control, that caused a post back. The following code will help...

private string GetControlThatPostedBack()
{
if(Page.IsPostBack)
{
//try to find the name of the postback control in the hidden __EVENTTARGET field
string controlName = Page.Request.Form["__EVENTTARGET"];
// if the string is not null, return the control with that name
if(controlName != null && controlName.Trim().Length > 0)
{
return Page.FindControl(controlName).ID;
}
}

//the above logic does not work for PostBack events fired by standard buttons.
//Still, we can find out the control, by looping through the Form's control collection
//and retrieving the control that submitted the page
foreach(string keyName in Page.Request.Form)
{
Control formControl = Page.FindControl(keyName);
if(formControl != null)
{
return formControl.ID;
}
}
return "";
}

Thursday, June 10, 2004

Use of HTTPOnly cookie attribute

A cookie can be marked as HTTPOnly , to indicate that the cookie is
"non-scriptable" and should not be revealed to the client application, for
security reasons. Within Windows Internet, this means that the cookie cannot
be retrieved through the InternetGetCookie function.
If Internet Explorer 6.0 SP1 detects a cookie marked HttpOnly and some
client side script code, such as JavaScript, attempts to read the cookie
(document.cookie, for example), Internet Explorer returns an empty string,
thus preventing the attack by preventing the malicious code in the XSS
attack from sending the data back to a malicious site. Of course, the cookie
is passed to and from the originating server as normal; the browser using
script code just can't read it.

Web browsers that do not support the HttpOnly cookie attribute either ignore
the cookie or ignore the attribute, which means it is still subject to XSS
attacks.

The System.Net.Cookie class does not currently support an HttpOnly property.
To add an HttpOnly attribute to the cookie, you need to use an ISAPI filter,
or if you
want a managed code solution, add the following code to your application’s
Application_EndRequest event handler in Global.asax:

protected void Application_EndRequest(Object sender, EventArgs e)
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
// Just set the HttpOnly attribute on the Forms authentication cookie
// Skip this check to set the attribute on all cookies in the collection
if (sCookie.Equals(authCookie))
{
// Force HttpOnly to be added to the cookie header
Response.Cookies[sCookie].Path += ";HttpOnly";
}
}
}

A future version of the .NET Framework is likely to have an HttpOnly
property on the Cookie class.

_________________________________________________________________
Are you a cricket freak? CDs, books, and more goodies!
http://www.msn.co.in/Shopping/CricketShop/ Available at the cricket shop!

Microsoft Caching Application Blocks

The Microsoft caching application block is very useful building block for developing enterprise .NET Applications. I found this very useful, and it reduces a great deal of coding effort. However, I found this piece of information worth sharing, so that it will be useful for other developers.

There is a FileDependency class which is used to set the cache dependency on a cached file. The as-is logic of the application block will refresh the cache every time the file is Accessed. It uses the following logic.

While an item is added to the cache, the App block, makes a note of the LastAccessTime of the shared file.
The App block has an in built File System Watcher, which will scan the file after every ‘n’ seconds, and will determine.
· If the current “LastAccessTime” of the file is greater than the value, that was determined in step 1 above.

· If yes the app block will refresh the cache.

The problem I faced here is, my application will read the file more frequently and will update the file less frequently. For example, if my application accesses the file (to read certain values) for 10 times in a day, it may update the file only once in a day. So going by the given logic of the App-Block the cache was getting refreshed for all the 10 times. The very purpose of caching was not served.


So I decided to change the code (Microsoft PAG allows us to change and recompile the code). I changed the logic of the FileDependency class, so that it will refresh the cache based on LastUpdated time rather on LastAccess time. The modified code is as below.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;

// Used for Handling Exceptions
using Microsoft.ApplicationBlocks.ExceptionManagement;

namespace Microsoft.ApplicationBlocks.Cache.Expirations
{
///
/// This class tracks a file cache dependency.
///

[Serializable]
public class FileDependency : ICacheItemExpiration, ISerializable
{
#region Private members
private string keyValue;
private string dependencyFileName;
private DateTime lastAccessedTime;
#endregion

#region Constructor
///
/// Constructor with one argument.
///

///
/// Indicates the file name of the file
///
public FileDependency( string fullFileName )
{
try
{

string path;
string fileName;
#region Throwing Argument Exception
if(Object.Equals(fullFileName, null))
{
throw new ArgumentNullException("fullFileName",
CacheResources.ResourceManager[RES_ExceptionNullFileName"]);
}
if(fullFileName.Length == 0)
{
throw(new ArgumentOutOfRangeException("fullFileName",
CacheResources.ResourceManager"RES_ExceptionEmptyFileName"]));
}
if(! File.Exists(fullFileName))
{
throw(new ArgumentException(CacheResources.
ResourceManager["RES_ExceptionInvalidFileName"],
"fullFileName"));

}

#endregion

// Validate File
FileInfo fileDependencyInfo = new FileInfo(fullFileName);
if (!fileDependencyInfo.Exists)
{
throw new FileNotFoundException();
}
// Get Path from full file name
path = Path.GetDirectoryName(fullFileName);
// Get file name from full file name
fileName = Path.GetFileName(fullFileName);
dependencyFileName = fullFileName;
//////////////////////////////////////////////////////
//Changed HERE
//////////////////////////////////////////////////////
lastAccessedTime = File.GetLastWriteTime(fullFileName);
//////////////////////////////////////////////////////
/// END OF CHANGE
//////////////////////////////////////////////////////
}
catch( Exception genException )
{
ExceptionManager.Publish( genException );
throw;
}
}
#endregion
#region ICacheItemExpiration Implementation

///
/// Event to indicate the cache item expiration.
///

public event ItemDependencyChangeEventHandler Change;
///
/// This method sets the external dependency key.
///

void ICacheItemExpiration.Key(string keyVal)
{
try
{
#region Throwing Argument Exception
if( Object.Equals(keyVal, null) )
{
throw new ArgumentNullException( "keyVal",
CacheResources.ResourceManager[
"RES_ExceptionNullKey" ] );
}
if( keyVal.Length == 0)
{
throw new ArgumentOutOfRangeException( "keyVal",
CacheResources.ResourceManager[
"RES_ExceptionEmptyKey" ] );
}
#endregion
keyValue = keyVal;
}
catch(Exception genException)
{
ExceptionManager.Publish(genException);
throw;
}
}
///
/// Specifies if the item has expired or not.
///

bool ICacheItemExpiration.HasExpired()
{
try
{
// Compare the Filedependency object's last write time
// value with the last write time value. If they are not
// equal return true, otherwise false.

//////////////////////////////////////////////////////
//Changed HERE
//////////////////////////////////////////////////////
if(DateTime.Compare(lastAccessedTime,
File.GetLastWriteTime(dependencyFileName)) != 0)
{
return true;
}
//////////////////////////////////////////////////////
/// END OF CHANGE
//////////////////////////////////////////////////////
}

catch(Exception genException)
{
ExceptionManager.Publish(genException);
}
return false;
}

///
/// Notifies that the item was recently used.
///

void ICacheItemExpiration.Notify()
{}
#endregion
#region Serialization functions
#region Public method
///
/// This method performs the serialization of members of the
/// current class.
///

///
/// A SerializationInfo object which is deserialized by the
/// formatter and then passed to current constructor
///
///
/// A StreamingContext that describes the source of the
/// serialized stream from where the Serialization object
/// is retrieved
///
[SecurityPermissionAttribute(
SecurityAction.Demand, SerializationFormatter = true)]
[SecurityPermissionAttribute(
SecurityAction.LinkDemand, SerializationFormatter = true)]
public void GetObjectData( SerializationInfo info,
StreamingContext context )
{
// Adds the file name and last accessed time
// into the SerializationInfo,
// where it is associated with the name key
info.AddValue("fileName", dependencyFileName);
info.AddValue("lastAccessedTime", lastAccessedTime);
}
#endregion

#region Constructor
///
/// This method performs the deserialization of members of the
/// current class.
///

///
/// A SerializationInfo object which is deserialized by the
/// formatter and then passed to current constructor
///
///
/// A StreamingContext that describes the source of the
/// serialized stream from where the Serialization object
/// is retrieved
///
protected FileDependency ( SerializationInfo info,
StreamingContext context )
{
try
{
// Getting the value of file name and
// last accessed time
dependencyFileName = info.GetString("fileName");
lastAccessedTime = Convert.ToDateTime(
info.GetValue("lastAccessedTime",
typeof(DateTime)));

}
catch( Exception genException )
{
ExceptionManager.Publish( genException );
}
}
#endregion
#endregion
}
}

Using the GlobalProxySelection

I was writing a web based RSS reader. Working in .NET, I wanted to write my own reader, rather than download one. Actually the reason for going in for a web based reader was, it could be used by even others who do not have .NET Fx installed. Actually, many of you who have already done this, would know how simple it is to write a RSS reader. Even I found it very simple. But when I tried running the app, I was in for some surprises. My office network is behind a firewall. So whenever I tried running the app, “The underlying connection was closed: The remote name could not be resolved” error. After some thought a little research I found out a workaround. Thought I would share this.

I added the following lines to the page load event…and lo! It started working…

IWebProxy proxyObj = new WebProxy(“IP address of the proxy server:portnumber”,true);
proxyObj.Credentials = new NetworkCredential(,,);
GlobalProxySelection.Select = proxyObj;

Hope this helps…

Tuesday, June 08, 2004

My First Posting

Test Posting :-)