.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Wednesday, February 15, 2006

.Net Framework Tools Part 2

Type Library Importer (TlbImp.exe) and Exporter (TlbExp.exe)
Type library importer imports the type library information for a COM components into equivalent definitions in command language runtime library. This is useful when you want to use your legacy COM components with your new .Net application (think COM Interop). If you are someone like me who uses Visual Studio.Net, you can do this by adding a reference to the COM components from your IDE. For others, sample usage is:

tlbimp myTLB.tlb /out:myNet.dll

For more information on this tool goto: http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfTypeLibraryImporterTlbimpexe.asp

Type library exporter is opposite of importer, it is useful to create a type library for your .netr assembly. Again this is used in a COM interop scenario when your COM application (ex: your old VB 6.0 App) wants to use some new functionality that your developed using .Net ( I see this in lot of places where critical VB 6.0 apps still being used and new development moved to .net and this approach is usually part of the migration strategy)

Usage is:


tlbexp myNet.dll /out:myTLB.tlb

One important information to note here is that this tool creates the TLB but does not register it. For that you should use another tool (discussed next) , RegAsm.exe
For more information on this tool goto: http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfTypeLibraryExporterTlbExpexe.asp

Assembly Registration Tool (RegAsm.exe)
This tool reads the metadata within the .net assembly and creates the necessary information within the registery so that a COM client can consume services of a .Net component. This tool can optionaly create a TLB also. Afer you register your assembly using this tool, you can install it into Global Assembly Cache also so that it can be activated from any client. How do we do it? Use GacUtil.exe which will be discussed next :)

Usage for RegAsm.exe:

regasm myNet.dll
or when you want to create a TLB, use
regasm myNet.dll /tlb:myTLB.tlb

For more information on this tool goto: http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfAssemblyRegistrationToolRegasmexe.asp

Global Assembly Cache Tool (GacUtil.exe)
This tool is used to view and manipulate the contents of the Global Assembly Cache. Like we explained earlier, one use is to install new .net assembly into GAC. This can also be used to uninstall an assembly. Examples of simple usages are:

For install
gacutil /i myNet.dll


For uninstall
gacutil /u myNet.dll


For more information on the tool and its usage goto:http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfGlobalAssemblyCacheUtilityGacutilexe.asp

WinZip command line and unzip script

