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

Monday, October 23, 2006

Create a Printer friendly page for DataGrid

For one of my projects, user needed a feature where they could print out their search results (shown in a datagrid). The following steps builds a printer-friendly page for datagrid results.

1. Add a new aspx page, call it Print.aspx
2. Add javascript to trigger IE print, on body load,


--body onLoad= "self.print()" --





--body--


3. Now comes the data, pass the underlying datasource for the grid to this page (use the method you like, use a session variable (bad), use a unique keyed cache item (ok), get it from parents property (good). Once you have this data, the following code block does the trick. Key is the RenderControl method of datagrid. It uses a HtmlTextWriter object to write out the HTML snippet of the grid. If we create the grid with plain vanila settings for color and edges, it will be "printer friendly".

On Page load add (don't forget to pass the dataview,

Response.Write(CreatePrinterFriendlyPage(dview).toString());


private StringBuilder CreatePrinterFriendlyPage(DataView dv)
{

DataGrid dg = new DataGrid();
dg.DataSource = dv;
dg.HeaderStyle.Font.Name = "Arial";
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.Font.Size = FontUnit.XSmall;
dg.ItemStyle.Font.Name = "Arial";
dg.ItemStyle.Font.Size = FontUnit.XXSmall;
dg.DataBind();

System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
dg.RenderControl(hw);

StringBuilder sb = new StringBuilder();
sb.Append (tw.ToString().Replace("\"","'").Replace("\r","").Replace("\n","").Replace("\t",""));

return (sb);

}


Happy coding !

Monday, October 02, 2006

System.Data.OracleClient requires Oracle client software version 8.1.7 or greater.

I was trying to use OracleClient namespace for the first time, I wrote my first line of code...to try to connect to a Oracle db, and got this error!!
"System.Data.OracleClient requires Oracle client software version 8.1.7 or greater."
Misleading....beacuse I know that I have ver 9.2 installed!
Luckily, Google is there to help, issue is related to permissions! and the solution is goven in this good blog post by Roy Tore Gurskevik,
http://www.dotnetjunkies.com/WebLog/rtgurskevik/archive/2005/01/19/45958.aspx

Tuesday, August 08, 2006

For ASP.Net Developers

Check out this article by Jeff Prosise,
Keep Sites Running Smoothly By Avoiding These 10 Common ASP.NET Pitfalls

A must read !

ADO.Net and Sybase ! Strange behavior !

This is what I see, may be there is something that I don't see !
I am using .Net v1.1, Sybase db ver 12.5 with Sybase ASE OleDb Provider Ver 2.70.
When I create parameters for my command (CommandType is StoredProcedure), it expects me to create the params in the same order as specified within the stored procedure. I am creating the params using names and not by ordinal! There is no error thrown even when the params are in different order, values simply gets assigned to the wrong params !!

Did any one of you have seen similar issue ??

Thursday, June 01, 2006

Infragistics Net Advantage 2005 Vol 3 - Tips and Tricks - Part 1

1) For development, always install the complete product, dont try to copy the Infragistics assemblies script files manually to set up your dev machine. A proper install will make sure that the components are added to your VS.Net IDE toolbox. If your install fails to do this, there is a command line utilty provided (available from Infragistics Program Group) with the product that will add VS.Net toolbox tab.
If you are upgrading Infragistics from an older version to newer version, make sure to upgrade your project files using .Net Project Upgrade Utility (also found in Infragistics Program Group). Make sure that you have all the latest hot fixes applied (to avoid nasty surprises). A complete installation will also install
help files, regsiter them propery, it also comes with a nice Samples Browser with a lot of working samples.

2) First time when you starting your development with Infragistics, (for example UltraWebgrid), you set your references to the required assemblies, dragged the control on to your form and ran it. If you get a runtime error pointing to missing "BorderStyle" class/namespace reference, you probably need to set "CopyLocal" property for the WebUI assembly to True. To do this locate Infragistics.WebUI.Shared.v5.3, right click and Properies, set CopyLocal to true.

