Thursday, August 30, 2007

Creating XML Documents in Memory to read them into String

In the previous post on Writing XML Documents with XMLTextWriter Class, I have given sample code for writing the XML to an XML file.

But what if you wish to create the XML document in memory and use it as a string. I've also included in the sample the way to create well-formatted(indented) XML document with XmlTextWriter.

Here is the trick.

You could use MemoryStream class to create the XML document and later use it as a string.

MemoryStream memoryStreamObject = new
MemoryStream();

XmlTextWriter xmlTextWriterObject = new
XmlTextWriter(memoryStreamObject, System.Text.Encoding.UTF8);

xmlTextWriterObject.Formatting = Formatting.Indented;

xmlTextWriterObject.IndentChar = '\t';

xmlTextWriterObject.Indentation = 1;

    xmlTextWriterObject.WriteStartDocument();    

//here goes entire code to build the XML document

    xmlTextWriterObject.WriteEndDocument();

    xmlTextWriterObject.Flush(); //write the XML content to MemoryStream and close writer

memoryStreamObject.Position = 0;

    StreamReader sr = new
StreamReader(memoryStreamObject);

    String output = sr.ReadToEnd();    //reads entire content from the stream to string

//now use the string into your program

That's it. So, you could use the create string representation of XML in your .NET Application like saving it into Database or pass it onto another module.

Enjoy Xmling!!

Wednesday, August 29, 2007

Creating / Writing XML Documents with the XmlTextWriter Class

The .NET Framework provides a class designed specifically to create XML documents, the System.Xml.XmlTextWriter class. By using this class to create XML documents you don't need to worry about illegal XML characters in the text portion of the XML document, and the end code is much cleaner. In this article we'll look at using the XmlTextWriter class to create XML documents on the fly.

The Basics of the XmlTextWriter Class
The
XmlTextWriter class contains a number of methods that are useful for starting and completing an XML document and for adding elements and attributes to the XML document. The most important methods are:

  • WriteStartDocument() - you should call this method to start creating an XML document. This will create the first line in the XML document, specifying that the file is an XML document and its encoding.
  • WriteStartElement(string) - this method creates a new element in the XML document with the name specified by the string input parameter. (You can also specify a namespace as a second, optional string parameter.)
  • WriteElementString(name, text_value) - If you want to create an XML element with nothing but text content (i.e., no nested elements), you can use this method.
  • WriteAttributeString(name, value) - this method writes an attribute name and value to the current element.
  • WriteEndElement() - this method closes off the element created in the WriteStartElement(string) method call.
  • WriteEndDocument() - this method completes the writing of the XML document.
  • Close() - this method closes the underlying stream, writing the contents of the XML document to the specified file location.

To get started using the XmlTextWriter class you need to specify the file and encoding in the class's constructor. The encoding needs to be of the type System.Text.Encoding; some example encoding values are: System.Text.Encoding.ASCII, System.Text.Encoding.Unicode, and System.Text.Encoding.UTF8. Alternatively, you can specify in the constructor that the output of the XmlTextWriter class should be squirted out to a specified Stream.

Creating a Simple XML Document with XmlTextWriter
To demonstrate using the
XmlTextWriter class let's create a simple XML document, saving it to a specified file location. This XML document will contain information about the current user visiting the page, and will have this structure:

<userInfo>

<browserInfo>

<urlReferrer>URL referrer info</urlReferrer>

<userAgent>User agent referrer info</userAgent>

<userLanguages>languages info</userLanguages>

</browserInfo>

<visitInfo timeVisited="date/time the page was visited">

<ip>visitor's IP address</ip>

<rawUrl>raw URL requested</rawUrl>

</visitInfo>

</userInfo>

(This XML file structure was chosen so that it would illustrate using all of the XmlTextWriter methods discussed in the previous section.)

The code needed to create this XML document through an ASP.NET Web page is shown below:

<%@ Import Namespace="System.Xml" %>

<%@ Import Namespace="System.Text" %>

<script language="C#" runat="server">

void Page_Load(object sender, EventArgs e)

{

// Create a new XmlTextWriter instance

XmlTextWriter writer = new

XmlTextWriter(Server.MapPath("userInfo.xml"), Encoding.UTF8);


// start writing!

writer.WriteStartDocument();

writer.WriteStartElement("userInfo");


// Creating the <browserInfo> element

writer.WriteStartElement("browserInfo");


if (Request.UrlReferrer == null)

writer.WriteElementString("urlReferrer", "none");

else

writer.WriteElementString("urlReferrer",

Request.UrlReferrer.PathAndQuery);


writer.WriteElementString("userAgent", Request.UserAgent);

writer.WriteElementString("userLanguages",

String.Join(", ", Request.UserLanguages));

writer.WriteEndElement();


// Creating the <visitInfo> element

writer.WriteStartElement("visitInfo");

writer.WriteAttributeString("timeVisited", DateTime.Now.ToString());

writer.WriteElementString("ip", Request.UserHostAddress);

writer.WriteElementString("rawUrl", Request.RawUrl);

writer.WriteEndElement();


writer.WriteEndElement();

writer.WriteEndDocument();

writer.Close();

}

First, notice that the System.Xml and System.Text namespaces have been imported. The Page_Load event handler begins by creating a new XmlTextWriter instance, indicating that its content should be saved to the file userInfo.xml and that its encoding should be UTF8 (a translation of 16-bit unicode encoding into 8-bits). Note that for each element with nested elements a WriteStartElement(elementName) method is called, along with a matching WriteEndElement() after the inner content has been renderred. Furthermore, the WriteElementString(elementName, textValue) is used for those elements with just text content.

Emitting XML Content to the Browser Window Directly
The previous example demonstrates how to use the
XmlTextWriter class to create an XML document and persist it to a file. While this may be precisely what you are after, oftentimes when creating an XML document in an ASP.NET Web page we want to emit the XML content's to the client requesting the Web page. While this could be done in the previous example by opening the userInfo.xml file after creating it and then Response.Write()ing its contents out, this approach is a bit of a hack.