Winzip provides a command line add-on that you can use if you have a licensed version of WinZip. (For download goto: http://www.winzip.com/prodpagecl.htm ) This comes very handly when you need to unzip files from your program. In my case, I wrote a small VB Script file (scheduled to run using my scheduler as part of a batch job) . Below given is the script. it unzips to a specified directory, uses WScript and Shell object.



Option Explicit
On Error Resume Next

Dim oArgs
Set oArgs = WScript.Arguments
if oArgs.Count <> 2 Then
WScript.Echo "Usage: zUnzip <ZIP FILENAME> <PATH TO UNZIP>"
WScript.Quit
End if

Dim ZipFileName
Dim PathName
ZipFileName = oArgs.Item(0)
PathName = oArgs.Item(1)

'Unzip given zip file to specified path
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
Dim cmdScript
cmdScript = "%comspec% /c wzunzip.exe " & ZipFileName & " " & PathName
objShell.Run(cmdScript), 1, True

WScript.Quit



Some points worth mentioning,

objShell.Run(cmdScript), 1, True

In this command, second parameter for the Run Method is window style, if it is 1 it shows a window, use 0 for not showing the command window
Also note %comspec% /c in the command, this variable gets you the command interpreter for your OS, for example for Win2K, it gives you "cmd" and /C switch closes the secondary session after execution.

Cheers!

Thursday, February 09, 2006

commenting and trackback have been added to this blog.

Wednesday, February 08, 2006

.Net Framework Tools Part 1

Assemly Linker (Al.exe)


In .Net, basic (versionable) entity is an assembly. This is nothing but a collection of classes presented as DLLs or EXE file. When it is DLLs you can call it as components and when it is EXEs you can call it application. But in both the cases it is stored in disk as portable executables (PE) and loaded on demand. Further more, assemblies can be private assemblies used by a single program or global assemblies that are shared by many programs. You can use AL.exe to create a multi module assembly. The Assembly Linker generates a file with an assembly manifest from one or more files that are either modules or resource files. A module is a Microsoft intermediate language (MSIL) file that does not have an assembly manifest.

Example> al /t:library /out:bin\Linked.dll bin\One.dll bin\Two.dll

For more information on Al.exe goto: http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfAssemblyGenerationUtilityAlexe.asp


Asp Net IIS Registeration Tool (Aspnet_regiis.exe)

The ASP.NET IIS Registration tool allows you to update the script maps for an ASP.NET application to point to the ASP.NET ISAPI version associated with the tool. If your machine has multiple versions of .Net Framework installed, run it from the sub-directory of the version you want to install. This tool should be used when you install your OS (like Windows XP) and IIS first and then you install your .Net Framework. Also use this tool to Install the client-side
scripts for ASP.NET, such as client-side validation scripts, to the aspnet_client subdirectory of each IIS site directory.

To install ( for the current version)


C:\WINNT\Microsoft.NET\Framework\v1.1.4322> aspnet_regiis -i


To copy/install client side scripts

C:\WINNT\Microsoft.NET\Framework\v1.1.4322> aspnet_regiis -c

For more information on this tool goto: http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfASPNETIISRegistrationToolAspnet_regiisexe.asp


Code Access Security Policy Tool (Caspol.exe)

The Code Access Security Policy tool(Caspol) helps your to modify security policy for the machine policy level, the user policy level, and the enterprise policy level. Usage varies on what you want to do,

For more information goto: http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfCodeAccessSecurityPolicyUtilityCaspolexe.asp
Here is a link to a
good article by David Myers on configuring code security (http://www.15seconds.com/issue/040121.htm)


Cetificate Manager (CertManager.exe)

The Certificate Manager tool manages certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs). This is a useful tool if you are dealing with secure site and developing using VS.Net against a remote server where SSL certificate is installed. In this particular case, you should instruct your Visual Studio (using IE security) to trust your remote web server
as a trusted publisher. You can use CertManager to do this (or use IE Admin tool),


C:\WINNT\Microsoft.NET\Framework\v1.1.4322> certmgr.exe -add
yourcert.cer /r/s localMachine local_machine\Root

C:\WINNT\Microsoft.NET\Framework\v1.1.4322> certmgr.exe -add
yourcert.cer /r/s localMachine ;ocal_machine\TrustedPublisher\


For more information on this tool goto:
http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfCertificateManagerToolCertmgrexe.asp

Contd...

Monday, February 06, 2006

Forgot that connection string?

Goto http://www.connectionstrings.com/. You will find connection strings to almost all the possible data sources.

Cheers!

Friday, February 03, 2006

Content Syndication using Dynamic Javascript

In the
previous post
we saw how to use RSS to syndicate your web content. If you want to syndicate your
content for other web sites, this method demand work from the consumer work site in terms of reading
the feed and interpreting it. An alternate method, is content syndication using dynamic javascript.

This example show you how,
The site that consumes your content will include a block of script like this where ever they want your
content to be shown,


<SCRIPT SRC="http://www.directkerala.com/syn/js.aspx?js=y"> </SCRIPT>


When the webpage is rendered it calls this page in your web site to render the content. In your
web site ( In our example, js.aspx ), you will add code similar to this,



private void Page_Load(object sender, System.EventArgs e)
{
if (Request["js"] == "y")
{
Response.ContentType = "application/vnd.javascript";
Response.Write ("document.write('");
Response.Write ("<a href=http://www.directkerala.com><img border=0 src=http://www.directkerala.com/images/dklogohome.jpg>");
Response.Write ("</a>')");
Response.End();
}
}



Please take a note of the MIME[Content] type here, it is set as "application/vnd.javascript". This will enable dynamic
javascript and your "document.write" will write the html you have embedded within. This is a very effective way of providing
content and attracting users to your site.

Content Syndication using RSS

RSS is a popular format for syndicating content over the web. As a website owner, you attract more repeat customers to your site if you allow the users to consume your content using content aggregation technology like RSS. At the users end, they can use a feed aggregator or any RSS Reader software to read your published content.

Here is the Wiki definition of RSS,

RSS is a family of XML dialects for Web syndication used by (among other things) news websites and weblogs. The abbreviation is used to refer to the following standards:

  • Rich Site Summary (RSS 0.91)

  • RDF Site Summary (RSS 0.9 and 1.0)

  • Really Simple Syndication (RSS 2.0)


The technology of RSS allows Internet users to subscribe to websites that have provided RSS feeds; these are typically sites that change or add content regularly. To use this technology, site owners create or obtain specialized software (such as a content management system) which, in the machine-readable XML format, presents new articles in a list, giving a line or two of each article and a link to the full article or post.


Since Netscape's creation of original version of RSS ( ver 0.90 ), it has gone through many
revisions. (0.91, 0.92, 0.93, 0.94...1.0 and now 2.0). The format of RSS 2.0 looks like this,

<rss version="2.0" xmlns:dc="http://directkerala.com/ns/">
<channel>
<title>DirectKerala.com</title>
<link>http://www.directkerala.com/</link>
<descriptionvDirect Kerala is Kerala's no.1 portal</description>
<item>
<title>Movie Review - Rajamanikyam</title>
<link>http://www.directkerala.com/movies/rajamanikyam.aspx</link>
<description>Mammootty’s Midas touch- Rajamanikyam....</description>
<dc:creator>DirectKerala</dc:creator>
<dc:date>2006-02-02</dc:date>
</item>

</channel>
</rss>

Here is a sample ASP.Net program that shows you how to create your own RSS Feed.
In this example, I have a page named rss.apsx , and the following is code for its Page_Load


private void Page_Load(object sender, System.EventArgs e)
{
Rss r = new Rss();
DataSet ds = GetData();
r.OutputStream = Response.OutputStream;
r.RssTitle = "DirectKerala.com";
r.PublisherUrl = Request.Url.Host;
r.Description = "DDirect Kerala is Kerala's no.1 portal";
r.Copyright = "Copyright (C) Direct Kerala Online Services (P) Ltd, DBA DirectKerala.com.";
r.Generator = "DirectKerala.com RSS Generator";
r.ItemSource = ds;
r.ItemTitleField = "ListCaption";
r.ItemDescriptionField = "ListDesc";
r.ItemPublicationDateField = "ListStartDate";
r.ItemUrlField = "ListingCode";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/xml";
Rss.PublishRss(r);
Response.End();

}


GetData() is the function that gets me the data that need to be publised. The DataSet returned has fields like "ListCaption", "ListDesc",... etc. Make sure that the content type is set to text/xml and Rss.PublishRss() method will write the data in RSS 2.0 format to the Response stream.

To be Contd....

Thursday, February 02, 2006

Ajax using Xml Http

These days everybody is talking about Ajax, every product vendor is trying to make their UI products Ajax enabled. Some of the technologies and techniques related to this new buzzword existed for a long time in the form of Remote Scripting (Microsoft), XmlHttp request, etc. Let us here take XmlHttpRequest and examine its features to build our own "Ajax" example. This is how Ajax is defined in Wikipedia...

Asynchronous JavaScript And XML, or its acronym Ajax, is a Web development technique for creating interactive web applications. The intent is to shift a great deal of interaction to the Web surfer's computer, exchanging data with the server behind the scenes, so that the entire Web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page's interactivity, speed, and usability. The Ajax technique uses a combination of:


  • XHTML (or HTML) and CSS for marking up and styling information.
  • The DOM accessed with a client-side scripting language, especially ECMAScript implementations like JavaScript and JScript, to dynamically display and interact with the information presented
  • The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in some situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server. XML is commonly used as the format for transfering data, although any format will work, including preformatted HTML, plain text, JSON and even EBML.

Setup:
I have an ASP.Net page (1.aspx) in my TestApp under http://localhost. What we are trying to do here is to have a listbox and a hyperlink on that page. When you click on that hyperlink, we do a XmlHttp call to server side (without re-posting page) get some data element and paste it to the list box. Simple as that ! In this example, server side is simply passing a text element every time it gets a call. To extend you can use custom query string params to get some keys, go to database, grab some data, format it as xml ( yes it is a requirement ) and pass it to the calling client. Here is the sample code and explanation: ASP.Net page,


<asp:ListBox id="myList" runat="server"> <asp:HyperLink
id="ClickMe" runat="server" NavigateUrl="javascript:clickMe();">Click Me to
Add</asp:HyperLink>



And now paste this javascript code to your page's HEAD section,

var xmlReq=null;
function clickMe(){

var url = "http://localhost/TestApp/1.aspx?x=y";
xmlReq=getXmlHTTP();
if(xmlReq)
{
xmlReq.onreadystatechange = ReadyStateChangeHandler;
xmlReq.open("GET", url, true);
xmlReq.send("");
}


}

function ReadyStateChangeHandler() {

if (xmlReq.readyState == 4) {
// Http "OK"
if (xmlReq.status == 200) {
//do your processing here !
//alert (xmlReq.responseXML.xml);
var str = xmlReq.responseXML.firstChild.text;

var lst = document.getElementById("myList");
var optionObject = new Option(str,str);
var optionRank = lst.options.length;   
lst.options[optionRank]=optionObject;

} else {
alert("Error retreiving data\n" + req.statusText);
}
}
}
function getXmlHTTP(){
if(typeof XMLHttpRequest!="undefined"){
return new XMLHttpRequest();
}
else if(typeof ActiveXObject != "undefined")
{
try{
var xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}
catch(e)
{
return null;
}
}
return null;
}

Now here it needs some explanation, we use a global variable xmlReq to hold the instance of XmlHttpRequest object,
we create that object, call the server side URL with a quesry string element ?X=y to denote it is an XmlHttp call,
and call Send method of XmlHttp object. Notice that we set the call back handler function for onreadystatechange event.

Some of the important properties of XmlHttpRequest are:




























Property
Description
onreadystatechange Event handler for an event that fires at every state change
readyState Object status integer:

0 = uninitialized

1 = loading

2 = loaded

3 = interactive

4 = complete
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
status Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusText String message accompanying the status code


And here is my simple server side code, (for 1.aspx )

private void Page_Load(object sender, System.EventArgs e)
{
if (Request["x"] == "y")
{
Response.ContentType = "text/xml";
Response.Write("" + "Hello from Server Side Code" + "");
Response.End();
}
}


When you run this simple sample, you will see each time you click on that link, a text message "Hello from Server Side Code" will be added to the list/select box. And all this without having to do reload of the page !!!

Wednesday, February 01, 2006

Accessing a Secured Web Service

My setup:
My web application uses Basic Authentication (SSL enabled). This application consumes
a web service which is under Basic Authentication as well. I am using Visual Stuio.net to develop.

Since I am using VS.Net, it is easy to start using the web service, you click on Add Web Refrerence,point it to the web service url (http://myserver/mywebservice/service.asmx). At this point VS.Net creates your proxy class in built with the mechanism to talk to your web service. You are all set,
You are ready to can access your web methods now!

Now only small challenge I faced here is around the authentication. When I initially called my web method, it threw me an HTTP Error 401:Authorization Required. Ofcourse, I was not passing any authentication credentials to the web serive (which BTW uses Basic Authentication).

So I changed my code to add these two lines,

proxy.PreAuthenticate = true;
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;


before the actual call is made. Still no luck, why? I overlooked the fact that passing DefaultCredentials works only for NTLM and Kerberos (Windows Authentication).

Now at this point, I want to stress the importance of PreAuthenticate Property.
It is important to set this to true when dealing with a secured web service.
According to Microsoft

The proxy's PreAuthenticate property can be set to true or false.
Set it to true to supply specific authentication credentials to cause a WWW-authenticate HTTP header to be passed with the Web request. This saves the Web server denying access on the request, and performing authentication on the subsequent retry request.



So I changed my code again,

MyWebService proxy = new MyWebService();
string pwd = HttpContext.Current.Request.ServerVariables["AUTH_PASSWORD"];
string uid = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
NetworkCredential nc = new NetworkCredential(uid,pwd,"mydomain");
proxy.Credentials = nc;
proxy.PreAuthenticate = true;

and make the call !

With this change it all started working, I am getting the user id and password from my application that has already authenticated the user, create a credentical and pass it to the web service.

:)

Tuesday, January 31, 2006

HTTP 500 - Internal server error

This is no fun message ! When you get this message, a simple restart of W3 services might fix your issues. When you are dealing with ASP.net, some time you end up installing asp.net on your server again ( aspnet_regiis -i from your current framework version sub directory ), in my case, it showed up for no "apparent" reason ( server: Win 2k, .NET 1.1 ). Server Event log showed this message,
Source: DCOM
Error: DCOM got error "Logon Failure: unknown username or bad password" Unable to logon .\IWAM_SERVERNAME in order to run the server.



Source: W3SVC
Error: "The server failed to load application '/LM/W3SVC/1/Root/op.' The error was 'The server process could not be started because the configured identity is incorrect. Check the username and password.


I did some basic test pages ( both aspx and asp ) and found out that both the pages were not serving from the server. (html pages were ok).

After some research (read Googling:) this is what I found out,
"Configured Identity Is Incorrect for IWAM Account!!"
and what you need to resolve this issue is to sync up IUSR and IWAM accounts in IIS metabase. I followed the steps in this MS KB article and the issue was resolved.

http://support.microsoft.com/default.aspx?scid=kb;%5BLN%5D;Q297989

Tuesday, January 24, 2006

"Server Application Unavailable"

All of a sudden, this big scary message showed up ! Application Event Log showed more details like,


"aspnet_wp.exe could not be launched because the username and/or password supplied in the processModel section of the config file are invalid.
aspnet_wp.exe could not be started. HRESULT for the failure: 80004005
"...


If you get this error, this link might shed some light on the issue,
http://support.microsoft.com/default.aspx?scid=kb;en-us;315158

In my case, it was much simpler issue, my ASPNET account (Win 2K Server) was locked out ! (dont have a clue how that happened !!)

Thursday, January 19, 2006

Server.Transfer and Page to Page data exchange

When you are using Server.Transfer to transfer control from one page to another page within the same HttpContext, you can use Context property of Current (http context) to get a handle of the parent page. Once you have that you can access properties (public) of that page. Key thing to remember is that all ASP.Net pages are classes! (derived from mama Page Class )

Here is a simple illustration:

Your first page:

public class FirstPage: System.Web.UI.Page
{

public int MyInt
{
get
{
return (1);
}
}

}

Your second page:

public class SecondPage: System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
int myParentInt;
FirstPage myParentPage;
myParentPage = (FirstPage)Current.Handler;
myParentInt = myParentPage.MyInt;



}
}

