Monday, March 31, 2008

This Blog Has Moved!

This is friendly reminder that if you're looking for new and fresh content from yours truly (Caveman), you should head on over to my new blog at Caveman's blog

Tuesday, March 25, 2008

Replace special characters in XML, using C#

We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent [1].

Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)

I have used the HttpUtility classes UrlEncode and UrlDecode methods to handle cross-site scripting attacks and this also helped me to get rid of the XmlException - "Data at the root level is invalid".

Reference:
1. MSDN

Friday, March 14, 2008

Cookie Viewer

During the development of a web application that supports cookies, it is almost always a necessity to have the knowledge of what is being persisted in the cookie.

Okay.... what options does one have to achieve this?

hmm..... lets see... well I can think of three ways of doing this:

1. Write a web page application to read all the cookie key/value pairs and display them.
2. Write a windows application to read all the cookie key/value pairs and display them.
3. Open the cookie file manually and go through the content.

I have been there and done that ... I mean during the course of my s/w development activities in the past I have myself implemented all three ways that I mentioned above and yet was not happy with the ease of use.

What if I could find some freeware that does the hard part of fetching all the cookies and enumerating them on a pane that is visually appealing.

Finally !!! I have stumbled on one such freeware utility called IE Cookies Viewer. This utility that displays the details of all cookies that Internet Explorer stores on your computer.



Following are a few things that this utility allows you to do:

1. Sort the cookies list by any column you want, by clicking the column header. A second click sorts the column in descending order.
2. Find a cookie in the list by specifying the name of the Web site.
3. Select and delete the unwanted cookies.
4. Save the cookies to a readable text file.
5. Copy cookie information into the clipboard.
6. Automatically refresh the cookies list when a Web site sends you a cookie.
7. Display the cookies of other users and from other computers.
8. Open the IECookiesView utility directly from Internet Explorer toolbar.
9. Change the content of a cookie !
10. Export your cookies to Netscape/Mozilla cookies file.
11. Block specific Web sites from using cookies through the cookies blocking mechanism of Internet Explorer 6.0.

It can be downloaded at NirSoft. This site has a lot of some cool stuff/utilities that is free for download.

ASP.Net Permanent Cookie vs Temporary Cookie (Update: 03/17/08)

When a cookie is assigned a value without defining the "Expires" property, that cookie would expire as soon as the browser is closed and will be called as a temporary cookie.

A permanent cookie is one where the "Expires" property is defined for that cookie, it will be persisted on the client computer and will expire as per the definition of the "Expires" property.

Internet Explorer on Windows (XP/2000/2003) writes its cookies in the C:\Documents and Settings\[user_name]\Cookies folder.

References:
1. NirSoft

Tuesday, February 26, 2008

Developer's handkit

However skilled you are as a technician, without the appropriate tools you would still be a dud. Just like a craftsman knows his/her tools, a software professional also has to know the tools that are apt for the job. Tools that are handy and that make you look professional is what I am talking about. I have found and used a few tools over the years that have helped me a lot at my work.

Following are some of them and a brief description of what they do. Most of them are free to use and others are only free to try...

Fiddler:

Have you ever found yourself wondering how Microsoft Internet Explorer interacts with your Web application? Have you encountered a strange performance bottleneck that you can't track down? Are you curious about which cookies are being sent, or what downloaded content is marked as cacheable? [1]

Microsoft Fiddler can help you answer these questions, and many more. Fiddler is an HTTP debugging proxy that logs all HTTP traffic between your computer and the Internet. Fiddler enables you to inspect all HTTP traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler is much simpler to use than NetMon or other network debuggers because it exposes only HTTP traffic and does so in a user-friendly format. [1]

Fiddler includes a simple but powerful Microsoft JScript .NET event-based scripting subsystem flexible enough to support a broad array of HTTP debugging tasks. Written in C# on the Microsoft .NET Framework, Fiddler is available as an unsupported PowerToy for Internet Explorer. [1]


You can learn more about fiddler from MSDN athttp://msdn2.microsoft.com/en-us/library/bb250446.aspx

HttpWatch

HttpWatch is a tool that integrates with Internet Explorer and records detailed information about HTTP as you access a web site or application. If you access a site that uses secure HTTPS connections, HttpWatch automatically displays the decrypted form of the network traffic. [2]

I have used the free version called the HttpWatch Basic. This is an awesome tool for performance measurement and analysis.