3) Infragistics provides you a very rich UI experience. How does it do it? It uses a mix of client side javascripting and server side programs. Infragistics comes with a neat collection of client side javascript library for each of its controls. This provides rich client side features. It is AJAX enabled, and makes out-of-band calls to server to load data when the control's properties are set to use that feature. When you intsall the product (example: Ver 2005 Vol 3)
you will notice that a virtual directory named "ig_common" is created for you. This virtual directory hosts the required javascript files and other resources that are required for running Infragistics controls.

4) Discussion of the previous point leads us to the deployment of applications that uses Infragistics, For a simple deployment follow these steps,

  • Copy the Infragistics Assemblies that are used by your application to a install folder in your server. These are signed assemblies. Add these to Global Assembly Cache (GAC).

  • Copy the directory that is pointed by ig_common virtual directory in your dev
  • Create a virtual directory in your server, point it to the folder explained in the previous step.

  • Build your application that uses Infragistics, deploy it to the server ( which ever way you choose, xcopy, copy project..)



5) Page.SmartNavigation - Set this to False from design view. I have seen many developers complaining about this feature in v1.1. Setting this property to true is not recommended (so I was told by Infragistics Support once!)when your page has Infragistics components. If you want to preserve the scroll position on your page use some Javascript technique.

6) UltraWebGrid - Simple Binding - Works pretty much the same way as a regular ASP.Net grid. Please remember that UltraWebgrid can have multiple bands (virtual grids within grid) and columns collection is within the Band. Another important property is DisplayLayout. Most of the UI elements are defined within this. If you are binding the grid on the fly relying on the underlying datasource for columns, Set DisplayLayout > AutoGenerateColumns to True. You can also choose to add columns design time, setting the data field names for each columns, in that case set AutoGenerateColumns to False.

Example:

myGrid.DataSource = myDataSet.Tables[0].DefaultView;
myGrid.DataBind();

Once the DataBind() is done, the grid fires "InitalizeLayout" event. This is one event you can hace code to handle some useful
properties of the grid. This can be a good place to handle setting the column widths, making some columns hidden, setting "keys"
for columns, turning on/off sorting for columns, handling header captions and style to name a few.


//Do not forget to import the namespace
using Infragistics.WebUI.UltraWebGrid;
using Infragistics.WebUI.Misc;
:
:
//Examples of setting keys for columns; you can use the key to grab handle to this column
myGrid.Bands[0].Columns[0].Key = "Check";
myGrid.Bands[0].Columns[1].Key = "Id";

//Setting Align
myGrid.Bands[0].Columns[0].CellStyle.HorizontalAlign = HorizontalAlign.Center;

//Setting width
myGrid.DisplayLayout.Bands[0].Columns[0].Width = Unit.Pixel(30);

//setting click action on header
myGrid.DisplayLayout.Bands[0].Columns[0].Header.ClickAction = HeaderClickAction.NotSet;

//Setting Header Caption
myGrid.DisplayLayout.Bands[0].Columns[0].Header.Caption = "My Caption";

//set sort for all bands and columns of the grid to "No Sort"
myGrid.DisplayLayout.HeaderClickActionDefault = HeaderClickAction.NotSet;



More coming sooon....

Thursday, May 25, 2006

HOWTO: Get rid of " Could Not Establish Trust Relationship with Remote Server" error

If you are getting this error " Could Not Establish Trust Relationship with Remote Server" when trying to access a webservice secured by SSL, then read on. One possible issue might be that you do not have a SSL Certificate isssued by a trusted Certification Authority(CA). (Another case of error is explained in this Microsoft Article: http://support.microsoft.com/?scid=kb;en-us;823177). For both these instances workaround given in MS article is a possible solution. It is simple to implement, add this class that implements ICertificatePolicy and add this line of code before you call your web service.

System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();

Code for the class is given below,

using System.Net;
using System.Security.Cryptography.X509Certificates;

public class MyPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint
, X509Certificate certificate
, WebRequest request
, int certificateProblem) {

//Return True to force the certificate to be accepted.
return true;

} // end CheckValidationResult
} // class MyPolicy