Friday, January 06, 2006

More File and Directory Stuff !

Level: Beginner

In general, when you want to do anything related to Files and Directories, the namespace
of interest is System.IO. And most of the file and directory operations can be done using
one or combination of DirectoryInfo, Directory, FileInfo, or File class. Here is some common
tasks and one of many ways to do those...

1) Check if file exits :

FileInfo file = new FileInfo("filename.txt");
if (file.Exists)
{//file exists}


2) Check if directory exists:
Similar to the one before,
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{ // dir exists }

3) Create a Directory
DirectoryInfo dir = new DirectoryInfo(path);
if (!dir.Exists)
{ dir.Create(); }

Using the same class, you can get the attributes, number of files present (dir.GetFiles().Length.ToString())
and more...
4) If you want to change the attribute of a File, you can do so like this...

FileInfo file = new FileInfo("my.txt");
// This adds just the read-only attribute.
file.Attributes = file.Attributes FileAttributes.ReadOnly;

// This removes just the read-only attribute.
file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;


5) To read or write a text file, use a StreamReader and a StreamWrite classes
To create a new file,
FileStream fs = new FileStream("my.txt", FileMode.Create);
6) Find files with of a certain type:
FileInfo[] files = dir.GetFiles("*.xml");
GetFiles() method takes an argument where you can specify the type.