IE Developer Toolbar

The Internet Explorer Developer Toolbar provides several features for exploring and understanding Web pages. These features enable you to:
1. Explore and modify the document object model (DOM) of a Web page.
2. Locate and select specific elements on a Web page through a variety of techniques.
3. Selectively disable Internet Explorer settings.
4. View HTML object class names, ID's, and details such as link paths, tab index values, and access keys.
5. Outline tables, table cells, images, or selected tags.
6. Validate HTML, CSS, WAI, and RSS web feed links.
7. Display image dimensions, file sizes, path information, and alternate (ALT) text.
8. Immediately resize the browser window to a new resolution.
9. Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
10. Display a fully featured design ruler to help accurately align and measure objects on your pages.
11. Find the style rules used to set specific style values on an element.
12. View the formatted and syntax colored source of HTML and CSS.

The Developer Toolbar can be pinned to the Internet Explorer browser window or floated separately.

DotNet Reflecter

Lutz Roeder's .Net Reflecter a class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL [4] . There are several AddIns that enhance the richness of this application. The AddIns can be downloaded at from http://www.codeplex.com/reflectoraddins


Ndoc - .Net 1.x

NDoc is a code documentation generator for .NET 1.x. NDoc generates class library documentation from .NET assemblies and the XML documentation files generated by the C# compiler. NDoc uses pluggable documenters to generate documentation in several different formats, including the MSDN-style HTML Help format (.chm), the Visual Studio .NET Help format (HTML Help 2), and MSDN-online style web pages. [5]


Sand Castle .Net 2.0

Sandcastle produces accurate, MSDN style, comprehensive documentation by reflecting over the source assemblies and optionally integrating XML Documentation Comments. Sandcastle has the following key features: [6]
1. Works with or without authored comments
2. Supports Generics and .NET Framework 2.0
3. Sandcastle has 2 main components (MrefBuilder and Build Assembler)
4. MrefBuilder generates reflection xml file for Build Assembler
5. Build Assembler includes syntax generation, transformation..etc
6. Sandcastle is used internally to build .Net Framework documentation
This article was very helpful to me to get me going with learning to use this application: http://www.codeplex.com/DocProject/Wiki/View.aspx?title=Creating%20a%20DocProject%20for%20a%20new%20solution&referringTitle=Home


Araxis Merge

File comparison (diff), merging and folder synchronization has never been so simple before araxis. This application can be used it to compare and merge source code, web pages and other text files with native application performance. Compare images and binary files. Synchronize folders. Perform code reviews and audits. Work with source hierarchies containing thousands of files. [7] I would highly recommend to try the demo version and am pretty sure that you will be very impressed with the features offered by this application.

FxCop

FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. Many of the issues concern violations of the programming and design rules set forth in the Design Guidelines for Class Library Developers, which are the Microsoft guidelines for writing robust and easily maintainable code by using the .NET Framework. [8]

FxCop is intended for class library developers. However, anyone creating applications that should comply with the .NET Framework best practices will benefit. FxCop is also useful as an educational tool for people who are new to the .NET Framework or who are unfamiliar with the .NET Framework Design Guidelines. [8]

Reference:
1. MSDN
2. HttpWatch dot com
3. IE Development Toolbar
4. .Net Reflecter
5. Ndoc
6. Sand Castle
7. Araxis
8. Microsoft FxCop

Wednesday, February 13, 2008

The Response.Redirect Menace

You know how we all take things for granted and never bother to think of the caveats.... yep you know what I am talking about.... exactly... I ran into one such situation with Response.Redirect.

I have learnt that the Response.Redirect internally has to make a call to Response.End to force stop the execution of the current thread there by throwing a ThreadAbort exception [2].

The way this works is:

A call to HttpResponse.Redirect(string url) actually calls an overload HttpResponse.Redirect(string url, bool endResponse) with endResponse set to true. If endResponse is set to true, HttpResponse.Redirect will make a call to HttpResponse.End(). [1]

Microsoft recommends that we use the overloaded Response.Redirect(String url, bool endResponse) method that passes false so that a call to Thread.Abort() can be avoided by suppressing the call to Response.End. Is there a catch? Yes, the page will execute the code that follows Response.Redirect.

One solution I can think of to minimize the effort in execution of the code that follows the Response.Redirect is, actually code around the Response.Redirect

