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

:)