A better approach is to have the results of the XmlTextWriter emitted directly to the output stream. This can be accomplished quite easily, by changing one line of code in the previous code sample. In the XmlTextWriter constructor, rather than specifying a file path, we can specify a Stream. Specifically, we want to specify Response.OutputStream. When doing this you will need to make another small change to the ASP.NET Web page. In the <@ Page ... > directive you need to indicate the page's MIME type as text/xml. If you don't do this, some browsers may think the data being sent is for a standard HTML Web page, and will attempt to format the XML document just as they would an HTML page (which will hide the XML elements and remove all whitespace).

The following code shows an abbreviated version of the previous code sample, with the changes in bold.

<@ Page ContentType="text/xml" %>

<%@ Import Namespace="System.Xml" %>

<%@ Import Namespace="System.Text" %>

<script language="C#" runat="server">

void Page_Load(object sender, EventArgs e)

{

// Create a new XmlTextWriter instance

XmlTextWriter writer = new

XmlTextWriter(Response.OutputStream, Encoding.UTF8);


// start writing!

...

}

Notice that by viewing the live demo you are shown an XML document (even though you are visiting an ASP.NET Web page). This is the same XML document that, in the previous code sample, was saved to userInfo.xml.

ObjectDataSource with objects having parameterized constructor

The ObjectDataSource control will create an instance of the source object, call the specified method, and dispose of the object instance all within the scope of a single request, if your object has instance methods instead of static methods (Shared in Visual Basic). Therefore, your object must be stateless. That is, your object should acquire and release all required resources within the span of a single request.

You can control how the source object is created by handling the ObjectCreating event of the ObjectDataSource control. You can create an instance of the source object, and then set the ObjectInstance property of the ObjectDataSourceEventArgs class to that instance. The ObjectDataSource control will use the instance that is created in the ObjectCreating event instead of creating an instance on its own.

<asp:objectdatasource id="ObjectDataSource1" typename="Samples.AspNet.CS.EmployeeLogic" onobjectcreating="NorthwindLogicCreating" selectmethod="GetAllEmployees" runat="server">
</asp:objectdatasource>



and have a method defined as


 private void NorthwindLogicCreating(object sender, ObjectDataSourceEventArgs e)
{
// Create an instance of the business object using a non-default constructor.
EmployeeLogic eLogic = new EmployeeLogic("Not created by the default constructor!");

// Set the ObjectInstance property so that the ObjectDataSource uses the created instance.
e.ObjectInstance = eLogic;
}


Tuesday, August 28, 2007

Formatting GridView Template Data using FormatString in ASP .NET

GridView DataFormatString samples to format the Grid View columns Data e.g. DataFormatString="{0:MM/dd/yy}" HeaderText="date2" HtmlEncode="False" SortExpression="date2">


{0:n}Numbers: Provides formatting with commas for a thousands separator.{0:e4} Numbers:Specifies scientific notation to 4 decimal places{0:ddd, MMM d yyyy}date1 Shows a date as Sat, Jan 14, 2006{0:MM/dd/yy}date2 Shows a date as 01/16/06
As you enter these formatting strings, you also need to change the HtmlEncode property to False for each field. Otherwise, the formatting won't show up properly. This changed from the beta versions of the various Visual Studio 2005 products; in those versions, you didn't have to set HtmlEncode property to false.

How Generic Collections work inside?

public class TypeSafeList<T>
{
T[] innerArray = new T[0];
int currentSize = 0;
int capacity = 0;

public void Add(T item)
{
// see if array needs to be resized
if (currentSize == capacity)
{
// resize array
capacity = capacity == 0 ? 4 : capacity * 2; // double capacity
T[] copy = new T[capacity]; // create newly sized array
Array.Copy(innerArray, copy, currentSize); // copy over the array
innerArray = copy; // assign innerArray to the new, larger array
}

innerArray[currentSize] = item;
currentSize++;
}

public T this[int index]
{
get
{
if (index < 0 index >= currentSize)
throw new IndexOutOfRangeException();
return innerArray[index];
}
set
{
if (index < 0 index >= currentSize)
throw new IndexOutOfRangeException();
innerArray[index] = value;
}
}

public override string ToString()
{
string output = string.Empty;
for (int i = 0; i < currentSize - 1; i++)
output += innerArray[i] + ", ";

return output + innerArray[currentSize - 1];
}
}

Monday, August 27, 2007

. NET Type Safety

Type safe means preventing programs from accessing memory outside the bounds of an object's public properties A programming language is type safe when the language defines the behavior for when the programmer treats a value as a type to which it does not belong. Type safety requires that well-typed programs have no unspecified behavior (i.e., their semantics are complete). Languages such as C and C++, which allow programmers to access arbitrary memory locations, are not type safe. An unsafe programming language supports operations (such as accessing arbitrary memory locations), which are not defined in terms of the language semantics. Type safety is a property of the programming language, and not of the programs themselves.

. NET Type Safety

Sunday, August 26, 2007

Microsoft .NET Remoting - Complete Walkthrough

 

Remoting enables you to write applications that allow objects in different .NET application domains to communicate with each other. In general, objects living in different application domains cannot access each other directly. They need an infrastructure that makes communication possible. That's what .NET Remoting is for. It's the .NET analogy to DCOM, for those of you who are familiar with DCOM. It allows interprocess and intermachine communication between objects.

Look here for a great power-point presentation and also attached interview transcript of the author about Microsoft .NET Remoting - Complete Walkthrough...Just follow him!!! !!!

Microsoft .NET Remoting WebCast

String vs. StringBuilder - How they Work?

 

String objects in .net are immutable. Once the string has been created, the value can't be changed. When you type s = s + "foo";, you actually discard the old s and create a new string object containing the result of the concatenation. When repeated several times, you end up constructing many temporary string objects.

StringBuilder, on the other hand, represents a mutable string. The class itself contains quite a few methods to change the contents of the string. This includes appending new strings to the end - the most common operation by far. Internally, StringBuilder reserves a buffer of memory which is used only partially at first (usually). Concatenations that fit into the buffer are just pasted in and the string length is changed. If the new resulting string wouldn't fit into the buffer, a new buffer is allocated and the old contents are moved in. In no case new objects need to be created.