You could also check for specific errors/warnings in the CheckValidationResult method, in the above given example, it overrides any error!

Happy coding:)

Tuesday, May 16, 2006

Attention!!! all Infragistics Net Advantage Users

If you are using Infragistics Net Advantage 2005 Vol3, get the latest Hot Fix on this version and apply it now! if you haven't done it yet. This hot fix is out there for a while now, but if you have purchased the product from one of those re-sellers, then the media they sent you do not have any hot fixes. Goto to www.infragistics.com, register your product and get the hot fixes!


This hot fix fixes at least couple of issues I have encountered,

  • Infragistics script library code (js code) going into indefinite loop resulting in your web server going toast! This happens when you are doing add/edits directly into the UltraWebgrid...When this happens your CPU just peaks to 100% all eaten by your iis process

  • Again, Utrawebgrid eating all the memory when it is heirarchial and paging is enabled..(I am not sure about the sequence to re-produce the error!!)



So....Apply the hot fix! and keep coding ;-)

Cheers!

Visual Studio.NET - Web Reference Static v/s Dynamic

Visual Studio makes it very easy to create and consume web services. This note explains how to set up the references to consume a web service with Visual Studio.NET.


In order to start using a web service, you should make a reference to this from Visual Studio,to acheive this,

  • On your VS Solution Explorer, select your project, expand to References,Right click and click on Add Web References

  • Type in URL of your web service and click on Go

  • This will bring up your Web service's wsdl, you can change your web reference name to anything you want and click on Add Reference


Thats it, at this point, Visual Studio does all the work required (like creating your proxy class) and you are set to call your web service's web methods.


Now for some important and interesting observations!


The web reference you just created is a static reference, meaning it is always linked to the web service URL you just typed in. You can verify this by right clicking on your web reference to view the property sheet. You will notice that the URL Behavior is set to "static" with the Web Reference URL pointing to the URL you typed in. This is fine as long as you have only one environment (to TEST,QA,Stage, PRoduction....). But when you have to move your application through various environments in its life cycle, you will need to change this reference and rebuild the application. This leads us to the URL Behavior of "dynamic", when dynamic is set, your refrence.cs file (proxy) will include a property to read the URL from a Config File.


Code will look something like this...



public MyWebReference() {
string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["MyWebRef"];
if ((urlSetting != null)) {
this.Url = string.Concat(urlSetting, "");
}
else {
this.Url = "http://myWS/myWS.asmx";
}
}




Depending on the type of Visual Studion Project your web service client is, it works slightly different,

  • If your app is a web application and making the web reference from your application, this App Setting entry will go into its web.config file

  • If your app is windows application, making a dynamic reference will create an app.config entry and when built will be part of your app.exe.config

  • If you are referencing web service from a Class library project, the entry should be made to the client of that class library, if web project is using this class library then entry should be in web config or if its a win app using the class library, app setting entry will goto app.config!




Happy coding !!


Cheers!

Thursday, May 04, 2006

Response.Redirect not working in server?

[ASP.Net] Have you ever had an instance where your Response.Redirect calls are not working when you moved your code to remote server (every thing worked well in your local machine), first thing you check is your Page's SmartNavigation settings. If you have turned on your SmartNavigation (in v1.1) this might give problems with your Response.Redirect ( Server.Transfer will work ).

As a work around, set your SmartNavigation to false, before calling Response.Redirect

Page.SmartNavigation = false;
Response.Redirect("yourpage.aspx");

Wednesday, April 12, 2006

Convert String to Proper Case / Title Case

Proper case/ Title case = First letter of every word is capitalized.
In VB 6.0, we use StrConv() function to convert to proper case.



1 Dim stringVariable as String
2 stringVariable = "hello world"
3 stringVariable = StrConv(stringVariable,vbProperCase)
4 Debug.Print stringvariable 'Prints Hello World



In VB.Net, we could still use the same function, use the Microsoft.VisualBasic Namespace.