if(HaveToredirect == true)
{

Response.Redirect(url, false);
//as described in [1]
HttpContext.ApplicationInstance
.CompleteRequest();
return;

}

Check for the IsRequestBeingRedirected property of the Response object and return if it is true, in all the page events as the first step. This way we can mimimize the execution time of the page.

if (Response.IsRequestBeingRedirected == true)
return;

This approach might be feasible in all scenarios though.

Also note that Server.Transfer calls Response.End interally.

References:

1. Response.Redirect(url) ThreadAbortException Solution
2. Microsoft Support Article.

Monday, February 11, 2008

Commerce Server 2007 - Extending the PurchaseOrder

The purchase order table in CS 2007 comes with a limited default storage columns.
What if you want to add new columns to this table that would be used to hmmm...
lets say query the PO table. the answer is simple: Extend the PurchaseOrder !

Here is how I have dunit.

1. Extend the PurchaseOrder class (lets call it ExtendedPurchaseOrder and define the property that you would like to store in the Commerce Server PurchaseOrders table in the transactions database.

2. Add the new columns to the following section of OrderObjectMappings.xml

<Table Name="PurchaseOrders">

3. Change the name of the class from PurchaseOrder to ExtendedPurchaseOrder in the following section

<Class Name="PurchaseOrder">

4. Add the new class property to table column mapping in the following section of the same xml:

<ClassTableMap Class="ExtendedPurchaseOrder" Table="PurchaseOrders">

5. Add the following section to the web.config file in the CommerceServer/Types section

<Type Key="PurchaseOrder" UserTypeName="EtxendedPurchaseOrder" AssemblyType="Local" NameSpace="YourClassLibraryNameSpace" Assembly="YourClassLibrary"/>

6. Create a new folder; say c:\temp and copy web.config, OrderObjectMappings.xml, YourClassLibrary.dll and the OrderMappings.exe to this folder. You should be able to find the OrderMappings.exe in the C:\Program Files\Microsoft Commerce Server 2007\Tools folder.

7. Open a Command window and run the following script to generate the SQL for Commerce server Transactions database.

OrderMappings -w web.config

8. You should a file OrdersStorage.sql being generate if the above command ran successfully.

9. Execute the SQL script in the OrdersStorage.sql file on the Commerce server transactions database after you have made the necessary schema change to the PurchaseOrders table.

10. Now you are ready to programatically insert custom data into the PurchaseOrders table.

11. I have inserted the Order Confirmation Number into the PurchaseOrders using the following code

ExtendedPurchaseOrder PO = (ExtendedPurchaseOrder ) this.Basket.SaveToReceipt();
PO.ConfirmationNumber = 100001;
PO.ListenerStatus = 1;
PO.Save("Site");

References:
1. MSDN Online

SSL for testing in Development

I have found that SelfSSL is one of the best and easiest tool that can be used for SSL testing. This tool comes from Microsoft and it is free :)

How to get it?

Goolge "IIS 6.0 Resource Kit". Download and install it from microsoft website.

After you have installed you should be able to see SelfSSL.exe under Start > Programs > IIS Resources > SelfSSL >

Clicking on SelfSSL will launch a command window. Type the command SelfSSL and hit enter to install a self-signed certificate into IIS.

This will install the certificate on the default web site. You cannot install the same certificate on more than one site.

Now launch your site by typing https://localhost/ in a browser on your development server and voila you have already started testing SSL.

Supported Operating Systems: Windows Server 2003; Windows XP

Wednesday, January 30, 2008

State Management in ASP.NET

Web form pages are HTTP-Based, they are stateless, which means they don’t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost, therefore state management is really an issue in developing web applications. We could easily solve these problems in ASP with cookie, query string, application, session and so on. Now in ASP.NET, we still can use these functions, but they are richer and more powerful, so let’s dive into it.

Mainly there are two different ways to manage web page’s state

  • Client-side

  • Server-side

Client-side state management

There is no information maintained on the server between round trips. Information will be stored in the page or on the client’s computer.

1) Cookies

A cookie is a small amount of data stored either in a text file on the client's file system or in-memory in the client browser session. Cookies are mainly used for tracking data settings. Let’s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user information from cookies.

//to create a cookie variable
Response.Cookies["username"].Value=name;

//to access a cookie variable
Request.Cookies["username"].Value

2) Hidden Field