The sore points of StringBuilder are the construction cost (which makes the "magic number" practically always at least 3) and the cost of allocating a new buffer when the resultant string would exceed the current buffer size. The latter one explains why the preknowledge (or a good estimation) of the resultant string size helps so much: StringBuilder can just allocate a sufficient buffer once.

.net String vs. StringBuilder - concatenation performance

Great articles on Data Structures and Collections in .NET

Hi,

I would recommend reading these below mentioned articles from MSDN for any programmer who wants to develop or is developing using Microsoft .NET Framework technologies.

Part 1: An Introduction to Data Structures
Part 2: The Queue, Stack, and Hashtable
Part 3: Binary Trees and BSTs
Part 4: Building a Better Binary Search Tree
Part 5: From Trees to Graphs
Part 6: Efficiently Representing Sets

Data Structures in .NET

 

Why data structures are important, and their effect on the performance of an algorithm. To determine a data structure's effect on performance, we'll need to examine how the various operations performed by a data structure can be rigorously analyzed. Finally, we'll turn our attention to two similar data structures present in the .NET Framework: the Array and the List. Chances are you've used these data structures in past projects. In this article, we'll examine what operations they provide and the efficiency of these operations.

The Queue and Stack. Like the List, both the Queue and Stack store a collection of data and are data structures available in the .NET Framework Base Class Library. Unlike a List, from which you can retrieve its elements in any order, Queues and Stacks only allow data to be accessed in a predetermined order. We'll examine some applications of Queues and Stacks, and see how these classes are implemented in the .NET Framework. After examining Queues and Stacks, we'll look at hashtables, which allow for direct access like an ArrayList, but store data indexed by a string key.

While arrays and Lists are ideal for directly accessing and storing contents, when working with large amounts of data, these data structures are often sub-optimal candidates when the data needs to be searched. The binary search tree data structure, which is designed to improve the time needed to search a collection of items. Despite the improvement in search time with the binary tree, there are some shortcomings. SkipLists, which are a mix between binary trees and linked lists, and address some of the issues inherent in binary trees.

A graph is a collection of nodes, with a set of edges connecting the various nodes. For example, a map can be visualized as a graph, with cities as nodes and the highways between them as edged between the nodes. Many real-world problems can be abstractly defined in terms of graphs, thereby making graphs an often-used data structure.

Finally, in Part 6 we'll look at data structures to represent sets and disjoint sets. A set is an unordered collection of items. Disjoint sets are a collection of sets that have no elements in common with one another. Both sets and disjoint sets have many uses in everyday programs, which we'll examine in detail in this final part.

Part 1: An Introduction to Data Structures

Saturday, August 25, 2007

Tuesday, August 21, 2007

Delegates in C# .NET


Delegates in C#
are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.
Here are some features of delegates:

  • A delegate represents a class.
  • A delegate is type-safe.
  • We can use delegates both for static and instance methods
  • We can combine multiple delegates into a single delegate.
  • Delegates are often used in event-based programming, such as publish/subscribe.
  • We can use delegates in asynchronous-style programming.
  • We can define delegates inside or outside of classes.
Syntax of using delegates
//Declaring delegate
delegate void SampleDelegate(string message);
// declare method with same signature:
static void SampleDelegateMethod(string message) { Console.WriteLine(message); }
// create delegate object
SampleDelegate d1 = SampleDelegateMethod;
// Invoke method with delegate
d1("my program");
Technorati Tags: ,

Web Services in ASP .NET


Introduction to web service especially in asp .net

A Web service is a class that allows its methods to be called by methods on other machines via common data formats and protocols, such as XML and HTTP. In .NET, the over-the-network method calls are commonly implemented through the Simple Object Access Protocol (SOAP), an XML-based protocol describing how to mark up requests and responses so that they can be transferred via protocols such as HTTP. Using SOAP, applications represent and transmit data in a standardized XML-based format.
A Web service is a software component stored on one machine that can be accessed by an application (or other software component) on another machine over a network. The machine on which the Web service resides is referred to as a remote machine. The application (i.e., the client) that accesses the Web service sends a method call over a network to the remote machine, which processes the call and returns a response over the network to the application.

Methods in a Web service are invoked through a Remote Procedure Call (RPC). These methods, which are marked with the WebMethod attribute, are often referred to as Web service methods or simply Web methods. Declaring a method with attribute WebMethod makes the method accessible to other classes through RPCs and is known as exposing a Web method.
Web services have important implications for business-to-business (B2B) transactions. They enable businesses to conduct transactions via standardized, widely available Web services rather than relying on proprietary applications. Web services and SOAP are platform and language independent, so companies can collaborate via Web services without worrying about the compatibility of their hardware, software and communications technologies.
Web services are not the best solution for certain performance-intensive applications, because applications that invoke Web services experience network delays. Also, data transfers are typically larger because data is transmitted in text-based XML formats.

Introduction to WebMethods in ASP .NET

Methods of a class that implement a Web service do not automatically have the ability to receive Web service requests and send back responses, but with Web services created using ASP.NET, it is very simple to add that capability. Apply a WebMethod attribute to public methods. Methods of a Web service class that can be communicated with over the Web are called Web service methods.

Web service methods are a key part of the messaging infrastructure employed by Web services. That is, a client and a Web service communicate using messages, specifically SOAP messages, by default. Clients send a SOAP request to a Web service and a Web service method typically returns a SOAP response. Web services define the type of messages they accept using operations, as defined by Web Services Description Language (WSDL). These operations correlate to each of the Web service methods within a Web service.

Even though each of these Web service methods are defined in ASP.NET using a method of a class, it is important to realize that the data that is eventually communicated over the network must be serialized into XML. As such, it is important to remember that Web services are not a replacement for DCOM, but rather a messaging infrastructure for communicating across platforms using industry standards.

Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. The WebMethod attribute tells .NET that a particular public method should be exposed as a web-callable method. The WebMethod attribute has six associated properties to document and change the behavior of your web method. They are:
Description
MessageName
EnableSession
CacheDuration
TransactionOption
BufferResponse
The first two properties are used to document a web method, while the others affect its behavior.