Can you think of more uses, samples...post on comments...Thanx :)

VS.net project, accessing from Network Share !

Level: Intermediate

If you place your VS.Net projects (Windows App) in a network share and try to work off that share, you might end up with an error message like this "The project location is not fully trusted by the .NET runtime". This message pops up when you try to open the project file. If you say Ok, to that "long" message and continue working you might end up with some security permissions issue when you try to debug. (In my case, I was trying to open a file using StremReader and it threw an Security Exception !)

In order to successfully run the projects, you will need to play around a bit with .Net configuration tool. Launch mscorcfg.msc (you should be able to find this under your current version of .Net Framework dir)

Under My Computer > Runtime Security Policy, you can either add a new code group and give "Full Trust" permission for the URL(File/Http) or you can use the adjust the security policy link, give Full Trust to Local Intranet.

Try one or the other and see what works for you !

Tuesday, December 27, 2005

Listing Files in a Directory using .Net

Level: Beginner

DirectoryInfo class is useful for creating, moving, and enumerating through directories and subdirectories.

for example, you can make a new directory like this,

DirectoryInfo di = new DirectoryInfo(@"c:\TestDir");
if (!di.Exists)
di.Create();


FileInfo class provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

Here is a simple code snippet to list all files in a given directory (example takes a directory path as input and returns an array list of files)

