tag:blogger.com,1999:blog-140779542024-03-07T22:29:35.384-08:00.NET TIPSNishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.comBlogger7125tag:blogger.com,1999:blog-14077954.post-4054209907986293742008-10-10T22:38:00.000-07:002008-10-10T22:39:30.440-07:00<script type="text/javascript"><!--<br />google_ad_client = "pub-4348558893710118";<br />/* Necab1 */<br />google_ad_slot = "9195215218";<br />google_ad_width = 728;<br />google_ad_height = 90;<br />//--><br /></script><br /><script type="text/javascript"<br />src="http://pagead2.googlesyndication.com/pagead/show_ads.js"><br /></script>Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0tag:blogger.com,1999:blog-14077954.post-4539856194572312872007-05-25T05:29:00.000-07:002007-05-25T05:39:22.769-07:00Validating an XML File using XSD in .NET .20<span style="color:#009900;">Below given is the.NET 1.1 code for validating an XML File using an XSD File.</span><br /><br />.NET 1.1 Code<br /><br />//.NET1.1 code<br /> /// <summary><br /> /// Methode to validate XML File<br /> /// </summary><br /> /// <param name="XmlData">This method expects input XML as string</param><br /> /// <param name="SchemaPath">Path to schema file</param><br /> /// <returns>true if xml is validated else false</returns><br /> <span style="color:#339999;"> private bool ValidateXmlUsingXsd(string XmlData,String SchemaPath)<br /> {<br /> XmlValidatingReader v = new XmlValidatingReader(XmlData, XmlNodeType.Document, null);<br /> v.ValidationType = ValidationType.Schema; <br /> v.ValidationEventHandler +=<br /> new ValidationEventHandler(MyValidationEventHandler);<br /> <br /> while (v.Read())<br /> {<br /> // Can add code here to process the content.<br /> }<br /> v.Close();<br /><br /> return isValid;<br /> <br /> }<br /></span> /// <summary><br /> /// This event handler is called only when a validation error occurs<br /> /// </summary><br /> /// <param name="sender"></param><br /> /// <param name="args"></param><br /> <span style="color:#339999;">public static void MyValidationEventHandler(object sender,<br /> ValidationEventArgs args)<br /> {<br /> //these two variables should be initialized as class level variables<br /> isValid = false;<br /> errorMessage = "Validation event\n" + args.Message;<br /><br /> }<br /></span> /// <summary><br /> /// Method to get XML in a string from an XML file<br /> /// </summary><br /> /// <param name="fileName"></param><br /> /// <returns></returns><br /> <span style="color:#339999;">private string GetStringFromXML(string fileName)<br /> {<br /> StreamReader rd = new StreamReader(fileName);<br /> string str = rd.ReadToEnd();<br /> rd.Close();<br /> return str;<br /> }<br /></span><br /><br /><br /><br />Calling the method :<br /> <span style="color:#339999;">bool valid = ValidateXmlUsingXsd(str, txtXSD.Text);<br /></span><br /><br />There are some changes in the .NET 2.0 code for XML Validation .<br /><span style="color:#33cc00;">XmlValidatingReader</span> is marked as obsolete. Need to use <span style="color:#33cc00;">XMLReader.Create()</span> using <span style="color:#33cc00;">XmlReaderSettngs</span> instead<br /><br />There are some behavioral changes between validation using the XmlReaderSettings and XmlSchemaSet classes and validation using the XmlValidatingReader class.<br /><br />The XmlReaderSettings and XmlSchemaSet classes do not support XML-Data Reduced (XDR) schema validation.<br /><br />The most important difference I found out is that to do XML data validation using a schema, <span style="color:#ff0000;"><strong>settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;</strong></span><br />Flag must be enabled. <span style="color:#cc0000;">Otherwise the Schema check error will not be displayed</span>.<br /><br />//.NET2.0 code<br /> <span style="color:#339999;">private bool ValidateXmlUsingXsd2(string XmlData,String SchemaPath)<br /> {<br /> XmlReaderSettings settings = new XmlReaderSettings();<br /> settings.ValidationType = ValidationType.Schema;<br /> settings.Schemas.Add(null, SchemaPath); <br /> settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; <br /> settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);<br /><br /> StringReader xmlStream = new StringReader(XmlData);<br /> XmlReader reader = XmlReader.Create(xmlStream, settings);<br /> while (reader.Read()) ;<br /><br /> return isValid; <br /> }<br /><br /> private static void ValidationCallBack(object sender, ValidationEventArgs e)<br /> {<br /> isValid = false;<br /> errorMessage = "Validation Error: " + e.Message;<br /> }<br /><br /></span><br />More about XmlSchemaValidationFlags Enumeration<br /><br /><a name="membersToggle"> </a><br />Member name<br />Description<br /><strong><span style="color:#006600;"><span style="color:#000099;">AllowXmlAttributes</span><br /></span></strong>Allow xml:* attributes even if they are not defined in the schema. The attributes will be validated based on their data type.<br /><span style="color:#000099;"><strong>None</strong></span><br />Do not process identity constraints, inline schemas, schema location hints, or report schema validation warnings.<br /><span style="color:#000099;"><strong>ProcessIdentityConstraints<br /></strong></span>Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation.<br /><span style="color:#000099;"><strong>ProcessInlineSchema</strong></span><br />Process inline schemas encountered during validation.<br /><strong><span style="color:#000099;">ProcessSchemaLocation</span></strong><br />Process schema location hints (xsi:schemaLocation, xsi:noNamespaceSchemaLocation) encountered during validation.<br /><span style="color:#ff0000;"><strong>ReportValidationWarnings</strong></span><br />Report schema validation warnings encountered during validation.<br /><br /><br /><span style="color:#cc0000;"><strong>In a nutshell, Always set settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; when a schema validation is required for the XML in .NET 2.0</strong></span>Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0tag:blogger.com,1999:blog-14077954.post-72560237226035998712007-05-19T12:10:00.000-07:002007-06-07T19:12:28.319-07:00Truncation of fields when CSV file is read using ADO.NET<span style="color:#000066;">I encountered a major problem with ADO.NET CSV reader in one of the projects where CSV File Import played a major role.<br />When a field in the CSV file with a “–“(hyphen) is read, the characters before the “–“are discarded. For example the model F-150 is read as –150 and T-Bird in the model field is not being read. And some of the values were missing in some of the fields.<br />Given below is the code I used :<br /><br /><span style="color:#339999;">string strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + folderName + ";Extended Properties=\"text;HDR=Yes; FMT=Delimited\"";<br />string sqlSelect = "select * from [" + fileName + "]";<br />System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(<br />strConnString.Trim());<br />conn.Open();<br />System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(sqlSelect, conn);<br />DataSet ds = new DataSet();<br />adapter.Fill(ds, "Inventory");<br />return ds.Tables[0]; </span><br /><br />Samir found a solution, to add a schema file which identifies all fields in the csv file as string values.<br />And call DataSet.ReadXMLSchema() method to attach the schema to the DataSet. Also the schema constraints are not enforced .<br /><br />modified code looks like this..<br /><br /><br /></span><span style="color:#339999;">string strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + folderName + ";Extended Properties=\"text;HDR=Yes; FMT=Delimited; IMEX=1\"";<br />string sqlSelect = "select * from [" + fileName + "]";<br />System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConnString.Trim());<br />conn.Open();<br />System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(sqlSelect, conn);<br />DataSet ds = new DataSet();<br /><br /></span><span style="color:#339999;"><span style="color:#ff0000;"><strong>ds.ReadXmlSchema(Server.MapPath("xmlschema.xsd"));<br />ds.EnforceConstraints = false;</strong> </span><br /><br />adapter.Fill(ds, "Inventory");<br />return ds.Tables[0]; </span><span style="color:#000066;"><br /><br />Even after using this code values like "F-150" was read as -150 if there is only one row in the csv file. </span><br /><span style="color:#ff0000;">F-100 reads as -100<br />K-100 reads as -100<br />S-100 reads as -100</span><br /><span style="color:#ff0000;">100-F reads as -100<br />100-K reads as -100<br />100-S reads as -100<br />100$F reads as 100<br />100$K reads as 100<br />100$S reads as 100<br />F100 reads as 100<br />K100 reads as 100<br />S100 reads as 100<br />F\100 reads as 100<br />K\100 reads as 100<br />S\100 reads as 100<br />F.100 reads as .1<br />K.100 reads as .1<br />S.100 reads as .1<br />K-.\\$$$.\\1 reads as -0.1<br />K\\-22..$$\\21 reads as -22.221<br />-$\.FSK1 reads as -0.1</span><br /><span style="color:#333399;">This happens only wen there is only one row in the csv file or more than half the values in a column is having the avove specified values</span><br /><span style="color:#333399;"></span><br /><span style="color:#000066;"> May be because ADO.NET does some internal calculation to treat F as floating point or something.. The fun part is that f-150 is read correctly.. problem is with capital letters :) . </span><br /><span style="color:#000066;">So we ended up using a custom third party csv reader . </span><br /><span style="color:#000066;">Moral of the story... never use ADO.NET csv reader... Always go for a custom CSV parser or a third party library. </span><br /><span style="color:#000066;"></span>Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0tag:blogger.com,1999:blog-14077954.post-36726210191652007832007-05-14T04:00:00.000-07:002007-05-14T04:03:59.195-07:00Method to sort an array of strings in descending order of number of words in each array elementJust adding a method which i wrote for an application for which the requirement was scrapped.<br />Hope someone can refer to this silly method. ;)<br /><br /><span style="color:#339999;">/// <summary><br />/// Method to sort an array of strings in descending order of number of words in each array element<br />/// </summary><br />/// <param name="strArray">Array to be sorted</param><br />/// <returns>Array sorted in descending order of number of words in each array element</returns><br /></span><br /><span style="color:#990000;">private static string[] SortArrayWithDescendingWordCount(string[] strArray)<br />{<br /><span style="color:#339999;">//Array to store the number of words in each string of the array to be sorted<br /></span>int[] wordLengths = new int[strArray.Length];<br /><span style="color:#339999;">//variable to keep track of array index of wordLengths array.<br /></span>int arrayIndex = 0;<br />foreach (string str in strArray)<br />{<br /><span style="color:#339999;">//split the string in to an array of words and store the word count in wordLengths array.<br /></span>wordLengths[arrayIndex] = str.Split(' ').Length; ;<br />arrayIndex++;<br />}<br /><span style="color:#339999;">//Sort arrays(ascending order) by taking wordLenths array as key and strArray as value</span><br />Array.Sort(wordLengths, strArray);<br /><span style="color:#339999;">//now reverse strArray array to sort the array in descending order of number of words in each array element<br /></span>Array.Reverse(strArray);<br />return strArray;<br />} </span>Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0tag:blogger.com,1999:blog-14077954.post-39810477373227400522007-03-05T16:00:00.000-08:002007-03-05T16:05:19.805-08:00VIewState issue in creating a Word Doc from Rendered ASPXEarly last week, i was involved in a pretty interesting assignment of creating a word document with some dynamically created data on the click of a button from an ASPX Page. I created a template aspx page for the word Document. In the load of the page, i took all the values from session and loaded the labels. Did a <strong><span style="color:#006600;">Server.Execute("Page.aspx", StringWriter)</span></strong> from the button click event. the <strong>StringWriter</strong> object was converted to a byte array and written in to the HTTP Stream using <span style="color:#006600;"><strong>Response.BinaryWrite(byte[])</strong>.</span> Everything went well and the word document was opened . But there was an uninvited guest in the word document when i opened it. it was a text box on top of the word doc with some junk values in it. After some investigations, I understood that it was the Viewstate variable created as an <span style="color:#006600;"><strong><input type =" hidden"></strong></span> inside the rendedred HTML. I turned off viewstate by doing <span style="color:#006600;"><strong>Page.EnableViewState = False</strong></span>. And tested again... but now also the text box appeared in the word document , but with no values in it. Even if you turn off ViewState, the viewstate variable will be created in the rendered HTML with no values in it. Workarounds:Now, there are 2 workarounds for this issue.(As suggested by 2 Avanade comunity members) 1. Use a usercontrol with the doc template created in it. Load values in the load event of the control. On Pag Load event, render the usercontrol using <span style="color:#006600;"><strong>UserControl.RenderControl();</strong></span>This worked out perfectly.<br />2. Either use <strong><span style="color:#006600;">Server.Execute("Page.aspx", StringWriter)</span></strong> from another page or this.Render(HTMLTextWriter) from the current page and get the rendered HTML of the Word Doc page in a StringWriter, Convert it to a string and find out Viewstate declaration inside the string and remove it. We choose this method as we had some problem in creating usercontrol in the complex architecture.<br />I wrote the following method to remove ViewState from the rendered HTML:<br /><br /><strong><span style="color:#330099;"><span style="color:#cc0000;"><span style="color:#990000;">//Method to remove __VIEWSTATE and stateTarget variables</span><br /></span>private string RemoveInputFieldsFromRenderedHTML(string pageData)<br /><span style="color:#990000;">{//pageDate variable contails the rendered HTML from the stringwriter.<br /></span>int startIndex;<br />int endIndex;<br /><span style="color:#990000;">//Variable to store the length of closing tag of Viewstate<br /><br /></span>string newPageData = "";<br />string viewStateStartTag = "<input type=\"hidden\" name=\"__VIEWSTATE";<br />string viewStateEndTag = "\" />";int lengthOfClosingTag = 4; //This can be re written as viewStateEndTag.Length()<br />startIndex = pageData.IndexOf(viewStateStartTag);<br />endIndex = pageData.IndexOf(viewStateEndTag,startIndex);<br />if(startIndex > 0)<br />newPageData = pageData.Remove( startIndex,(endIndex + lengthOfClosingTag) - startIndex);<br /><br />return newPageData;<br />}</span></strong><br /><strong><span style="color:#330099;"></span></strong><br />Hope this piece of code will be useful to somebody someday....Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0tag:blogger.com,1999:blog-14077954.post-67671747763593208162007-02-24T02:29:00.000-08:002007-02-24T02:34:57.031-08:00I was hosting an intranet website in Windows server 2003 with IIS6 . I noticed that the server was taking too much time to respond when the site was accessed . Then in the task manager I saw w3wp.exe(worker process for ASP.NET) was taking more than 500MB of memory.As a result the OS was using too much virtual memory .(Hard disk busy light was always on ). I went to microsoft website and saw that there is a hotfix for this problem and after applying this hotfix , a registry tweak must be done . But I couldnt find the hotfix patch to download.<br /><br />I restarted the machine and everything was working fine. Then i wrote a scrip to restart the server every sunday night. It was the only solution feasible at that point of time.<br /><br />I wrote a post regarding this issue in <a href="http://www.dotnetjunkies.com">www.dotnetjunkies.com</a> and today i got a gud reply for it. The reply is as follows.<br /><br /><br />Re: w3wp.exe taking too much memory<a name="12792">Posted: 02-23-2007 11:46 PM</a><br />That w3wp.exe also has been creating havoc on our servers us so we wrote a simple application to control it. Details and download here:<br /><a href="http://www.linkhelpers.net/w3wp_fix.asp">http://www.linkhelpers.net/w3wp_fix.asp</a> Works for us.<br /><br />Details in the link is given below:<br /><br />w3wp.exe FixSomehow, somewhere, someone released some untested code and hundreds of servers are crippled. I scanned through the forums an all the fixes were red herrings. So I decided to look into it myself. Looping like a loon it just eats up CPU resources like a voracious pig. The solution I came up with was to set w3wp.exe's priority to Idle. This seemed to help but the application would eventually crash and restart with the priority defaulting to Normal. Well baby sitting an executable is not realistic.<br />HeartBeatHeartBeat.exe is a stand alone application that will pulse every couple of seconds and reset w3wp.exe's priority to Idle. This appears to lessen the impact but is not a permanent fix. This fix has not been tested with servers running ISAPI filters which w3wp.exe is supposed to address. There are no guarantees or do we accept any liability for the use of this fix.<br />Access DatabasesFor some reason I still have not figured out, an *.ldb file causes IIS worker error dialogs. Once this file is deleted, the error dialogs stop. <a style="COLOR: blue" href="mailto:randelosreyes@yahoo.com">Randy Delos Reyes</a> was instrumental in figuring most of this out.<br />Download HeartBeat<br /><a style="FONT-WEIGHT: 700; COLOR: blue" href="http://www.linkhelpers.net/public/HeartBeat.zip">http://www.linkhelpers.net/public/HeartBeat.zip</a>Remember, test this fix first before using it. We are not liable for any unforseen problems you may have. I do know that it works great for our servers.<br /><br />--------------------------------------------<br /><br />Try your luck . :) .Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0tag:blogger.com,1999:blog-14077954.post-1135579066034962152005-12-25T22:34:00.000-08:002005-12-25T22:37:46.046-08:00Aspnet_Regiis.exeAfter doing a fresh installation of Visual Studio.NET in myWindow XP machine I was trying to open a sample application in ASP.NET.But VS was giving an error.<br /><br /> <strong><span style="color:#ff0000;">"The specified server is not running .NET 1.1"</span></strong><br /><br />And the solution : <br /><br /><strong><span style="color:#000099;">go to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 and execute aspnet_regiis -i I got .NET 1.1 installed.. Now everything is working fine.<br /></span></strong><br />The generalized path for aspnet_regiis is :<br /><br /><span style="color:#000099;">[Drive] :\[Windowsfolder]\Microsoft.NET\Framework\[Version]</span><br /><br /><strong>Now what is this utility for ?</strong><br /><br />simply aspnet_regiis.exe is "ASP.NET IIS Registration Tool "<br /><br />There may be different versions of .NET installed in a machine and the ASP.NET ISAPI version mapped to an ASP.NET application determines which version of the common language runtime is used for the application.An ASP.NET application is associated with an ASP.NET ISAPI version through a script map in IIS.Aspnet_regiis.exe allows the admin easily update the script maps for an ASP.NET application to point to the ASP.NET ISAPI version associated with the tool.<br /><br /><strong>The tool is also used for</strong><br /><br /><strong><span style="color:#330099;">1.To display all installed versions of .NET</span></strong><br /><strong><span style="color:#330099;">2.Register .NET versions coupled with the tool</span></strong><br /><strong><span style="color:#330099;">3.Create client script directories</span></strong><br /><strong><span style="color:#330099;">4.Perform other configurations.</span></strong><br /><br />Usage: aspnet_regiis.exe [-i[r] [-enable] -u[a] -r -s[n] <path> -k[n]> -lv -lk -c -e[a] -?]<br /> -i - Install this version of ASP.NET and update scriptmaps at the IIS metabase root and for all scriptmaps below the root. Existing scriptmaps of lower version are upgraded to this version.<br /> -ir - Install this version of ASP.NET, register only. Do not update scriptmaps in IIS.<br /> -enable - When -enable is specified with -i or -ir, ASP.NET will also be enabled in the IIS security console (IIS 6.0 or later).<br /> -s <path> - Install scriptmaps for this version at the specified path, recursively. Existing scriptmaps of lower version are upgraded to this version.<br /> E.g. aspnet_regiis.exe -s W3SVC/1/ROOT/SampleApp1<br /> -sn <path> - Install scriptmaps for this version at the specified path, non-recursively. Existing scriptmaps of lower version are upgraded to this version.<br /> -r - Install scriptmaps for this version at the IIS metabase root and for all scriptmaps below the root. All existing scriptmaps are changed to this version, regardless of current version.<br /> -u - Uninstall this version of ASP.NET. Existing scriptmaps to this version are remapped to highest remaining version of ASP.NET installed on the machine.<br /> -ua - Uninstall all versions of ASP.NET on the machine<br /> -k <path> - Remove all scriptmaps to any version of ASP.NET from the specified path, recursively. E.g. aspnet_regiis.exe -k W3SVC/1/ROOT/SampleApp1<br /> -kn <path> - Remove all scriptmaps to any version ASP.NET from the specified path, non-recursively.<br /> -lv - List all versions of ASP.NET that are installed on the machine, with status and installation path. Status: Valid[ (Root)]Invalid<br /> -lk - List all the path of all IIS metabase keys where ASP.NET is scriptmapped, together with the version. Keys that inherit ASP.NET scriptmaps from a parent key will not be displayed.<br /> -c - Install the client side scripts for this version to the aspnet_client subdirectory of each IIS site directory.<br /> -e - Remove the client side scripts for this version from the aspnet_client subdirectory of each IIS site directory.<br /> -ea - Remove the client side scripts for all versions from the aspnet_client subdirectory of each IIS site directory.<br /> -? - Print this help text.<br /><br /> A unique version of Aspnet_regiis.exe is included with each version of the .NET Framework. Since each version of the tool is applicable only to its associated version of the .NET Framework, be sure to use the appropriate version of the tool to configure an ASP.NET application.Nishanth Nairhttp://www.blogger.com/profile/17184368451587147040noreply@blogger.com0