SOAP in .NET Web Services

The Simple Object Access Protocol (SOAP) is a platform-independent protocol that uses XML to make remote procedure calls.
Each request and response is packaged in a SOAP message containing the information that a Web service requires to process the message.

SOAP supports an extensive set of types like the primitive types, DataSet, DateTime, XmlNode and others. SOAP can also transmit arrays of these types and objects of user-defined types.
When a program invokes a Web method, the request and all relevant information are packaged in a SOAP message and sent to the server on which the Web service resides.
A Web service receives a SOAP message and parses its contents (contained in a SOAP envelope) to determine the method that the client wishes to execute and the method's arguments.
After a Web service parses a SOAP message, the proper method is called and the response is sent back to the client in another SOAP message. The client parses the response to retrieve the result.

User Defined Types in Web Services

It is possible to process user-defined types (also known as custom types) in a Web service. These types can be passed to or returned from Web methods. Web service clients also can use these user-defined types, because the proxy class created for the client contains these type definitions

Custom types that are sent to or from a Web service are serialized, enabling them to be passed in XML format. This process is referred to as XML serialization.
Classes that are used to specify Web method return types and parameter types must provide a public default or parameterless constructor. Properties and instance variables that should be serialized in XML format must be declared public. Properties that should be serialized must provide both get and set accessors. Read-only properties are not serialized. Data that is not serialized simply receives its default value when an object of the class is deserialized.

Technorati Tags: ,

Sunday, August 19, 2007

atoi() function in c# .net - convert string to integer

 

public static int atoi(string str)
{
int sign=1;
int TheNumber=0;
int tmp=0;
int x=0;
int l=(str.Length)-1;
char[] c=str.ToCharArray();

if ('-'==c[0]){sign=-1; x=1;}

for(;x < l;x++)
{
if ((c[x]>='0')&&(c[x]<='9'))
{
tmp=(c[x]-'0');//0 is the 0 index
TheNumber=TheNumber*10+tmp; //to enlarge the number by *10 every time
}
}

return TheNumber*sign;

}

Technorati Tags:

Friday, August 10, 2007

Generic Dictionary Class

It's cool.

Here is a scenario. We want to store few Objects or Instances into a collection and then later identify them based on a key. We can use Dictionary class out of System.Collections.Generic.

Dictionary<TKey, TValue>, which is simply a collection of keys and its values.

So, let's say I want to store few objects in 2 different collections, but then retrieve them in particular order. If it was in single collection, it would have been easier to store in the same collection object, but here we need 2 different collections for storing them because, later at the time of retrieval we need to know the type of the object i.e. value we are retrieving.

Here is how we can handle this scenario.

	private Dictionary<int, ClassA> _ClassAObjectCollection;
private Dictionary<int, ClassB> _ClassBObjectCollection;
public void AddClassAObject(int orderNo, ClassA instance)
{
if(instance == null)
throw new ArgumentNullException("instance");
if(_ClassAObjectCollection == null)
_ClassAObjectCollection = new Dictionary();
_ClassAObjectCollection.Add(orderNo, instance);
}

Same way for ClassB.


So, that's just a small and cool example how can we utilize it to store objects and later retrieve these objects based on key from the collection of objects.


Thursday, August 9, 2007

Switch Statement in C# .net

Switch Statement syntax in C# .NET

switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}

 


An example is here...

switch (i) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
That's pretty simple C# syntax for Switch-case statements.

Technorati Tags:

Wednesday, August 8, 2007

HOW TO: Validating XML Fragments Against an XML Schema in .NET

This step-by-step article describes how to use XmlValidatingReader and XMLSchemaCollection objects to validate an Extensible Markup Language (XML) fragment against an XML schema.
XmlValidatingReader implements the XmlReader class and provides support for XML data validation. The Schemas property of XmlValidatingReader connects the reader to the schema files cached in an XmlSchemaCollection. The ValidationType property of XmlValidatingReader specifies the type of validation the reader should perform. If you set the property to ValidationType.None, you create a nonvalidating reader.
You can only add XML Schema Definition Language (XSD) schemas and XML-Data Reduced (XDR) schemas to XmlSchemaCollection. Use the Add method with a namespace URI to load schemas. For XML schemas, the typical namespace URI is the targetNamespace property of the schema.

HOW TO: Validate XML Fragments Against an XML Schema in Visual Basic .NET

Technorati Tags: ,

Monday, August 6, 2007

Membership Database instead of ASPNETDB.mdf

Creating Membership Database into existing sql server database

Generally, ASPNETDB.mdf, file based database is created in App_Data folder when we start using ASP .NET Membership and Profile features to use Login Controls in our ASP .NET application. But, generally we would like to create these membership database objects in the same database that we have created for our application.

I have created a video that shows how to do that using aspnet_regsql.exe Sql Server Membership database registration tool.



Saturday, August 4, 2007

.NET Framework Class Browser

 

I don't know if you have already used this class browser. But that's an excellent view of Microsoft .NET Framework Namespaces and Classes

It provides details about the namespaces and its classes. Also, provides information about fields, properties and methods in a class.

.NET Framework Class Browser

Thursday, August 2, 2007

A Unit Testing Walkthrough with Visual Studio Team Test

Introduction

With the latest release of Visual Studio Test System (VSTS) comes a full suite of functionality for Visual Studio Team Test (TT). Team Test is a Visual Studio integrated unit-testing framework that enables:

  • Code generation of test method stubs.
  • Running tests within the IDE.
  • Incorporation of test data loaded from a database.
  • Code coverage analysis once the tests have run.

In addition, Team Test includes a suite of testing capabilities not only for the developer, but the test engineer as well.