private ArrayList GetFileList(string inputDir)
{
ArrayList fileList = new ArrayList();
DirectoryInfo di = new DirectoryInfo(inputDir);
//GetFiles method accepts filter patterns like "*.xml"
FileInfo[] fArray = di.GetFiles("*.*");

foreach(FileInfo fi in fArray)
{
fileList.Add(fi);
}
return (fileList);

}

Friday, December 23, 2005

Random Image Rotator with CSS and ASP.Net

Level: Intermediate

For my header image I have defined something in CSS like this,
#pic { BACKGROUND: url(pic.jpg) repeat-x; }.
This works fine for a static image. If you want to rotate your image, you will need to dynamically grab that image to get there. ( Google this need, and you will find a lot of pages with PHP solution ). Here is what you do in .Net to rotate images with CSS !

Your CSS file will change to reflect the ASPX page now serving the images,

#pic { BACKGROUND: url(http://localhost/imgPick/pick.aspx) repeat-x; }

And here is the code that goes to page load of pick.aspx

private void Page_Load(object sender, System.EventArgs e)
{
string imagePath = GetRandomImageFileName();
//Open the image file
System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath, true);
Graphics graphic = Graphics.FromImage(image);


//To draw some text on that image !
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
float x = 150.0F;
float y = 50.0F;
graphic.DrawString("dotNetCouple :)", drawFont, drawBrush,x,y);

