Showing posts with label .NET Examples. Show all posts
Showing posts with label .NET Examples. Show all posts

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

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];
}
}

Sunday, August 26, 2007

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

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: ,

Monday, July 30, 2007

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 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, 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

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.

 
Dotster Domain Registration Special Offer