In this article, we are going to walk through how to create Team Test unit tests. We begin by writing a sample assembly, and then generating the unit test method stubs within that assembly. This will provide readers new to Team Test and unit testing with the basic syntax and code. It also provides a good introduction on how to quickly set up the test project structure. Next, we switch to using a test driven development (TDD) approach in which we write unit tests before writing the production code.

One of the key features of Team Test is the ability to load test data from a database and then use that data within the test methods. After demonstrating basic unit testing, we describe how to create test data and incorporate it into a test.

A Unit Testing Walkthrough with Visual Studio Team Test

Technorati Tags: ,

Monday, July 30, 2007

Consequences of Strong Naming Assembly in .NET

Any code you have that uses this assembly, will need to be recompiled with a reference to the new assembly with the newer version.

Strong named assemblies can only reference other strong named assemblies.

If your product includes many assemblies (.NET DLL's) and you want to ship only one of them as a hotfix, you will not be able to because your other assemblies will still refer to old version of the DLL. So either restrict to the same old version or use the .Net Framework configuration tool to forward the old version to the new version.

If you have classes that need to be serialized, the engine includes type information in the serialized data, that way it can be reconstituted later. If you the AssemblyFormat property is not set correctly, you could end up with a situation here you have stored some data, upgraded your application (maybe because of a bug fix), and then
error when you try to load your serialized database (even though nothing in that particular class has changed).

Unless your assemblies need to be placed in the GAC, or run as COM+ component, or some other special case,
strong-naming them probably is not necessary.

How to sign a .NET Assembly with a Strong Name

A strong name consists of the assembly's identity—its simple text name, version number, and culture information (if provided)—plus a public key and a digital signature. It is generated from an assembly file using the corresponding private key. (The assembly file contains the assembly manifest, which contains the names and hashes of all the files that make up the assembly.)

Security Note: A strong-named assembly can only use types from other strong-named assemblies. Otherwise, the security is already compromised.

It's pretty easy using Visual Studio .net 2005 IDE, but we will also talk about alternatives later.

  1. Go to "Property Pages" of your project from the Solution Explorer.
  2. Select the "Signing" Tab from the list of tabs on the left.
  3. Select the check-box "Sign the Assembly".
  4. Select "New..." from "Choose a strong name key file" drop-down list.
  5. Just finish the dialog by providing strong name key filename(new) and password(optional).

There you go!!

  • Alright, other alternatives are also mentioned here.

First of all, we need a cryptographic key pair to sign an assembly with a strong name.

This public and private cryptographic key pair is used during compilation to create a strong-named assembly. Microsoft has provided Strong Name Tool (sn.exe) to create this key pair in a file with ".snk" extension.

Open the command prompt and type the following command,

sn -k <filename> //e.g. sn -k mySgnKey.snk will create a keypair file named mySgnKey.snk

Delay Signing an Assembly:

If you intend to delay sign an assembly and you control the whole key pair (which is unlikely outside test scenarios), you can use the following commands to generate a key pair and then extract the public key from it into a separate file.

First Command: sn -k mySgnKey.snk

Second Command: sn -p mySgnKey.snk publicSgnKey.snk

Sign an Assembly with a Strong Name using Assembly Linker

al /out:<assembly name> <module name> /keyfile:<file name>

In this command, assembly name is the name of the assembly to sign with a strong name, module name is the name of the code module used to create the assembly, and file name is the name of the container or file that contains the key pair.

al /out:MyAssembly.dll Project.Module /keyfile:mySgnKey.snk

Signing an Assembly with a Strong Name using Assembly Attributes

C# usage: [assembly:AssemblyKeyFileAttribute(@"sgKey.snk")]

VB usage: <Assembly:AssemblyKeyFileAttribute("sgKey.snk")>

Note: When signing an assembly with a strong name, the Assembly Linker (Al.exe) looks for the key file relative to the current directory and to the output directory. When using command-line compilers, you can simply copy the key to the current directory containing your code modules.

How To Reference This Strongly Named Assembly

<compiler command> /reference:<assembly name>

In this command, compiler command is the compiler command for the language you are using, and assembly name is the name of the strong-named assembly being referenced. You can also use other compiler options, such as the /t:library option for creating a library assembly.

The following example creates an assembly called myAssembly.dll that references a strong-named assembly called myLibAssembly.dll from a code module called myAssembly.cs.

csc /t:library MyAssembly.cs /reference:MyProjectAssembly.dll

How To Make a Run-time Reference to this Strongly Named Assembly

We need to use the name of the assembly in following manner...

<assembly name>, <version number>, <culture>, <public key token>

C# usage: Assembly.Load("myAssemby,Version=1.0.0.1,Culture=neutral,PublicKeyToken=7b53aa32d4fc18b1");

VB usage: Assembly.Load("myAssemby,Version=1.0.0.1,Culture=neutral,PublicKeyToken=7b53aa32d4fc18b1")

Monday, July 23, 2007

Little RegEx Examples in .NET

If you want to use any of the special characters(viz. [,\, ^, $, . , , ?, *, + , (, ) ) as a literal in a regex, you need to escape them with a backslash.

e.g. Dot in the email pattern

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

Most regular expression flavors treat the brace { as a literal character, unless it is part of a repetition operator like {2,6}.

Using Character Classes, you can find text with particular set of characters.

e.g. To allow alphanumeric characters and underscores, use [A-Za-z_0-9]*

The only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\), the caret (^) and the hyphen (-).

Examples

1) Email Regular Expression

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

2) HTML Tag matching - Regular Expression

<([A-Z][A-Z0-9]*)[^>]*>(.*?)</\1>

This is very simple example and can't be used in real scenario, as it can't find the nested html tags.

3) Do you want to make RegEx for parsing ASP 3.0 Classic style written program/code?

This can help in matching. And it's a beautiful example of using named capture in Regular Expressions

.

(?<tbefore>.*?)(?<allcode><%(?<equals>=)*\s*(?<code>.*?)%>)(?<endtext>.*)

Here, tbefore name will capture all text before code starting tag <%.

allcode name will capture all code text within <% %> including signs.

code will capture all code within <% %>.