A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you would like to store directly in the page. Hidden field stores a single variable in its value property and must be explicitly added it to the page. ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.

protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;//to assign a value to Hidden fieldHidden1.Value=”this is a test”;//to retrieve a value string str=Hidden1.Value;

Note: Keep in mind, in order to use hidden field, you have to use HTTP-Post method to post web page. Although its name is ‘Hidden’, its value is not hidden, you can see its value through ‘view source’ function.

C. View State
Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don’t need to do anything about getting back the data of controls after posting page to the server. Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.

//to save informationViewState.Add(“shape”,”circle”);//to retrieve informationstring shapes=ViewState[“shape”];

Note: Unlike Hidden Field, the values in ViewState are invisible when ‘view source’, they are compressed and encoded.
D.Query Strings
Query strings provide a simple but limited way of maintaining some state information.
You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.

This is an article in its entirity has been posted on http://www.csharphelp.com/. I am reposting this on my blog since I feel it is very useful.

Reference:
1. http://www.csharphelp.com/archives/archive207.html

STANDARD TEMPLATE LIBRARY (STL)

CONTAINERS

String, List, Vector , Hash, Map, Multimap, Set,

String - #include
A string is a collection of ascii characters that supports both insertion and removal.

List vs Vector - #include "list" vs #include "vector"

Both of them can store collection of objects and work almost similarly.

Lists are double-linked lists. Where as a vector is sequential in memory like an array. Insertion at either end, or in the middle (providing you know an existing element in the middle) is equally fast. Also, splicing is fast (eg. putting a list into the middle of another) - all that does is re-arrange the end pointers. All of those operations would be slower with vectors, because you would need to copy everything. However, vectors shine in random access - since they are organised sequentially in memory, whilst this is slow for insertion at anywhere other than the end, you can easily find, say, element 500, you simply index into the vector. Thus, vectors can be sorted, shuffled, and accessed randomly.

Map - #include "map"
A collection for a varying length sequence of elements of type pair. The first element of each pair is the sort key and the second is its associated value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element. The key can be a simple as a number or string or as complex a key class. The key class must support normal comparison operations so that the collection can be sorted or searched.

Set - #include "set"
A collection that controls a varying length sequence of elements of type const Key. Each element serves as both a sort key and a value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element.

Multimap - #include "map"
A collection of a varying length sequence of elements of type pair. The first element of each pair is the sort key and the second is its associated value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element.

Multiset - #include
A collection of a varying-length sequence of elements of type const Key. Each element serves as both a sort key and a value. The sequence is represented in a way that permits lookup, insertion, and removal of an arbitrary element.


ALLOCATORS


Iterators

Iterators support the access of elements in a collection. They are used throughout the STL to access and list elements in a container. The iterators for a particular collection are defined in the collection class definition.

Monday, January 28, 2008

C# Copy Constructor

C# does not provide a copy constructor by default. We have to write an appropriate constructor method that will create a new object and to copy the values from an existing object. This implementation is nothing like the C++ copy constructor.

If we need a copy of an object we can use cloning techniques.

Observation:
This method has to be called explicitly.

Note: "A shallow copy creates a new instance of the same type as the originalobject, and then copies the non-static fields of the original object. If thefield is a value type, a bit-by-bit copy of the field is performed. If thefield is a reference type, the reference is copied but the referred objectis not; therefore, the reference in the original object and the reference inthe clone point to the same object. In contrast, a deep copy of an objectduplicates everything directly or indirectly referenced by the fields in theobject."

References:
1. MSDN Online

Generic Sql Table Data Insert Script

woah!!

I have my own blog and this is my first posting. hurray.... I have been shying away from doing this for a long time now... finally pulled all my energies to start blogging tech stuff that I learn ...

There is so much that I learn and so much I forget all the time.... It is getting really tough to keep track of all that I have learned.... I hope I can keep up with posting useful stuff that I learn.

enough of my preamble now... cutting the chase and getting to my post...

How many time must I have thought " I wish I had a script that I would run with the table name as an argument and get insert statements for all the data in a Sql Server 2000/2005 table." Thanks to Narayana Vyas Kondreddi, I have got a script [1] that does exactly what I want. This is a cool utility that is very handy.

To generate INSERT statements for table 'titles':
EXEC sp_generate_inserts 'titles'


References:
1. http://vyaskn.tripod.com/code.htm#tagit