1 Dim stringVariable as String
2 stringVariable = "hello world"
3 stringVariable = StrConv(s,VbStrConv.ProperCase)
4 System.Diagnostics.Debug.Writeln (stringvariable) 'Prints Hello World


If you are using c#, you could use the same technique, only point to note is that you will need to pass the locale ID to the StrConv() function (optional param is not possible)

1 string stringVariable = "hello world";
2 stringVariable = Strings.StrConv(s,VbStrConv.ProperCase,new CultureInfo("en-us").LCID);
3 System.Diagnostics.Debug.Writeln (stringvariable); //Prints Hello World


A little more elegant solution is to use TextInfo class to achieve the same.
C# code is shown below,

1 string stringVariable = "hello world";
2 stringVariable = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Input.ToLower());
3 System.Diagnostics.Debug.Writeln (stringvariable); //Prints Hello World

Happy Coding!
Cheers!

Tuesday, March 28, 2006

How to find out which webcontrol generated postback?

There will be instances where this information could come handy. You are doing some action specific to a control on postback and don' t want that to happen when postback happens because of some other control. Trick to figure out this is to understand how ASP.Net postback works. When ASP.Net renders HTML, it creates a block
of Javscript that looks like this,

1 function __doPostBack(eventTarget, eventArgument)
2 {
3 var theform = document.Form1;
4 theform.__EVENTTARGET.value = eventTarget;
5 theform.__EVENTARGUMENT.value = eventArgument;
6 Form1.submit();
7 }

When any controls generates a postback (example: Button Click), this Javscript is called and values are set to the hidden variables named __EVENTTARGET and __EVENTARGUMENT. __EVENTTARGET is the control that is doing the postback and __EVENTARGUMENT holds any additional information for that event. Now, with this information, it is easily understood how to use this at server side Page_Load event to determine which control caused the postback.

This is done by examining the request obejct to see the values in __EVENTTARGET.

1 char[] delim = {'_'};
2 string[] pbCtrl = Request.Form["__EVENTTARGET"].Split(delim);
3 System.Diagnostics.Debug.WriteLine (pbCtrl[0]);
4

pbCtrl[0] should contain the ID of the control that triggered this postback!


Cheers!

Friday, March 03, 2006

ASP.Net - Some performance myths.

Here is some performance myths in .net world as explained by Rob Howard in an article in MSDN Magazine along with what we think!

  • C# code is faster than Visual Basic code - False! Rob says that there is a grain of truth in this mainly because VB.Net allows performance hindering actions like not explicitly declaring types.I think both should be comparable because all the .net languages are ultimately creatingt code targeting the framework CLR and CTS. If you follow good programming practices, VB.Net and C# should provide with same features and performance (pretty much!)

  • Code-Behind is faster than Inlince code - False! Rob points out that sometimes it is advantageous to just change inline (or add inline) code because touching code behind means a Dll rebuild. If you ask me, I would say NO to inline code, haven't we had enough of spaghetti coding with all than classic ASP?

  • Components are faster than Pages- False! True in classic ASP, no longer in ASP.Net, since page is also a class, it provides the same performance as components. Again from a modular design point of view, lets go with components!



Cheers!

Wednesday, March 01, 2006

Clear your web applications Cache

We all know that Cache class provides an implementation for cache for a web application in ASP.net. Cache provides fast access to frequently used data. You can add your not so frequently changed data to Cache for a speedy access. Cache has an application scope, what ever is in cache is used by all users of your web application.

Being said that, I find sometimes a need to clear my web applications cache without affecting anything. In order to do that, this is the trick I have come up with (nothing genius here :)

I created a secure page (admin login required) with a "Clear All Cache" Button,
and here is what I do in that button click!



private void ClearCache_Click(object sender, System.EventArgs e)
{
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator();
string cacheKey="";
while (CacheEnum.MoveNext())
{
cacheKey = Convert.ToString(CacheEnum.Key);
Cache.Remove(cacheKey);
}

}

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 !

Place holder for some text here!