endtext name will capture all text after this code block.

Wednesday, July 18, 2007

Getting acquainted with Windows Powershell environment

The best way to get the help about it is,

get-command. What's that. The Get-Command cmdlet gets basic information about cmdlets and other elements of Windows PowerShell commands, such as files, functions, and Windows PowerShell providers.

get-help get-command -detailed

Where get-command is the cmdlet for which you wish to get the help.

and -detailed parameter indicates that we wish to get details regarding parameters and methods.

Optionally, -Full means complete help info. that's available

and -examples means to see only examples

and get-help get-command -parameter servicename would give you complete information about the parameter named 'servicename' that's part of the get-command returned object.

To display the help of all topics available, you can
get-help get-* and get-help about*

If you need help with any cmdlet that gets listed,

get-help <cmdlet-name or get-alias> -detailed

That's the best help to start with. It gives you list of all get commands and nouns for that matter as you may have observed the verb-noun pattern of powershell.

get-alias

to know the short names or aliases for many cmdlets in your powershell session.

Here are the few common verbs other than get.

More...for the next post!

Tuesday, July 17, 2007

Windows PowerShell

I'm trying to provide a very quick reference to windows powershell that could help the beginners and these are the same things that helped me.

Windows PowerShell is very different.

  • Windows PowerShell does not process text. Instead, it processes objects based on the .NET platform.

  • Windows PowerShell comes with a large set of built-in commands with a consistent interface.

  • All shell commands use the same command parser, instead of different parsers for each tool. This makes it much easier to learn how to use each command.

You can download and install it for free from this Microsoft web site. Make sure to check sys. requirements.

http://www.microsoft.com/technet/scriptcenter/topics/msh/download.mspx

Windows PowerShell Cmdlets

A cmdlet (pronounced "command-let") is a single-feature command that manipulates objects in Windows PowerShell. You can recognize Cmdlets by their name format -- a verb and noun separated by a dash (-), such as Get-Help, Get-Process, and Start-Service.

Ok, so here goes the question. How do you get to know which are the possible verbs and what are the possible nouns that you can use to constitute valid powershell commands or for that matter cmdlets.

The "get" cmdlets only retrieve data, the "set" cmdlets only establish or change data, the "format" cmdlets only format data, and the "out" cmdlets only direct the output to a specified destination.

Each cmdlet has a help file that you can access by typing:

get-help <cmdlet-name> -detailed

You can download the Graphical help file at this Microsoft site.
http://www.microsoft.com/downloads/details.aspx?familyid=3B3F7CE4-43EA-4A21-90CC-966A7FC6C6E8&displaylang=en

You can run Windows command-line programs in Windows PowerShell

All in PowerShell is your .NET Framework and .NET Objects world.

For example, when you get a process in Windows PowerShell, you are really getting an object that represents the process. When you view information about a process, you are viewing the properties of its process object. And, when you start a process, that is, when you change the Status property of the process to "started," you are using a method of the process object.

You can easily do string manipulation also to leverage the returned data.

Try this command in PS...

get-process findstr "iexplore"

and it will automatically filter the rows that had "iexplore" string...It gives you all the instances of Internet Explorer process... amazingly easy and handy...isn't it?

Tuesday, July 10, 2007

Paging Logic

I am trying to write a simple logic for paging the resultset of records.
It purely depends on a single querystring parameter like start = 161 or start=81
This would display records from 161 to 170 or 81 to 90.


int nStart = 1; //default start number i.e. very first record when first search hit.
int newStart;
string requestUri = Request.Url.AbsoluteUri; //actual complete URL
string newRequestUri;

if (Request.QueryString["start"] != null)
nStart = Convert.ToInt16(Request.QueryString["start"]);

int nMaxResultsInAPage = 10;
int pageNumber; //current page number

if (nStart == 1) //initially not divisible by 10 as it is possible with page 2nd and record 11
pageNumber = 1;
else //current page number....as start gives the record number
pageNumber = nStart / 10; // 2 = 21 / 10



//j... ... ...refers to the paging number to be iterated
//count... ... ...how many paging numbers to be shown in total for navigation

for (int j = pageNumber - 10 / 2, count = 0;count <> 0)
{
newStart = (j-1) * 10 + 1; //4th page represents records 31 to 40...so [4th Page] = 3 * 10 + 1
newRequestUri = requestUri.Replace("start=" + nStart.ToString(), "start=" + Convert.ToString(newStart));
if(count == 0)
ltrPageLinks.Text += " Previous - ";
else if (count == 11)
ltrPageLinks.Text += " Next - ";
else if (j == nStart / 10 - 1)
ltrPageLinks.Text += "" + j.ToString() + " - ";
else
ltrPageLinks.Text += "" + j.ToString() + " - ";


}
}

Tuesday, July 3, 2007

Good practice about DropDownList Databinding

Here is how one should bind the drop-downlist...and why is it good?
Because, in most cases we are executing some logic like loading another drop-down list on change of selected index of the first one.

Make functions to bind respective drop-down lists. And call them when needed to re-bind.

Page_Load
{
BindFirstDropDown();
FirstDropDown.Items.Insert(0,new ListItem("Select", "0"));
if(SecondDropDown.Items.Count == 0)
SecondDropDown.Items.Add(new ListItem("Select", "0"));
}

FirstDropDown_IndexChanged(...)
{
BindSecondDropDown();
SecondDropDown.Items.Insert(0,new ListItem("Select", "0"));

}
void BindFirstDropDown()
{
...
}

void BindSecondDropDown()
{
...
}

Monday, July 2, 2007

DataSet hell - Failed to enable constraints. One or more rows contain values...

I have found some great posts regarding
Typed DataSet regular problem that is faced by every programmer who starts working with datasets in good application.

http://weblogs.asp.net/rosherove/archive/2004/10/03/237260.aspx

What did I face?
Usually, as in most applications fields returns by every stored procedure even that's written on a gived table, are different.
So, result set of every stored procedure doesn't match the one specified in DataTable of Typed DataSet schema.