//Switch page output type to "jpg"
HttpContext.Current.Response.ContentType = "image/jpg";
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg );
//Write the image from memory to the response stream
stream.WriteTo(HttpContext.Current.Response.OutputStream);


}

private string GetRandomImageFileName()
{
Random random = new Random();
int arrIndex = random.Next(0, 2);
//I have an array of 3 images here!
//change this routine to your suite your needs !
string[] imgNames = new string[]
{
@"c:\binu\html\css\pic.jpg",
@"c:\binu\html\css\pic1.jpg",
@"c:\binu\html\css\pic2.jpg"
};
return (imgNames[arrIndex]);

}

and your HTML could look like this,


Some Text, This text will still be shown if there is no image served !



put all these together, and there you have it, a CSS based image rotator.

Tuesday, December 20, 2005

HTTP 502 Error while downloading exe from website

Level: Beginner

Have you ever got HTTP 502 error or CGI error while trying to download an exe from an IIS 5.0/ASP website ? If yes, it is worth checking "Execute Permissions" on that virtual directory. If the permissiona are set to "Script Only" then the executable files are treated like static HTML files and when try to access with a link like this, download of the file will start. If this is set to "Scripts and Executables" it will think that you are trying to execute the exe and will end up in HTTP 502 or CGI error in IIS!