So, it's a good idea to setup individual table adapter for almost all procedures!!

Enum Types in .NET or C# .NET

Enum types implicitly inherit the System.Enum type in the Base Class Library (BCL). This also means that you can use the members of System.Enum to operate on enum types.

I have included few code snippets which are self-explanatory for use of enums.

public
enum Volume : byte
{
Low = 1,
Medium,
High
}


void ShowVolume(int v)

{

Volume vol = (Volume)v;

If(vol == Volume.Low)


}


// get a list of member names from Volume enum,
// figure out the numeric value, and display
foreach (string volume in Enum.GetNames(typeof(Volume)))
{
Console.WriteLine("Volume Member: {0}\n Value: {1}",
volume, (byte)Enum.Parse(typeof(Volume), volume));
}


// get all values (numeric values) from the Volume
// enum type, figure out member name, and display
foreach (byte val in Enum.GetValues(typeof(Volume)))
{
Console.WriteLine("Volume Value: {0}\n Member: {1}",
val, Enum.GetName(typeof(Volume), val));
}


Given the type of the enum, the GetValues method of System.Enum will return an array of the given enum's base.

Accessing Typed Datasets

How to access Typed DataSet from C# .NET code ?

Dim productsAdapter As New NorthwindTableAdapters.ProductsTableAdapter()

Dim products as Northwind.ProductsDataTable


products = productsAdapter.GetProducts()


For Each productRow As Northwind.ProductsRow In products

Response.Write("Product: " & productRow.ProductName & "<br />")

Next


Each object used in this example is also strongly-typed, allowing Visual Studio to provide IntelliSense and compile-time type checking. And best of all the DataTables returned by the TableAdapter can be bound to ASP.NET data Web controls, such as the GridView, DetailsView, DropDownList, CheckBoxList, and several others.


Parameterized Methods in Typed DataSet based Data Access Layer.

It's almost same as the normal select all query.
Just go to DataSet designer and Right-click the TableAdapter section.
Click to "Add Query…".

You can preferably select Stored Procedure or Ad-Hoc Query.

In the next dialog screen, specify the query or select the procedure.

Now just rename the Fill and Get methods as per your preference and the methods are ready to test as soon as you finish the dialog.

Right-click on the table adapter and choose preview data to enter parameter values and see the results.


Anyhow, this is the best article that I have found on Typed Datasets…everything you need to know about typed datasets creation and using them.

Thursday, June 28, 2007

Strongly Typed DataSets over UnTyped DataSets

A typed DataSet is a class that derives from a DataSet.

You can access tables and columns by name, instead of using collection-based methods. A typed DataSet also allows the Visual Studio .NET code editor to automatically complete lines as you type.

The strongly typed DataSet provides access to values as the correct type at compile time. With a strongly typed DataSet, type mismatch errors are caught when the code is compiled rather than at run.

Typed Datasets increase the readability as we are no more using the ordinal index of the columns and it doesn't depend on the changes done in the backyard.

The typed DataSet code is shorter, requires neither the table name nor the column name to be accessed via a string or ordinal position, and it does not require the Rows property. You can use IntelliSense to get a list of the table names available to the typed DataSet as well as a list of the column names available to its tables, so the code is really easy to write. In the typed DataSet, the columns are all defined as properties with their respective datatypes. . Typed DataSets make binding to controls easier since they contain the schema information within them. When binding a typed DataSet to an ASP.NET DataGrid, the properties menu reads the selected typed DataSet's schema and recognizes the DataTables and the DataColumns that the typed DataSet exposes. The Properties window fills the DataMember list with the names of the selected DataSet's DataTable objects. Likewise, the list of available fields is loaded into the DataKeyField property.

There are differences in maintenance and performance when referring to columns in an untyped DataSet. The strongly typed DataSet offers advantages over the untyped DataSet in terms of speed and easy maintainability.

Classes

It takes an XML Schema Definition (XSD) file as well as a class file to create a strongly typed DataSet. The XSD file stores the XML that defines the schema for the strongly typed DataSet.

A strongly typed DataSet is actually a class that inherits from the System.Data.DataSet class and adds a few extra features of its own. The class file is generated from the XSD file. You can regenerate the class file by right-clicking in the XSD's designer view and selecting Generate DataSet (alternatively, you can use the xsd.exe command-line utility). The class file actually contains a series of classes that inherit from and extend the DataSet, DataTable, DataRow, and EventArgs classes. Because of this inheritance, developers do not lose any functionality by using a strongly typed DataSet. For example, even though you can refer to a DataTable via a property with the same name as the table, you can still refer to the table through the Tables collection. So, oDS.Tables["Orders"] is same as the oDS.Orders.

The strongly typed DataSet class file contains one class that inherits from the base DataSet. It also contains one class for every DataTable contained within the DataSet. For example, if there are both Orders and OrderDetails DataTables in a strongly typed DataSet, there will be classes called OrdersDataTable and OrderDetailsDataTable that both inherit from the DataTable object. Likewise, there would be classes named OrdersRow and OrderDetailsRow that inherit from DataRow. Because of this inheritance, these classes also expose all of the standard functionality that the base classes expo

Strongly typed DataSets also offer a few additional methods to extend the DataSet base class. For example, a typed DataSet based on the Northwind database's Orders table would expose the method FindByOrderID which would accept an integer argument that would locate the DataRow with the corresponding OrderID value. The standard Find method could still be used since all of the base class's method and properties are available, but the extended properties and methods can make writing code a bit easier on developers.

Strongly typed DataSet objects are practically self documenting since they are so easy to read. Because the names of the tables and columns that they represent are properties of the typed DataSet class, writing code with typed DataSets is more intuitive and easier to maintain. By making development time faster, easier, less prone to typing errors, and by making the code more maintainable, strongly typed DataSets are a great help to developers who want to write more effective code more efficiently.

Tuesday, June 26, 2007

Creating Tab Strip using Multi-View and View Server Controls


Here is a very simple way to create a Tab Strip display for tabbed user interface using existing ASP .NET Server controls viz., Multi-View and View Server Controls.

This code creates an illusion of tab-strip control in asp .net. On click event of the Menu Control, it changes the 'View' that are part of the Multi-View control. So, presumably this causes a postback of the page. You can prevent this using UpdatePanel of ASP .NET AJAX toolkit and setting the trigger on Menu Control click.

You can use the following code into any ASPX file and see the output as is shown here in the pretty screen shot.



<table border="0" cellpadding="0" cellspacing="0">



<tr id="menustrip">

<td>

<asp:Menu ID="mnuTabs" runat="server" Orientation="Horizontal" BackColor="#B5C7DE" DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="1em" ForeColor="#284E98" StaticSubMenuIndent="10px" OnMenuItemClick="mnuTabs_MenuItemClick">

<Items>

<asp:MenuItem Text="Tab 1" Value="1" Selected="True"></asp:MenuItem>

<asp:MenuItem Text="Tab 2" Value="2"></asp:MenuItem>

<asp:MenuItem Text="Tab 3" Value="3"></asp:MenuItem>

<asp:MenuItem Text="Tab 4" Value="4"></asp:MenuItem>

</Items>



<StaticMenuItemStyle HorizontalPadding="10px" VerticalPadding="4px" ItemSpacing="0" BorderColor="#507cd1" BorderStyle="dotted" BorderWidth="1" />

<DynamicHoverStyle BackColor="#284E98" ForeColor="White" />

<DynamicMenuStyle BackColor="#B5C7DE" />

<StaticSelectedStyle BackColor="#507CD1" ForeColor="White" BorderColor="#507cd1" BorderStyle="solid" BorderWidth="1" />

<DynamicSelectedStyle BackColor="#507CD1" />

<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />

<StaticHoverStyle BackColor="#284E98" ForeColor="White" />

</asp:Menu>



</td>

<td></td>

</tr>

<tr>

<td colspan="2">

<div style="border: solid 2px #507cd1; border-top-width:4px; display:table; position:relative; padding: 3px 5px 3px 5px; min-width:975px; min-height:200px;">

<asp:MultiView ID="mvwPanes" runat="server">

<asp:View ID="View1" runat="server">

<p class="tab-view-heading">

Pane 1</p>

</asp:View>

<asp:View ID="View2" runat="server">

<p class="tab-view-heading">

Pane 2</p>

</asp:View>

<asp:View ID="View3" runat="server">

<p class="tab-view-heading">

Pane 3</p>

</asp:View>

<asp:View ID="View4" runat="server">

<p class="tab-view-heading">

Pane 4</p>

</asp:View>

</asp:MultiView>

</div>

</td>

</tr>

<tr id="viewstrip">



</tr>

</table>

Sunday, May 13, 2007

What do you mean Asynchronous Database Commands ?

When we execute any database. Thread that executing command waits before command get fully executing before executing any additional code. Thread is blocked for another process. But Asynchronous Database Commands solve this problem when database command is executing current thread can continue on other process.Thread can execute a no of database command. There are two benefits of using Asynchronous Database Commands.
A.Executing Multiple Databse Commands simultaneously improve performance.
B. Because ASP dot Net framework uses a limited pool service for request. Whenany request for a page is comes its assign a thread to handle the request. If framework is out of thread then job is in gueses we get error 503. But if we are using asynchronous database command then current thread is release back to current thread pool."

How to set process priority in .NET?

Here is the sample code lines,
which allows setting the priority of the process.

The process here, refers to WinForms application or Windows Service which can be seen in Task Explorer being executed as an EXE.

Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;


Namespace: System.Diagnostics
Class: System.Diagnostics.Process
Method: System.Diagnostics.Process.GetCurrentProcess()
--> This method allows us to get instance of the process under which the application is executed.
Property: PriorityClass
--> This property allows us to get or set the process priority

Enumerator: ProcessPriorityClass
--> This enumerator contains values as RealTime, High, AboveNormal, Normal, BelowNormal, Low. These are the same process priority levels as can be seen from Task Explorer for any windows processes.

Encrypting Connection Strings in web.config

DataProtectionConfigurationProvider
And
RSAProtectedConfigurationProvider

With config = ConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
And
config.Sections(“ConnectionStrings”).SectionInformation.ProtectSection(providerObj)


AQAAANCMnd8.............p4nZCszebgXs=

Friday, May 11, 2007

What is service oriented architecture - SOA ?

In this changing business climate, where globalization and demanding customers require agility and flexibility, retailers' IT systems are not helping them in meeting these expectations. Most of the legacy retail systems were built following tightly coupled point-to-point integration principles. Service orientation offers great benefits in moving from these legacy systems to more flexible and agile systems.

· SOA is a design philosophy independent of any product, technology, or industry trend.

· SOAs can be realized using Web services, but using Web services will not necessarily result in a SOA

· EDI, CORBA, and DCOM were conceptual examples of SO.

· SOA is not a methodology.

· SOAs are like snowflakes: No two are the same.

· SOA should be incremental and built on your current investments.

· SOA requires tools, not consultants.

· SOA is a means, not an end.

Microsoft .NET Framework, ASP .NET, C# .NET, VB .NET - Concepts, Queries, Interview Questions understanding

Hi all,

I have tried to gather few questions or queries in Microsoft .NET Framework Technologies like ASP .NET, C# .NET, VB .NET, Visual Studio.

The questions also pertain to Object Oriented Modeling or Object Oriented Concepts which are inherent part of .NET Framework programming model.

The questions would cover topics like
- Classes & Objects in .NET
- Inheritance and Polymorphism in .NET
- Reflection in .NET
- .NET Remoting & Web Services
- HttpHandler & HttpModule in .NET
- Debugging & Tracing in Microsoft Visual Studio .NET
- User Controls & Server Controls in .NET
- Methods, Attributes, Fields, Properties in .NET server controls and classes
- XML, XPath, XSLT in .NET
- Object Oriented Architectural Design Patterns in .NET
- ADO .NET
- .NET CLR, MSIL, CTS concepts

 
Dotster Domain Registration Special Offer