Monday, December 19, 2005

Validating XML using XMLValidatingReader

Level: Beginner

You can use XmlValidatingReader class to validate an cml file against an XSD schema, Here is the code snippet to do it,



XmlSchemaCollection schemaCol = new XmlSchemaCollection();
schemaCol.Add("",schemaFile);
XmlTextReader textReader = null;
XmlValidatingReader vReader = null;
try
{
textReader = new XmlTextReader(xmlFile);
// create a validating reader.
vReader = new XmlValidatingReader(textReader);
// validate using the schemas stored in the schema collection.
vReader.Schemas.Add (schemaCol);
// set the validation event handler
vReader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// read and validate the XML data.
while (vReader.Read()){}
}
catch (Exception ex)
{
return (false);
}
finally
{
// close the readers

vReader.Close ();
textReader.Close ();
}


And your Event Handler to handle the validation callbacks,

private void ValidationCallBack (object sender, ValidationEventArgs args)
{
this._xmlFeedValid = false;
}



Access Denied Error with MSXML 4.0 SP2

Level: Advanced

If you have recently updated your MSXML 4.0 with SP2 and started getting an "Access Denied" error, then read on...
According to this Microsoft article, Security in the implementation of the MSXML 4.0 SP2 ServerXmlHttp object has been enhanced to check the Internet Explorer security policy setting for submitting non-encrypted form data.

Follow these steps to configure IE Security,


1. Click Start, click Run, type mmc, and then press ENTER.
2. On the File or the Action menu, click Add/Remove Snap-in.
3. In the Add/Remove Snap-in dialog box, click Add.
4. On the Standalone tab, click Add. In the Available Standalone Snap-in dialog box, click Group Policy , and then click Add. The Group Policy Wizard appears.
5. In the Group Policy Wizard, Click Finish
6. Close the Add Standalone Snap-in window by clicking the Close button
7. Click OK in the Add/Remove Snap-in dialog box.
8. Under User Configuration, expand Windows Settings, expand Internet Explorer Maintenance, and then click Security.
9. In the right pane, double-click Security Zones and Content Ratings.
10. Under Security Zones and Privacy, click Import the current security zones and privacy settings, and then click Modify Settings.
11. Select the zone that you would like to modify, and click Custom Level
12. Modify the settings to enable the Submit nonencrypted form data option by selecting the enable radio button for that option. If it is already enabled, then just click the OK button. The zone where the setting should be enabled is determined by the zone where the target URL of the POST operation is classified. For example, when you post to an Internet URL, you must enable this option for the internet zone.
13. Restart the process that is running ServerXMLHTTP. To do this, you may have to restart your computer.

Friday, December 16, 2005

Creating DataSet from XML and XSD

Level: Beginner-Intermediate

If you want to read your XML file into a DataSet, you could use the ReadXml method of the DataSet. You can read the XSD for the same XML file using ReadXMLSchema method. Here is how to use these methods,


string doc = @"c:\test.xml";
string docSchema = @"c:\test.xsd";
XmlDataDocument myXmlDataDocument = new XmlDataDocument ;


We will use a StreamReader to read the schema file,

StreamReader reader = new StreamReader(docSchema);
//this will read the schema to DataSet
myXmlDataDocument.DataSet.ReadXmlSchema(reader);


[do not forget to close the StreammReader in your actual code]

//this will read the XML
myXmlDataDocument.Load(document);


DataSet also has a ReadXML method you can use to read the XML. This method can be used instead of XMLDataDocument's Load method. ReadXML method takes a second parameter that specifies XMLReadMode [enumeration].
Read more about this on MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatasetclassreadxmltopic.asp

All these methods works well with simple XML and XSD. In my experience, if you have many complex types and relations in XML/XSD, ReadXMLSchema method gives undefined error! on some types [native and sometimes derived!] and subsequently Load fails!!