tag:blogger.com,1999:blog-274326902024-03-05T07:27:31.000-07:00..:: CoDe Maverick ::..Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.comBlogger17125tag:blogger.com,1999:blog-27432690.post-25025532211122125602010-01-11T13:11:00.010-07:002010-01-11T13:41:08.045-07:00System.Data.SqlClient.SqlException: Arithmetic overflow error converting expression to data type datetime<p align='justify'>This exception occurs when you set a date, which is earlier than January 1, 1753 to a datetime parameter in your SQL expression. Now, what does this "January 1, 1753" represent? This is the minimum date value that a DATETIME data type can have. Setting any date earlier to this date in your SQL expression will result in a SQL datetime overflow. Also such arithmetic overflow exceptions could occur when we set to a datetime field, a date which is later than 31st December, 9999, which is the maximum date value that a DATETIME data type can have.</p>
<p align='justify'>In order to avoid such SQL exceptions, it is always a good practice to validate your date to ensure that your date time is never beyond the min and max limits of SQL date time.</p>
<p>The following sample code will help you to validate your date:
<pre>
<b>VB.NET:</b>
<span style="color: rgb(0,0,255)">Dim</span> dtSQLMinDate As DateTime = <span style="color: rgb(0,0,255)">New</span> DateTime(1753, 1, 1)
<span style="color: rgb(0,0,255)">Dim</span> dtSQLMaxDate As DateTime = <span style="color: rgb(0,0,255)">New</span> DateTime(9999, 12, 31)
<span style="color: rgb(0,0,255)">Private Function</span> ValidateMyDate(<span style="color: rgb(0,0,255)">ByVal</span> dtMyDate <span style="color: rgb(0,0,255)">As</span> DateTime) <span style="color: rgb(0,0,255)">As Boolean</span>
<span style="color: rgb(0,0,255)">If</span> dtMyDate < dtSQLMinDate <span style="color: rgb(0,0,255)">Then</span>
MsgBox(<span style="color: rgb(128,0,0)">"Enter a valid date which is later than Jan 1, 1753"</span>)
<span style="color: rgb(0,0,255)">End If</span>
<span style="color: rgb(0,0,255)">If</span> dtMyDate > dtSQLMaxDate <span style="color: rgb(0,0,255)">Then</span>
MsgBox(<span style="color: rgb(128,0,0)">"Enter a valid date which is earlier than Dec 31, 9999"</span>)
<span style="color: rgb(0,0,255)">End If
End Function</span>
</pre><br/>
<pre>
<b>C#.NET:</b>
DateTime dtSQLMinDate = <span style="color: rgb(0,0,255)">new</span> DateTime(1753, 1, 1);
DateTime dtSQLMaxDate = <span style="color: rgb(0,0,255)">new</span> DateTime(9999, 12, 31);
<span style="color: rgb(0,0,255)">private bool</span> ValidateMyDate(DateTime dtMyDate)
{
<span style="color: rgb(0,0,255)">if</span> (dtMyDate < dtSQLMinDate) {
Interaction.MsgBox(<span style="color: rgb(128,0,0)">"Enter a valid date which is later than Jan 1, 1753"</span>);
}
<span style="color: rgb(0,0,255)">if</span> (dtMyDate > dtSQLMaxDate) {
Interaction.MsgBox(<span style="color: rgb(128,0,0)">"Enter a valid date which is earlier than Dec 31, 9999"</span>);
}
}
</pre>
</p>Geetha Ramanathanhttp://www.blogger.com/profile/10488864273735056380noreply@blogger.com0tag:blogger.com,1999:blog-27432690.post-35014184716244954492008-02-03T02:14:00.001-07:002008-02-03T02:26:15.148-07:00Transpose DataGrid or GridView by transposing DataTable<p>New requirements poured in last week and one among them was to transpose a DataGrid by interchanging rows to columns and columns to rows. The usability engineer proposed that, by doing so, would enable him to utilize the recovered empty spaces on the screen to group data more efficiently. As you know, there is no straightforward way to flip a grid by setting a property or so. I googled to see if there were any solutions already implemented by fellow .NET'ers to address this requirement and found an impressive article on <a href="http://www.codeproject.com/KB/webforms/AspNetBindDatagridVT.aspx" target="_blank">Code Project</a>. Well, I was looking for a much simpler solution and eventually decided to do it myself. It didn't take any longer than I spent googling. The idea is straight and simple, transpose the DataTable and bind it to the grid.</p> <p>To demonstrate this approach, I'll first start by creating a sample DataTable with 3 columns and 5 rows using the code shown below. </p><pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,128,128)">DataTable</span> GetSampleTable()
{
<span style="color: rgb(0,128,128)">DataTable</span> dt = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataTable</span>();
dt.Columns.Add(<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataColumn</span>(<span style="color: rgb(128,0,0)">"First Name"</span>,<span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(0,0,255)">string</span>)));
dt.Columns.Add(<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataColumn</span>(<span style="color: rgb(128,0,0)">"Last Name"</span>,<span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(0,0,255)">string</span>)));
dt.Columns.Add(<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataColumn</span>(<span style="color: rgb(128,0,0)">"Age"</span>,<span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(0,128,128)">Int32</span>)));
<span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 1; i < 6; i++)
{
<span style="color: rgb(0,128,128)">DataRow</span> dr = dt.NewRow();
dr[<span style="color: rgb(128,0,0)">"First Name"</span>] = <span style="color: rgb(128,0,0)">"First Name "</span> + i;
dr[<span style="color: rgb(128,0,0)">"Last Name"</span>] = <span style="color: rgb(128,0,0)">"Last Name "</span> + i;
dr[<span style="color: rgb(128,0,0)">"Age"</span>] = i*10;
dt.Rows.Add(dr);
}
<span style="color: rgb(0,0,255)">return</span> dt;
} </pre><pre class="code"> </pre><a href="http://11011.net/software/vspaste"></a>
<p></p>
<p><u>Original Grid</u></p>
<div>
<table id="grdMain" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Age</th></tr>
<tr>
<td>Firstname1</td>
<td>Lastname1</td>
<td>10</td></tr>
<tr>
<td>Firstname2</td>
<td>Lastname2</td>
<td>20</td></tr>
<tr>
<td>Firstname3</td>
<td>Lastname3</td>
<td>30</td></tr>
<tr>
<td>Firstname4</td>
<td>Lastname4</td>
<td>40</td></tr>
<tr>
<td>Firstname5</td>
<td>Lastname5</td>
<td>50</td></tr></tbody></table></div>
<p>Interchange rows to columns and columns to rows by calling the GetTransposedTable() method as shown below. </p><pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,128,128)">DataTable</span> GetTransposedTable(<span style="color: rgb(0,128,128)">DataTable</span> dt)
{
<span style="color: rgb(0,128,128)">DataTable</span> newTable = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataTable</span>();
newTable.Columns.Add(<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataColumn</span>(<span style="color: rgb(128,0,0)">"0"</span>,<span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(0,0,255)">string</span>)));
<span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 0; i < dt.Columns.Count; i++)
{
<span style="color: rgb(0,128,128)">DataRow</span> newRow = newTable.NewRow();
newRow[0] = dt.Columns[i].ColumnName;
<span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> j = 1; j <= dt.Rows.Count; j++)
{
<span style="color: rgb(0,0,255)">if</span> (newTable.Columns.Count < dt.Rows.Count + 1)
newTable.Columns.Add(<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataColumn</span>(j.ToString(),<span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(0,0,255)">string</span>)));
newRow[j] = dt.Rows[j - 1][i];
}
newTable.Rows.Add(newRow);
}
<span style="color: rgb(0,0,255)">return</span> newTable;
} </pre><pre class="code"> </pre><a href="http://11011.net/software/vspaste"></a>
<p>Bind the resulting DataTable to the ASP.NET GridView Control. </p><pre class="code"><span style="color: rgb(0,0,255)"><</span><span style="color: rgb(128,0,0)">asp</span><span style="color: rgb(0,0,255)">:</span><span style="color: rgb(128,0,0)">GridView</span> <span style="color: rgb(255,0,0)">ID</span><span style="color: rgb(0,0,255)">="grdTransposed"</span> <span style="color: rgb(255,0,0)">runat</span><span style="color: rgb(0,0,255)">="server"</span><span style="color: rgb(0,0,255)">></span></pre><pre class="code"><span style="color: rgb(0,0,255)"></span> </pre>
<p><strong><u>Transposed Grid</u></strong></p>
<div>
<table id="grdTransposed" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<th scope="col">0</th>
<th scope="col">1</th>
<th scope="col">2</th>
<th scope="col">3</th>
<th scope="col">4</th>
<th scope="col">5</th></tr>
<tr>
<td>First Name</td>
<td>Firstname1</td>
<td>Firstname2</td>
<td>Firstname3</td>
<td>Firstname4</td>
<td>Firstname5</td></tr>
<tr>
<td>Last Name</td>
<td>Lastname1</td>
<td>Lastname2</td>
<td>Lastname3</td>
<td>Lastname4</td>
<td>Lastname5</td></tr>
<tr>
<td>Age</td>
<td>10</td>
<td>20</td>
<td>30</td>
<td>40</td>
<td>50</td></tr></tbody></table></div>
<div> </div>
<p><strong><u></u></strong> The column headers are numbered by default. You can hide them by setting <span style="color: rgb(255,0,0)">ShowHeader</span><span style="color: rgb(0,0,255)">="false" </span>which would render a grid as shown below.</p>
<div>
<table id="grdTransposed" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<td>First Name</td>
<td>Firstname1</td>
<td>Firstname2</td>
<td>Firstname3</td>
<td>Firstname4</td>
<td>Firstname5</td></tr>
<tr>
<td>Last Name</td>
<td>Lastname1</td>
<td>Lastname2</td>
<td>Lastname3</td>
<td>Lastname4</td>
<td>Lastname5</td></tr>
<tr>
<td>Age</td>
<td>10</td>
<td>20</td>
<td>30</td>
<td>40</td>
<td>50</td></tr></tbody></table></div>
<div> </div>
<p> Now, let's make the first column elements bold indicating that they're the new "headers" for the transposed grid. This could be tricky with the AutoGenerated columns as we don't have explicit control over them. By default, the HtmlEncode property on these columns are set to "True". This rules out an option of enclosing texts with HTML tags (<B></B>) when the columns are autogenerated. </p><pre class="code">newRow[0] = <span style="color: rgb(128,0,0)">"<B>"</span>+dt.Columns[i].ColumnName+<span style="color: rgb(128,0,0)">"</B>"</span>;</pre><a href="http://11011.net/software/vspaste"></a>
<p>This would render an ugly looking grid as shown below...</p>
<div>
<table id="grdTransposed" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<td><B>First Name</B></td>
<td>Firstname1</td>
<td>Firstname2</td>
<td>Firstname3</td>
<td>Firstname4</td>
<td>Firstname5</td></tr>
<tr>
<td><B>Last Name</B></td>
<td>Lastname1</td>
<td>Lastname2</td>
<td>Lastname3</td>
<td>Lastname4</td>
<td>Lastname5</td></tr>
<tr>
<td><B>Age</B></td>
<td>10</td>
<td>20</td>
<td>30</td>
<td>40</td>
<td>50</td></tr></tbody></table></div>
<div> </div>
<p>Moreover, the GridView column collection will not have autogenerated columns, that is, their count is 0. This rules out another option of looping through the columns and selectively setting the properties. However, by setting the AutoGenerateColumns property to False and dynamically creating bound columns, with HtmlEncode = "false", would give us more flexibility. The GenerateGridColumns() method that's shown below loops through each column in the transposed table, creates a BoundField and adds it to the GridView's DataControlFieldCollection. </p>
<p> </p><pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">void</span> GenerateGridColumns(<span style="color: rgb(0,128,128)">DataTable</span> dt)
{
grdTransposed.AutoGenerateColumns = <span style="color: rgb(0,0,255)">false</span>;
<span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 0; i < dt.Columns.Count; i++)
{
<span style="color: rgb(0,128,128)">BoundField</span> field = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">BoundField</span>();
field.DataField = dt.Columns[i].ColumnName;
field.HtmlEncode = <span style="color: rgb(0,0,255)">false</span>;
grdTransposed.Columns.Add(field);
}
}</pre><pre class="code"> </pre>
<p> I call the above method just before binding the table to the Grid.</p><pre class="code"> <span style="color: rgb(0,128,128)">DataTable</span> transposedTable = GetTransposedTable(dt);
GenerateGridColumns(transposedTable);
grdTransposed.DataSource = transposedTable;
grdTransposed.DataBind();
</pre>
<p> </p>
<p>The final Transposed grid rendered with "Headers" would look like this...</p>
<div>
<table id="grdTransposed" style="border-collapse: collapse" cellspacing="0" rules="all" border="1">
<tbody>
<tr>
<td><b>First Name</b></td>
<td>Firstname1</td>
<td>Firstname2</td>
<td>Firstname3</td>
<td>Firstname4</td>
<td>Firstname5</td></tr>
<tr>
<td><b>Last Name</b></td>
<td>Lastname1</td>
<td>Lastname2</td>
<td>Lastname3</td>
<td>Lastname4</td>
<td>Lastname5</td></tr>
<tr>
<td><b>Age</b></td>
<td>10</td>
<td>20</td>
<td>30</td>
<td>40</td>
<td>50</td></tr></tbody></table></div>
<div> </div>
<p> Hope this helps!</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com8tag:blogger.com,1999:blog-27432690.post-88996952075949324932008-01-24T22:50:00.002-07:002008-09-09T12:01:47.603-06:00Orkut.com vs Cyber Sannyasi<p></p> <p>Alright, seems like it's time to write about something that I did early this week (21st Jan 2008) with Google's most popular Orkut.com. Most of the Orkut users would've seen this message in their scrapbook sent by one of their friends... </p> <blockquote> <p>Here are some tips to make your cell phone battery last longer. Just copy the JavaScript, paste it in your address bar and hit ENTER</p> <p><em>javascript:d=document;c=d.createElement(’script’);d.body.appendChild(c);c.src=’</em><em>http://userscripts.org/scripts/source/20885.user.js’void(0)</em></p> <p>trust me, you’ll find this newsletter informative! [;)] (...ending with a sarcastic wink !)</p></blockquote> <p>And, if they did what it suggested them to do, I'm sure, they had enjoyed the Cyber Sannyasi's cool Technology newsletter that featured an excellent YouTube video and a wikihow.com's article on extending your cell phone battery's life. </p> <p>For those who're seeing this message for the first time here, be patient, you may see it in your scrapbook soon as this script is being misused by many users. Orkut has not fixed the bug completely. </p> <p>Let me briefly explain what this JavaScript did... </p> <p>When logged into Orkut.com you're asked by your friend to run this JavaScript from the address bar. This injects the actual prank Script from <a href="http://userscripts.org/scripts/review/20885?format=txt" target="blank">http://userscripts.org/scripts/source/20885.user.js</a> that runs in the background and renders the newsletter within the same browser window. While the user is engrossed with YouTube video and battery tips - the sript runs asynchronously performing those actions that it was programmed to do. It first sends a read receipt with timestamp back to the author's scrapbook (that's for my tracking purposes). Then fetches the current logged-on user's friends list from Compose.aspx page, builds AJAX based WebRequests and posts the scrap message to everyone on that list. The users were completely unaware of what had just happened until somebody on their list did the same. It forced Orkut to do one more nasty thing... When the user's friend-count exceeded 150 with 150 scraps originating rapidly with a time gap of 500 milliseconds, orkut blocked their write access for an indefinite period of time assuming he/she was a potential spammer [bug? it need not take 150 for the damage... damage has already been done at this point]. As mentioned earlier, this was just a prank and never touched users' sensitive information nor transmitted any cookies nowhere as some bloggers falsely believed (...and scared). In short, it meant no harm to anybody, but for the nuisance it created.</p> <p>The script was later flagged as spam by many and eventually got deleted from the site where it was hosted. The hit counter showed that it was accessed 70,000 times within 36hrs before it went offline prematurely. Well, in a much popular social networking site like orkut.com this number could grow astronomically over time.</p> <p><strong>Why did I do that ?</strong> <p>Hmm, good question. Well the story goes like this.., Inspired by all those "SCRAP ALL" and tons of other similar scripts (...this one's a mutant of SCRAP ALL), I wanted to take Orkut on a more profound spammer-coaster ride propelled by its own do-all-what-I'm-told ignorant users, I wanted to exploit a bug in Orkut.com, and I wanted to educate the users - in a safe but annoying way - about the harms of running scripts while being logged on. Remember the bold red message I had at the bottom of that newsletter ? </p> <blockquote> <p><strong><font color="#ff0000">Protect your account: Never run any script while logged into orkut.com, no matter what it claims to do. Including this newsletter or "Scrap To All" thingy... LOL!!</font></strong></p></blockquote> <p>Yep, I put the same security tip that often appears in BOLD on the home page after you login. I commend Orkut in this regard for constantly reminding its users not to run any scripts while logged in.</p> <p><strong><u>My advice:</u></strong></p> <p>I believe, there are sections where Orkut can improve its anti-spam, anti-bot techniques. Like word filter, that could immediately pop up a captcha when trying to enter URLs or potential script texts in Srapbook. Employ the same flood-prevention algorithms to disallow users from posting similar messages within a specific time. Currently, this works only on a One-One basis. That is, one user cannot send consecutively similar scraps to the same friend, but, CAN definitely send consecutively similary scraps to one friend at a time - a potential for *SPAMs* like this one [;)] ( ... another sarcastic wink!). Hello Orkut, if you're reading this post, get this fixed asap as several users have already started hosting this script at multiple locations and misusing it. </p> <p>For now, if you want to keep spam off of orkut.com just remember the red bold message above. Or, if you're the one who is really curious to see what happens when you run scripts... then... don't curse script-authors for the outcome... It's YOUR PROBLEM & YOU CHOSE TO DO IT! </p> <p>As a final note, I would like to apologize for the frustration, annoyance, confusion & inconvenience caused to several thousand users who fell for this prank. I would also like to apologize the guys at userscripts.org for using their site as a hosting place for this script. <p><strong>Once again.... I love Orkut.com and let's keep Orkut Beautiful... [:)] (...a hearty smile) !!</strong></p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com15tag:blogger.com,1999:blog-27432690.post-26217722465895838122007-10-31T01:01:00.001-06:002007-10-31T13:31:27.372-06:00WMI Queries on Remote Machines<p>Windows management instrumentation (WMI) can be used to access system management data across remote machines. You can use this to get status and configuration information on windows machines listening on the network. The classes found in the System.Management namespace helps developers to write code to access these information quickly. </p> <p>The following example shows how to access LogicalMemoryConfiguration data on a remote machine.</p><pre class="code"><span style="color: rgb(0,0,255)">using</span> System;
<span style="color: rgb(0,0,255)">using</span> System.Net;
<span style="color: rgb(0,0,255)">using</span> System.Management;
<span style="color: rgb(0,0,255)">namespace</span> WMIonRemoteMachine
{
<span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(0,128,128)">Program
</span> {
<span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">void</span> Main(<span style="color: rgb(0,0,255)">string</span>[] args)
{
<span style="color: rgb(0,128,0)">//Specify the Adminstrator's Username and Password
</span> <span style="color: rgb(0,128,128)">ConnectionOptions</span> co = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">ConnectionOptions</span>();
co.Username = <span style="color: rgb(128,0,0)">"Administrator"</span>;
co.Password = <span style="color: rgb(128,0,0)">"password#xyz"</span>;
<span style="color: rgb(0,128,0)">//Connect to the default namespace on Remote Machine
</span> <span style="color: rgb(0,128,128)">ManagementScope</span> scope = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">ManagementScope</span>(<span style="color: rgb(128,0,0)">@"\\[REMOTE MACHINE]\root\cimv2"</span>, co);
<span style="color: rgb(0,128,128)">SelectQuery</span> query = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">SelectQuery</span>(<span style="color: rgb(128,0,0)">"SELECT * FROM Win32_LogicalMemoryConfiguration"</span>);
<span style="color: rgb(0,128,128)">ManagementObjectSearcher</span> searcher = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">ManagementObjectSearcher</span>(scope, query);
<span style="color: rgb(0,0,255)">foreach</span> (<span style="color: rgb(0,128,128)">ManagementObject</span> mObj <span style="color: rgb(0,0,255)">in</span> searcher.Get())
{
<span style="color: rgb(0,0,255)">foreach</span> (System.Management.<span style="color: rgb(0,128,128)">PropertyData</span> property <span style="color: rgb(0,0,255)">in</span> mObj.Properties)
System.<span style="color: rgb(0,128,128)">Console</span>.WriteLine(property.Name.PadLeft(25,<span style="color: rgb(128,0,0)">' '</span>) + <span style="color: rgb(128,0,0)">": "</span> + property.Value);
}
<span style="color: rgb(0,128,128)">Console</span>.ReadLine();
}
}
}</pre>
<p><strong><u>OUTPUT </u></strong>
<p> AvailableVirtualMemory: 1405028<br> Caption: Logical Memory Configuration<br> Description: Logical Memory Configuration<br> Name: LogicalMemoryConfiguration<br> SettingID: LogicalMemoryConfiguration<br> TotalPageFileSpace: 2523064<br> TotalPhysicalMemory: 1046512<br> TotalVirtualMemory: 3569576
<p>
<p>The username and password supplied in the above code should belong to an account that is a member of Administrator Group on the remote machine. If the ConnectionOptions is not set then the namespace residing on the Local System is accessed.
<p>The default WMI namespace or schema "\root\cimv2" is queried to retrieve common system management information. WMI implements the <a href="http://www.dmtf.org/standards/cim/" target="_blank">Common Information Model</a> (CIV) schema proposed by Distributed Management Task Force (DMTF). </p>
<p>Remote connections in WMI are affected by Firewall. It blocks all data requests from remote machines. If a connection fails, an exception of type System.Runtime.InteropServices.COMException is thrown in System.Management with an error message "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)". So make sure that the firewall settings are configured to allow these connections.</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com0tag:blogger.com,1999:blog-27432690.post-29485061274447812022007-09-24T22:11:00.001-06:002008-01-26T23:24:49.306-07:00Data Formatting issues in GridView<p>You have a Grid bound to a datasource. You do all the right stuff by putting the correct formatting expressions in place for the BoundColumn. But when the page is rendered the columns are not formatted. I'm sure everybody would have encountered this at some point or the other while rendering data in ASP.NET 2.0 GridView.</p> <p>The fix is straight, set the HtmlEncode property of the Bound Columns to "false". </p><pre class="code"><span style="color: rgb(0,0,255)"><</span><span style="color: rgb(128,0,0)">asp</span><span style="color: rgb(0,0,255)">:</span><span style="color: rgb(128,0,0)">BoundField</span> <span style="color: rgb(255,0,0)">DataField</span><span style="color: rgb(0,0,255)">="Number"</span> <span style="color: rgb(255,0,0)">DataFormatString</span><span style="color: rgb(0,0,255)">="{0:c}"</span> <span style="color: rgb(255,0,0)">HtmlEncode</span><span style="color: rgb(0,0,255)">="false"</span> <span style="color: rgb(255,0,0)">HeaderText</span><span style="color: rgb(0,0,255)">="Number"</span> <span style="color: rgb(0,0,255)">/></span></pre><pre class="code"><span style="color: rgb(0,0,255)">or</span></pre><pre class="code"><span style="color: rgb(0,0,255)"></span><span style="color: rgb(0,0,255)"><</span><span style="color: rgb(128,0,0)">asp</span><span style="color: rgb(0,0,255)">:</span><span style="color: rgb(128,0,0)">BoundField</span> <span style="color: rgb(255,0,0)">DataField</span><span style="color: rgb(0,0,255)">="Date"</span> <span style="color: rgb(255,0,0)">DataFormatString</span><span style="color: rgb(0,0,255)">="{0:MM/dd/yyyy}"</span> <span style="color: rgb(255,0,0)">HtmlEncode</span><span style="color: rgb(0,0,255)">="false"</span> <span style="color: rgb(255,0,0)">HeaderText</span><span style="color: rgb(0,0,255)">="Date"</span> <span style="color: rgb(0,0,255)">/></span> </pre>
<p>By default this property is set to True for security reasons. When the page is rendered, the output HTML is encoded to prevent cross site scripting (XSS) attacks. So make sure to turn off HtmlEncoding on those columns that you want to display formatted data.</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com0tag:blogger.com,1999:blog-27432690.post-75866935921445601392007-05-22T19:52:00.001-06:002008-01-26T23:26:43.643-07:00Viewing HTML source in AJAX-enabled web pages<p>Sometimes we want to view the HTML rendered by the web server for debugging purposes. We right-click on the browser (IE), select "View Source" and a neat little notepad opens up with the HTML. This is valid as long as the pages are rendered in a conventional way where the entire page is posted back for each subsequent requests.</p> <p>In AJAX, where the pages are rendered asynchronously, "View Source" would only show you the HTML for the page that was originally rendered but does not show you any updates to that page modified through AJAX callbacks. </p> <p>Enter the following javascript in the address bar to view the outer HTML actually generated through AJAX Callbacks.</p> <p><strong>javascript:'<xmp>'+window.document.body.outerHTML+'</xmp>'</strong></p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com3tag:blogger.com,1999:blog-27432690.post-68086337040096087022007-03-18T00:02:00.000-06:002007-11-06T11:02:45.628-07:00.NET Articles<p>Here is a list of articles that I've published elsewhere. This post will be updated frequently... </p> <p><strong>ASP.NET</strong></p> <ul> <li><a href="http://www.c-sharpcorner.com/UploadFile/dheenu27/ResourceFilesOnTheFly09112007004555AM/ResourceFilesOnTheFly.aspx" target="_blank">Generate XML based Resource Files on the fly in ASP.NET 1.x applications</a> </li></ul> <p><strong>GDI+</strong></p> <ul> <li><a href="http://www.c-sharpcorner.com/UploadFile/dheenu27/ImageToASCIIconverter03022007164455PM/ImageToASCIIconverter.aspx" target="_blank">Generate ASCII Art from an Image using C#</a> </li></ul>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.comtag:blogger.com,1999:blog-27432690.post-27018180467194387652007-03-06T21:54:00.001-07:002008-12-09T01:08:22.267-07:00Simple Image-To-ASCII Converter using C#<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8m_bodCkDcC1L-PGnj-Nu2-SpdUPVgJP8g_m8uZIzGlDhZXJKwPRqtkgKSXsPiWdWNXlrwSxF6CXsJYn0Hgtc8mXpvbv4pVGWQwdmfVobG3dErufbuc12h44W3qjkiHRwxUdS9Q/s1600-h/ASCII-art.JPG"><img id="BLOGGER_PHOTO_ID_5039046681955188530" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 154px; CURSOR: hand; HEIGHT: 172px" height="176" alt="" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8m_bodCkDcC1L-PGnj-Nu2-SpdUPVgJP8g_m8uZIzGlDhZXJKwPRqtkgKSXsPiWdWNXlrwSxF6CXsJYn0Hgtc8mXpvbv4pVGWQwdmfVobG3dErufbuc12h44W3qjkiHRwxUdS9Q/s200/ASCII-art.JPG" width="158" border="0" /></a>
<div>If you're a .NET lover and moreover worked with GDI+ then you would definitely want to mess around with images. I've written a short article, <a href="http://www.c-sharpcorner.com/UploadFile/dheenu27/ImageToASCIIconverter03022007164455PM/ImageToASCIIconverter.aspx" target="blank">Generating ASCII Art from an Image using C#</a>, and published it on c-sharpcorner with complete source code. This is a quick and simple Image-To-ASCII generator with zoom-in/zoom-out feature that converts JPEGs and Bitmaps of any resolution to cool and fascinating ASCII arts. Have fun playing with the code!
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVeDlpFe46wiJHPkk7CPA-2aeU1uE5Z-nUB4tlUTro67ASChp1scF5KKxrCChHVO1AidW0tyMGtxvTEsBaZQmljHtg2lAJXfMstSRrIe0c1JOrOJTMxKNGVqpXOT545TvEtZpN4g/s1600-h/ASCII-art.JPG"></a></div>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com1tag:blogger.com,1999:blog-27432690.post-6992231821976236942007-02-23T01:09:00.001-07:002007-10-31T01:05:14.426-06:00[How to] retrieve System Management information with WMI Queries<p>Windows Management Instrumentation (WMI) is the base for management data and operations on Windows Operating system. And System.Management namespace is the WMI namespace in .NET framework. The ManagementObjectSearcher class is one of the first level class objects contained within this namespace. This class can be used to retrieve a collection of ManagementObject based on a specified Win32 query. For example, it can be used to enumerate all Disk Drives, Disk Partitions, Network Adapters, Network Connections, Processes etc.</p> <p>To enumerate all the disk drives and their associated properties we first instantiate a new ManagementObjectSearcher object which takes as input a WMI query. The Get() method on this object returns a collection of management objects that match this query. </p><pre class="code"><span style="color: rgb(0,0,255)">string</span> mosQuery = <span style="color: rgb(128,0,0)">"SELECT * FROM Win32_DiskDrive"</span>;
System.Management.<span style="color: rgb(0,128,128)">ManagementObjectSearcher</span> query = <span style="color: rgb(0,0,255)">new</span> System.Management.<span style="color: rgb(0,128,128)">ManagementObjectSearcher</span>(mosQuery);
<span style="color: rgb(0,0,255)">foreach</span> (System.Management.<span style="color: rgb(0,128,128)">ManagementObject</span> mObj <span style="color: rgb(0,0,255)">in</span> query.Get())
{
<span style="color: rgb(0,0,255)">foreach</span> (System.Management.<span style="color: rgb(0,128,128)">PropertyData</span> property <span style="color: rgb(0,0,255)">in</span> mObj.Properties)
{
System.<span style="color: rgb(0,128,128)">Console</span>.WriteLine(property.Name + <span style="color: rgb(128,0,0)">"__::"</span> + property.Value);
}
} </pre>
<p><u>Sample Output (Just one object in the Collection)</u></p>
<p>Availability__::<br>BytesPerSector__::512<br>Capabilities__::System.UInt16[]<br>CapabilityDescriptions__::<br>Caption__::FUJITSU MHV2060BH<br>CompressionMethod__::<br>ConfigManagerErrorCode__::0<br>ConfigManagerUserConfig__::False<br>CreationClassName__::Win32_DiskDrive<br>DefaultBlockSize__::<br>Description__::Disk drive<br>DeviceID__::\\.\PHYSICALDRIVE0<br>ErrorCleared__::<br>ErrorDescription__::<br>ErrorMethodology__::<br>Index__::0<br>InstallDate__::<br>InterfaceType__::IDE<br>LastErrorCode__::<br>Manufacturer__::(Standard disk drives)<br>MaxBlockSize__::<br>MaxMediaSize__::<br>MediaLoaded__::True<br>MediaType__::Fixed hard disk media<br>MinBlockSize__::<br>Model__::FUJITSU MHV2060BH<br>Name__::\\.\PHYSICALDRIVE0<br>NeedsCleaning__::<br>NumberOfMediaSupported__::<br>Partitions__::1<br>PNPDeviceID__::IDE\DISKFUJITSU_MHV2060BH_______________________0085002A\5&1F698B3F&0&0.0.0<br>PowerManagementCapabilities__::<br>PowerManagementSupported__::<br>SCSIBus__::0<br>SCSILogicalUnit__::0<br>SCSIPort__::0<br>SCSITargetId__::0<br>SectorsPerTrack__::63<br>Signature__::4026531840<br>Size__::60011642880<br>Status__::OK<br>StatusInfo__::<br>SystemCreationClassName__::Win32_ComputerSystem<br>SystemName__::UOPONLG8BFLB1<br>TotalCylinders__::7296<br>TotalHeads__::255<br>TotalSectors__::117210240<br>TotalTracks__::1860480<br>TracksPerCylinder__::255
<p> </p>
<p>Or, you can also use this query,"SELECT * FROM Win32_Service WHERE Started = False", to enumerate a list of services which are not started. </p>
<p>The Win32_DiskDrive/Win32_Service is a WMI object that is being queried here. You can replace the above query with one of those that are listed below. I've compiled a list of management queries by inspecting the objects using WMI object browser. You can play with them or implement the same in your applications as per your requirements...</p><pre class="code"><span style="color: rgb(0,128,0)">//mosQuery = "SELECT * FROM Win32_Account";
//mosQuery = "SELECT * FROM Win32_BIOS";
//mosQuery = "SELECT * FROM Win32_BootConfiguration";
//mosQuery = "SELECT * FROM Win32_Bus";
//mosQuery = "SELECT * FROM Win32_CacheMemory";
//mosQuery = "SELECT * FROM Win32_CDROMDrive";
//mosQuery = "SELECT * FROM Win32_ComputerSystem";
//mosQuery = "SELECT * FROM Win32_DesktopMonitor";
//mosQuery = "SELECT * FROM Win32_DeviceMemoryAddress";
//mosQuery = "SELECT * FROM Win32_DiskDrive";
//mosQuery = "SELECT * FROM Win32_DiskPartition";
//mosQuery = "SELECT * FROM Win32_DMAChannel";
//mosQuery = "SELECT * FROM Win32_Environment";
//mosQuery = "SELECT * FROM Win32_Fan";
//mosQuery = "SELECT * FROM Win32_IDEController";
//mosQuery = "SELECT * FROM Win32_IRQResource";
//mosQuery = "SELECT * FROM Win32_Keyboard";
//mosQuery = "SELECT * FROM Win32_LoadOrderGroup";
//mosQuery = "SELECT * FROM Win32_LogicalDisk";
//mosQuery = "SELECT * FROM Win32_LogicalMemoryConfiguration";
//mosQuery = "SELECT * FROM Win32_LogicalProgramGroup";
//mosQuery = "SELECT * FROM Win32_MemoryArray";
//mosQuery = "SELECT * FROM Win32_MemoryDevice";
//mosQuery = "SELECT * FROM Win32_MotherBoardDevice";
//mosQuery = "SELECT * FROM Win32_NetworkAdapter";
//mosQuery = "SELECT * FROM Win32_NetworkConnections";
//mosQuery = "SELECT * FROM Win32_NTEventLogFile";
//mosQuery = "SELECT * FROM Win32_NTLogEvent";
//mosQuery = "SELECT * FROM Win32_OperatingSystem";
//mosQuery = "SELECT * FROM Win32_PCMCIAController";
//mosQuery = "SELECT * FROM Win32_PnPEntity";
//mosQuery = "SELECT * FROM Win32_PointingDevice";
//mosQuery = "SELECT * FROM Win32_PortableBattery";
//mosQuery = "SELECT * FROM Win32_PortResource";
//mosQuery = "SELECT * FROM Win32_POTSModem";
//mosQuery = "SELECT * FROM Win32_Printer";
//mosQuery = "SELECT * FROM Win32_Process";
//mosQuery = "SELECT * FROM Win32_Processor";
//mosQuery = "SELECT * FROM Win32_SCSIController";
//mosQuery = "SELECT * FROM Win32_SerialPort";
//mosQuery = "SELECT * FROM Win32_Service";
//mosQuery = "SELECT * FROM Win32_share";
//mosQuery = "SELECT * FROM Win32_SoundDevice";
//mosQuery = "SELECT * FROM Win32_SystemDriver";
//mosQuery = "SELECT * FROM Win32_SystemUsers";
//mosQuery = "SELECT * FROM Win32_TemperatureProbe";
//mosQuery = "SELECT * FROM Win32_TimeZone";
//mosQuery = "SELECT * FROM Win32_USBController";
//mosQuery = "SELECT * FROM Win32_USBHub";
//mosQuery = "SELECT * FROM Win32_UserAccount";
//mosQuery = "SELECT * FROM Win32_VideoController";
</span></pre><a href="http://11011.net/software/vspaste"></a>
<p>Happy Coding !!!</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com1tag:blogger.com,1999:blog-27432690.post-77414500368177060252007-02-15T23:34:00.001-07:002007-02-15T23:45:37.919-07:00Creating splash screens with fading effects in Windows Forms<p>All those cool splash screens that you see during application-startup can be created using Windows Forms in .NET 2.0/1.1 easily. Read my previous post on <a href="http://cybersannyasi.blogspot.com/2007/02/creating-custom-winforms-in-net-20-yes.html" target="_blank">creating visually attractive custom shaped forms in .NET</a>. You can enhance these forms with fading effects that could be "cool" and appealing.</p> <p>The trick is with the Form's Opacity property which governs its overall transparency levels. A double value of 1.00, which is its default, sets the Form to be Opaque. Whereas, any value less than that would make it transparent. In mathematical terms, a form is 60% opaque when its opacity value is 0.60. And it is completely invisible when the value is 0.00.</p> <p><strong>Fading Effect</strong></p> <p>The code below does the trick of fading-out. Insert this code in the InitializeComponent method or in a button-click event wherever you would want a "fading-effect" to be fired. </p><pre class="code"><span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 100; i >= 0; i -= 10)
{
<span style="color: rgb(0,0,255)">this</span>.Opacity = (<span style="color: rgb(0,0,255)">double</span>)i / 100;
<span style="color: rgb(0,128,128)">Application</span>.DoEvents();
System.Threading.<span style="color: rgb(0,128,128)">Thread</span>.Sleep(100);
}</pre>
<p>As you can see, between each levels of transparency, I'm specifying a delay of 100 milliseconds. This would give the real fading effect to a form. The Application.DoEvents() method forces a repaint without blocking. </p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com0tag:blogger.com,1999:blog-27432690.post-49078983174302259412007-02-12T21:02:00.000-07:002008-12-09T01:08:22.417-07:00Creating custom WinForms in .NET 2.0. Yes, Forms with more attractive shapes...<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXlcFiTojmjPAXpwgsCtFhgWurcQ0Uxm1XufUAkE4aQw2dT_hjysdLsTPlc88kU5FBn5XCufV3WVu7u2-Tey8DW4F8fSInMTcJmUcXbfkLPUqQnQ3w0iuaIwaoKhlua_CrVvVkYw/s1600-h/customwinform.JPG"><img id="BLOGGER_PHOTO_ID_5031060247132322018" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; CURSOR: hand" alt="" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXlcFiTojmjPAXpwgsCtFhgWurcQ0Uxm1XufUAkE4aQw2dT_hjysdLsTPlc88kU5FBn5XCufV3WVu7u2-Tey8DW4F8fSInMTcJmUcXbfkLPUqQnQ3w0iuaIwaoKhlua_CrVvVkYw/s320/customwinform.JPG" border="0" /></a>
<p>Have you ever wanted to create an application with a GUI that looked just like one of those skins in Windows Media Player 10 ? In .NET you don't have to write a single line of code to generate one such form. Earlier, creating a non-rectangular form was the toughest part which involved complex low-level coding by trapping various Form-handles and calling so many system API's. </p>
<p>I'll show you how to create a Form just like the one as shown in the figure.</p>
<p>Start by creating a transparent Bitmap image using MS Paint or other Image editors. </p>
<p>Add this image to the Form by setting its BackgroundImage property. </p>
<p>Set the BackgroundImageLayout to None.</p>
<p>Set the FormBorderStyle to None.</p>
<p>Set the TransparencyKey to White. This color will appear transparent on the Form.</p>
<p>Thats it, run your application to find a more attractive window. But hold on, its not over yet. This form has one serious limitation. You can't drag and move this form around because you've alread set the FormBorderStyle property to None and the borders & title bar are missing. The title bar functionalities need to be explicitly added to the code to handle all the basic functions like Close, Minimize, Maximize and Move.
</p>
<p><strong><u>Adding a Close Handler</u></strong></p>
<p>Drag and drop a Button control from the ToolBox over the form. Resize and rename this as btnClose with its Text property 'X'. Set the control's BackColor property to the one that blends with your Form's color. Double click on it and add the following code to the Form's Close EventHandler.</p><pre class="code"><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">void</span> btnClose_Click(<span style="COLOR: rgb(0,0,255)">object</span> sender, <span style="COLOR: rgb(0,128,128)">EventArgs</span> e)
{
<span style="COLOR: rgb(0,0,255)">this</span>.Close();
}
</pre><p><strong><u>Adding Drag/Move functionality</u></strong>
</p><p>When the left-button of a mouse is clicked on the form, we first capture the thickness, in pixels, of the border for the window. We then create a point that is relative to the Form's Border and the mouse's current position. This Point becomes the new reference that is available globally.</p><pre class="code"><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,128,128)">Point</span> _OffsetPoint;</pre><a href="http://11011.net/software/vspaste"></a>
<p></p><pre class="code"><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">void</span> CustomForm_MouseDown(<span style="COLOR: rgb(0,0,255)">object</span> sender, System.Windows.Forms.<span style="COLOR: rgb(0,128,128)">MouseEventArgs</span> e)
{
<span style="COLOR: rgb(0,0,255)">if</span> (e.Button == <span style="COLOR: rgb(0,128,128)">MouseButtons</span>.Left)
{
<span style="COLOR: rgb(0,0,255)">int</span> formBorderWidth = <span style="COLOR: rgb(0,128,128)">SystemInformation</span>.FrameBorderSize.Width;
<span style="COLOR: rgb(0,0,255)">int</span> formBorderHeight = <span style="COLOR: rgb(0,128,128)">SystemInformation</span>.FrameBorderSize.Height;
_OffsetPoint = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,128,128)">Point</span>(-(e.X + formBorderWidth), -(e.Y + formBorderHeight));
}
}
</pre><p>The SystemInformation Class can be used to get information about the current system environment like Windows display element sizes, OS settings and other Hardware installed on the machine. The FrameBorderSize property gives the thickness of the border for the window. </p>
<p>When a window is dragged, the new position of the mouse determines the Form's new location. This is achieved by the Point Class' Offset Method. Setting the form's Location property with this new point will translate the form to this point. </p><pre class="code"><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">void</span> CustomForm_MouseMove(<span style="COLOR: rgb(0,0,255)">object</span> sender, System.Windows.Forms.<span style="COLOR: rgb(0,128,128)">MouseEventArgs</span> e)
{
<span style="COLOR: rgb(0,0,255)">if</span> (e.Button == <span style="COLOR: rgb(0,128,128)">MouseButtons</span>.Left)
{
<span style="COLOR: rgb(0,128,128)">Point</span> mousePos = <span style="COLOR: rgb(0,128,128)">Control</span>.MousePosition;
mousePos.Offset(_OffsetPoint.X, _OffsetPoint.Y);
Location = mousePos;
}
}</pre><p>This is just slice of what you can do with Visual Studio.NET and the .NET framework. Have fun with it !!</p><a href="http://11011.net/software/vspaste"></a>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com0tag:blogger.com,1999:blog-27432690.post-68469568074334981242007-02-09T21:58:00.001-07:002007-02-11T16:34:27.580-07:00Search and Replace Texts in all Files and Subfolders using C#<p></p> <p>Recently I needed to replace a string in whole bunch of HTML template files that I had been working on. I found a couple of text editors which attempted to do this only after loading the entire lot of files in the memory. When the number of files were in hundreds they failed miserably. I also tried to load the files into a project in Visual Studio 2005 IDE and use its Find & Replace in Current Project feature. This failed to find texts with line breaks eventually forcing me to drop this idea. After spending an hour of intense googling to find the right tool, I decided to make my own Search & Replace application in C# and I did make it in 15mins. This application can search and replace texts in all files and subfolders filtered by their extensions. <p>Instead of using the string.Replace() method provided by the string object, I wrote a custom method which finds and replace strings in a loop. This gives me more flexibility to keep track of the number of replacements as well as the files that were actually affected. The Directory.GetFiles() method returns the complete paths of all files (after applying the filter) in the specified folder and all its subfolders. <p>Here is The code.... <pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">void</span> btnReplace_Click(<span style="color: rgb(0,0,255)">object</span> sender, <span style="color: rgb(0,128,128)">EventArgs</span> e)
{
<span style="color: rgb(0,128,0)">//Enter some text that you want to search and replace
</span> <span style="color: rgb(0,0,255)">string</span> find = txtFind.Text;
<span style="color: rgb(0,0,255)">int</span> replaced = 0;
<span style="color: rgb(0,128,0)">//Get all the files from the root directory filtered by a filter text.
</span> <span style="color: rgb(0,0,255)">string</span>[] fileList = <span style="color: rgb(0,128,128)">Directory</span>.GetFiles(<span style="color: rgb(128,0,0)">@"C:\Documents and Settings\tganesan\Desktop\FindnReplace"</span>, <span style="color: rgb(128,0,0)">"*.txt"</span>, <span style="color: rgb(0,128,128)">SearchOption</span>.AllDirectories);
<span style="color: rgb(0,128,0)">//Loop through each file, call the ReplaceText() method
</span> <span style="color: rgb(0,128,0)">//and replace the file if something was replaced.
</span> <span style="color: rgb(0,0,255)">foreach</span> (<span style="color: rgb(0,0,255)">string</span> file <span style="color: rgb(0,0,255)">in</span> fileList)
{
<span style="color: rgb(0,128,128)">StreamReader</span> sr = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">StreamReader</span>(file);
<span style="color: rgb(0,0,255)">string</span> content = sr.ReadToEnd();
sr.Close();
<span style="color: rgb(0,0,255)">if</span>(ReplaceText(<span style="color: rgb(0,0,255)">ref</span> content, txtFind.Text, txtReplace.Text, <span style="color: rgb(0,0,255)">ref</span> replaced))
{
<span style="color: rgb(0,128,128)">StreamWriter</span> sw = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">StreamWriter</span>(file);
sw.Write(content);
sw.Flush();
sw.Close();
<span style="color: rgb(0,128,0)">//TODO: Add the files to a collection that were affected.
</span> }
}
<span style="color: rgb(0,128,128)">MessageBox</span>.Show(<span style="color: rgb(128,0,0)">"Total replacements = "</span> + replaced);
}
<span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"><summary>
///</span><span style="color: rgb(0,128,0)"> This method loops through the File content
</span><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> and replaces the text if found.
</span><span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"></summary>
///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"><param name="content"></param>
///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"><param name="oldValue"></param>
///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"><param name="newValue"></param>
///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"><param name="replaced"></param>
///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)"><returns></returns>
</span><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">bool</span> ReplaceText(<span style="color: rgb(0,0,255)">ref</span> <span style="color: rgb(0,0,255)">string</span> content,<span style="color: rgb(0,0,255)">string</span> oldValue, <span style="color: rgb(0,0,255)">string</span> newValue, <span style="color: rgb(0,0,255)">ref</span> <span style="color: rgb(0,0,255)">int</span> replaced)
{
<span style="color: rgb(0,128,128)">Boolean</span> isReplaced = <span style="color: rgb(0,0,255)">false</span>;
<span style="color: rgb(0,0,255)">int</span> startIndex = 0;
<span style="color: rgb(0,0,255)">while</span> (startIndex != -1)
{
startIndex = content.IndexOf(oldValue,startIndex);
<span style="color: rgb(0,0,255)">if</span> (startIndex != -1)
{
content = content.Remove(startIndex, oldValue.Length);
content = content.Insert(startIndex,newValue);
replaced += 1;
isReplaced = <span style="color: rgb(0,0,255)">true</span>;
}
}
<span style="color: rgb(0,0,255)">return</span> isReplaced;
}</pre>Don't forget to take a backup of files before running this code.Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com0tag:blogger.com,1999:blog-27432690.post-62050856017955145462007-02-05T21:39:00.001-07:002007-02-05T21:39:52.375-07:00System.Data.EvaluateException: Cannot perform '=' operation on System.Int16 and System.String<p>This exception was thrown while filtering out rows from a DataTable with an incorrect filter expression. See the sample code shown below...</p><pre class="code"><span style="color: rgb(0,128,128)">DataTable</span> dt = GetDataTable();
<span style="color: rgb(0,128,128)">DataRow</span>[] drs = dt.Select(<span style="color: rgb(128,0,0)">"ID='"</span> +param + <span style="color: rgb(128,0,0)">"'"</span>);
</pre><a href="http://11011.net/software/vspaste"></a><pre class="code"><a href="http://11011.net/software/vspaste"></a></pre><pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,128,128)">DataTable</span> GetDataTable()
{
<span style="color: rgb(0,128,128)">DataTable</span> dt = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataTable</span>();
dt.Columns.Add(<span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">DataColumn</span>(<span style="color: rgb(128,0,0)">"ID"</span>, <span style="color: rgb(0,0,255)">typeof</span>(<span style="color: rgb(0,128,128)">Int16</span>)));
<span style="color: rgb(0,128,128)">DataRow</span> dr;
<span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 0; i <= 100; i++)
{
dr = dt.NewRow();
dr[<span style="color: rgb(128,0,0)">"ID"</span>] = i;
dt.Rows.Add(dr);
}
<span style="color: rgb(0,0,255)">return</span> dt;
}
</pre><a href="http://11011.net/software/vspaste"></a>
<p>The GetDataTable() method just returns a sample DataTable with one column of Type Int16. The param in the filter expression is of string type. The expression works fine as long as the param string is a number, like 0, 1, 2... since ID is an Int16 column. The expression can be framed either as "ID = '2'" or "ID = 2". When param is an empty string or null, the above exception is thrown as these types of strings cannot be converted into a type that is equivalent to the comparing column (Int16). </p>
<p>So the next time when you use a filter expression to filter out rows from a DataTable ensure that you use the right Data Types.</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com1tag:blogger.com,1999:blog-27432690.post-46998312496438575632007-01-30T21:52:00.001-07:002007-02-11T22:49:52.466-07:00Split and Merge files in C#<p>In this feed I'll show you how to Split a file into user-specified chunks and eventually merge them all together. You will find this very helpful if you have very large text files, greater than a GB, that cannot be viewed in your "lousy Notepad". These large text files could be one of the crucial log files from your enterprise applications that may accrue data, if left un-attended, over time.</p> <p>The code example I have shown below is generalized to split any file irrespective of their format. </p><pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">void</span> btnSplit_Click(<span style="color: rgb(0,0,255)">object</span> sender, <span style="color: rgb(0,128,128)">EventArgs</span> e)
{
<span style="color: rgb(0,0,255)">string</span> inputFile = txtInputFile.Text; <span style="color: rgb(0,128,0)">// Substitute this with your Input File
</span> <span style="color: rgb(0,128,128)">FileStream</span> fs = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">FileStream</span>(inputFile, <span style="color: rgb(0,128,128)">FileMode</span>.Open, <span style="color: rgb(0,128,128)">FileAccess</span>.Read);
<span style="color: rgb(0,0,255)">int</span> numberOfFiles = <span style="color: rgb(0,128,128)">Convert</span>.ToInt32(txtChunks.Text);
<span style="color: rgb(0,0,255)">int</span> sizeOfEachFile = (<span style="color: rgb(0,0,255)">int</span>)<span style="color: rgb(0,128,128)">Math</span>.Ceiling((<span style="color: rgb(0,0,255)">double</span>)fs.Length / numberOfFiles);
<span style="color: rgb(0,0,255)">for</span> (<span style="color: rgb(0,0,255)">int</span> i = 1; i <= numberOfFiles; i++)
{
<span style="color: rgb(0,0,255)">string</span> baseFileName = <span style="color: rgb(0,128,128)">Path</span>.GetFileNameWithoutExtension(inputFile);
<span style="color: rgb(0,0,255)">string</span> extension = <span style="color: rgb(0,128,128)">Path</span>.GetExtension(inputFile);
<span style="color: rgb(0,128,128)">FileStream</span> outputFile = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">FileStream</span>(<span style="color: rgb(0,128,128)">Path</span>.GetDirectoryName(inputFile) + <span style="color: rgb(128,0,0)">"\\"</span> + baseFileName + <span style="color: rgb(128,0,0)">"."</span> + i.ToString().PadLeft(5, <span style="color: rgb(0,128,128)">Convert</span>.ToChar(<span style="color: rgb(128,0,0)">"0"</span>)) + extension + <span style="color: rgb(128,0,0)">".tmp"</span>, <span style="color: rgb(0,128,128)">FileMode</span>.Create, <span style="color: rgb(0,128,128)">FileAccess</span>.Write);
<span style="color: rgb(0,0,255)">int</span> bytesRead = 0;
<span style="color: rgb(0,0,255)">byte</span>[] buffer = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,0,255)">byte</span>[sizeOfEachFile];
<span style="color: rgb(0,0,255)">if</span> ((bytesRead = fs.Read(buffer, 0, sizeOfEachFile)) > 0)
{
outputFile.Write(buffer, 0, bytesRead);
}
outputFile.Close();
}
fs.Close();
}</pre><a href="http://11011.net/software/vspaste"></a><pre class="code"><span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">void</span> btnMerge_Click(<span style="color: rgb(0,0,255)">object</span> sender, <span style="color: rgb(0,128,128)">EventArgs</span> e)
{
<span style="color: rgb(0,0,255)">string</span> outPath = txtInputFolder.Text; <span style="color: rgb(0,128,0)">// Substitute this with your Input Folder
</span> <span style="color: rgb(0,0,255)">string</span>[] tmpFiles = <span style="color: rgb(0,128,128)">Directory</span>.GetFiles(outPath, <span style="color: rgb(128,0,0)">"*.tmp"</span>);
<span style="color: rgb(0,128,128)">FileStream</span> outputFile = <span style="color: rgb(0,0,255)">null</span>;
<span style="color: rgb(0,0,255)">string</span> prevFileName = <span style="color: rgb(128,0,0)">""</span>;
<span style="color: rgb(0,0,255)">foreach</span> (<span style="color: rgb(0,0,255)">string</span> tempFile <span style="color: rgb(0,0,255)">in</span> tmpFiles)
{
<span style="color: rgb(0,0,255)">string</span> fileName = <span style="color: rgb(0,128,128)">Path</span>.GetFileNameWithoutExtension(tempFile);
<span style="color: rgb(0,0,255)">string</span> baseFileName = fileName.Substring(0, fileName.IndexOf(<span style="color: rgb(0,128,128)">Convert</span>.ToChar(<span style="color: rgb(128,0,0)">"."</span>)));
<span style="color: rgb(0,0,255)">string</span> extension = <span style="color: rgb(0,128,128)">Path</span>.GetExtension(fileName);
<span style="color: rgb(0,0,255)">if</span> (!prevFileName.Equals(baseFileName))
{
<span style="color: rgb(0,0,255)">if</span> (outputFile != <span style="color: rgb(0,0,255)">null</span>)
{
outputFile.Flush();
outputFile.Close();
}
outputFile = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">FileStream</span>(outPath + baseFileName + extension, <span style="color: rgb(0,128,128)">FileMode</span>.OpenOrCreate, <span style="color: rgb(0,128,128)">FileAccess</span>.Write);
}
<span style="color: rgb(0,0,255)">int</span> bytesRead = 0;
<span style="color: rgb(0,0,255)">byte</span>[] buffer = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,0,255)">byte</span>[1024];
<span style="color: rgb(0,128,128)">FileStream</span> inputTempFile = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(0,128,128)">FileStream</span>(tempFile, <span style="color: rgb(0,128,128)">FileMode</span>.OpenOrCreate, <span style="color: rgb(0,128,128)">FileAccess</span>.Read);
<span style="color: rgb(0,0,255)">while</span> ((bytesRead = inputTempFile.Read(buffer, 0, 1024)) > 0)
outputFile.Write(buffer, 0, bytesRead);
inputTempFile.Close();
<span style="color: rgb(0,128,128)">File</span>.Delete(tempFile);
prevFileName = baseFileName;
}
outputFile.Close();
}</pre><pre class="code"><font face="Verdana"></font> </pre><pre class="code"><font face="Verdana">The split method is straightforward, you set the count of number of files to be split, and the size of each file is allocated equally. Each file is named after its parent, numbered and tailed with an extension of ".tmp". If you're splitting a Text file with no intention of merging them at a later time, you can replace the ".tmp" extension with ".txt".</font></pre>
<p>The Merge method above, is in fact a "Merge All" method. It merges all the files with extensions ".tmp" in the specified directory and re-creates the parent file back. That's the reason why I'm retaining the original fileName and their extensions. </p>
<p>The <span style="color: rgb(0,128,128)">Directory</span>.GetFiles() method returns an array of all the file paths from the directory in ascending order. If you have fileNames like Testfile1.txt, Testfile2.txt, .... testfile100.txt then their order in the string array would be Testfile1.txt, Testfile10.txt, Testfile100.txt, Testfile2.txt, Testfile20.txt, Testfile3.txt,.... as the numbers are just strings. The Merge would fail eventually because of this merge-order. This can be addressed if you LeftPad the number with 0's, preferably a padding of 5 characters, while splitting. The fileNames now would be something like these, Testfile00001.txt, Testfile00002.txt...Testfile00100.txt.</p>
<p>All the "tmp" files are deleted from the folder after they are merged. </p><pre class="code"><font face="Verdana"></font> </pre>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com8tag:blogger.com,1999:blog-27432690.post-55874672116310291402006-12-18T00:45:00.001-07:002007-01-29T10:07:37.457-07:00"This stream does not support seek operations."<p></p><p>I ran into a problem while reading binary data from a site for my web-spidering application that I was developing a couple of months ago. I was able to read text strings from few sites but failed on many websites because the ResponseStream was not seekable. See this code snippet <pre> </pre><pre class="code"><span style="COLOR: rgb(0,128,128)">HttpWebRequest</span> myRequest = (<span style="COLOR: rgb(0,128,128)">HttpWebRequest</span>)<span style="COLOR: rgb(0,128,128)">WebRequest</span>.Create(url);
<span style="COLOR: rgb(0,128,128)">HttpWebResponse</span> myResponse = (<span style="COLOR: rgb(0,128,128)">HttpWebResponse</span>) myRequest.GetResponse();
<span style="COLOR: rgb(0,0,255)">int</span> length = myResponse.ContentLength;</pre><a href="http://11011.net/software/vspaste"></a>The ContentLength property of the WebResponse object failed to retrieve the stream’s length and threw “This stream does not support seek operations” exceptions. I later realized that it was not actually a problem with the WebResponse object, but the way I intended to retrieve binary data from the web was not right. Ok, so how can I retrieve data out of this stream, say, a straight HTML text for further parsing? The best way to do this would be to copy this stream to a MemoryStream and finally convert it into a Byte Array. <pre> </pre><pre class="code"><span style="COLOR: rgb(0,128,128)">HttpWebRequest</span> myRequest = (<span style="COLOR: rgb(0,128,128)">HttpWebRequest</span>)<span style="COLOR: rgb(0,128,128)">WebRequest</span>.Create(url);
<span style="COLOR: rgb(0,128,128)">HttpWebResponse</span> myResponse = (<span style="COLOR: rgb(0,128,128)">HttpWebResponse</span>) myRequest.GetResponse();
<span style="COLOR: rgb(0,128,128)">Stream</span> respStream = myResponse.GetResponseStream();
<span style="COLOR: rgb(0,128,128)">MemoryStream</span> memStream = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,128,128)">MemoryStream</span>();
<span style="COLOR: rgb(0,0,255)">byte</span>[] buffer = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,0,255)">byte</span>[2048];
<span style="COLOR: rgb(0,0,255)">int</span> bytesRead = 0;
<span style="COLOR: rgb(0,0,255)">do
</span>{
bytesRead = respStream.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, bytesRead);
} <span style="COLOR: rgb(0,0,255)">while</span> (bytesRead != 0);
</pre><pre>respStream.Close();
buffer = memStream.ToArray();
<span style="COLOR: rgb(0,0,255)">string</span> html = System.Text.<span style="COLOR: rgb(0,128,128)">Encoding</span>.ASCII.GetString(buffer);</pre>
<p><a href="http://11011.net/software/vspaste"></a>Here, I am instantiating a new MemoryStream object, reading fixed bytes from the stream and copying it over to the MemoryStream. The Stream.Read() method reads a maximum of "bytesRead" bytes from the current stream and store them in the buffer. In the above example it reads a maximum of 2048 bytes each time, stores them in a buffer and finally write that into the MemoryStream. The method returns a 0 if there is no more data to be read. One important thing to be noted here is that the Stream.Read() method can return fewer bytes than requested (< 2048) even if end of the stream has not been reached.
</p>
<p>MemoryStream.ToArray() method finally converts it into a Byte Array. If the retrieved data is of plain-text type, which can be know from its headers, can be converted into a string using the System.Text.Encoding.ASCII.GetString(buffer) method. Else, write the byte array to a file using the FileStream object. </p>
<p>You will find this implementation very useful if you’re planning to download something and later resume broken downloads in your web-spidering applications….!</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com4tag:blogger.com,1999:blog-27432690.post-20950919380117639692006-12-03T22:15:00.000-07:002008-12-09T01:08:22.627-07:00TripleDES Encryption in .NET<p></p><p>Encryption of sensitive data is very important in most of the software applications today. In this feed I’ll show you how to encrypt and decrypt a string data using the encryption classes contained within .NET. The method I’m going to employ here is a “private-key” algorithm that uses one key to encrypt and the same key to decrypt the data. I’ll be using the TripleDES encryption algorithm which is considered to be very secure. It performs three times as much encryption as the standard DES. <p>DES, Data Encryption Standard, encrypts data using 64-bit or 8-byte blocks and employs 16 rounds of encryption to every block of data. It uses a key size of 56 bits, 8 bits reduced from 64 bits which serve as parity bits. As mentioned earlier, TripleDES, which performs 3 times the encryption as DES requires 168-bit key and encrypts each block three times. That is, each block of data is actually encrypted 48 times, making TripleDES more secure. <p>In this example, instead of using a 24-byte private key directly, I’m converting a pass phrase into a TripleDES key using the Hash Computation algorithm found in MD5CryptoServiceProvider class. I am doing this because the pass phrase makes more sense when you want to share the private key among those whom you want to share your secure data with. You definitely don’t want to memorize a private key of this kind {12, 26, 13, 44, 95,16,17,38,29, 10, 11, 22, 43, 24, 15, 56, 37, 78, 29, 27, 23, 52, 43, 4} to decrypt or encrypt your data. <p>Let’s look at the code now. To begin with, we’ll add a few namespaces. <pre><span style="COLOR: rgb(0,0,255)">using</span> System;
<span style="COLOR: rgb(0,0,255)">using</span> System.Text;
<span style="COLOR: rgb(0,0,255)">using</span> System.Security.Cryptography;</pre><a href="http://11011.net/software/vspaste"></a><pre>Add an initialization vector as the private member of that class. </pre><pre><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">string</span> Key = <span style="COLOR: rgb(128,0,0)">""</span>;
<span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">readonly</span> <span style="COLOR: rgb(0,0,255)">byte</span>[] IVector = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,0,255)">byte</span>[8] { 27, 9, 45, 27, 0, 72, 171, 54 };
</pre>
<p>An initialization vector is used to mask the encryption method in private-key algorithms as they are known to process data in blocks. In most general terms, a block cipher will move to the next block after encrypting each block of data using the same key. Say, if the alternate block has the same data, then the encrypted equivalent also would be having the same encrypted data because they were encrypted with the same key. An initialization vector, in combination with the private key, uses the previous block’s information in encrypting subsequent blocks thereby generating different encrypted data even though they’re the same. </p>
<p>The above initialization vector contains 8 bytes. This can be replaced with your choice. Take a look at the Encrypt Method. <pre> </pre><pre class="code"><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">string</span> Encrypt(<span style="COLOR: rgb(0,0,255)">string</span> inputString)
{
<span style="COLOR: rgb(0,0,255)">byte</span>[] buffer = <span style="COLOR: rgb(0,128,128)">Encoding</span>.ASCII.GetBytes(inputString);
<span style="COLOR: rgb(0,128,128)">TripleDESCryptoServiceProvider</span> tripleDes = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,128,128)">TripleDESCryptoServiceProvider</span>();
<span style="COLOR: rgb(0,128,128)">MD5CryptoServiceProvider</span> MD5 = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,128,128)">MD5CryptoServiceProvider</span>();
tripleDes.Key = MD5.ComputeHash(<span style="COLOR: rgb(0,128,128)">ASCIIEncoding</span>.ASCII.GetBytes(Key));
tripleDes.IV = IVector;
<span style="COLOR: rgb(0,128,128)">ICryptoTransform</span> ITransform = tripleDes.CreateEncryptor();
<span style="COLOR: rgb(0,0,255)">return</span> <span style="COLOR: rgb(0,128,128)">Convert</span>.ToBase64String(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));
}</pre>
<p>I’m first converting the plain text string to a byte Array since many cryptographic methods expect the data to be in this format. I’m then instantiating couple of objects, firstly, TripleDESCryptoServiceProvider which accepts the initialization vector and the private key, and secondly, MD5CryptoServiceProvider which is used to compute the Hash and create a valid TripleDES private key from the Pass Phrase that I was telling you about. The ICryptoTransform defines the basic operations of cryptographic transformations. The TransformFinalBlock method transforms the input byte array into an encrypted byte array by applying the private key and the initialization vector. This is finally converted into a Base64String and returns the encrypted string to the calling method. </p>
<p>The process of decrypting the data is very much similar to encrypting the data because they use exactly the same private key. The Decrypt method shown below does the decryption process. <pre> </pre><pre class="code"><span style="COLOR: rgb(0,0,255)">private</span> <span style="COLOR: rgb(0,0,255)">string</span> Decrypt(<span style="COLOR: rgb(0,0,255)">string</span> inputString)
{
<span style="COLOR: rgb(0,0,255)">byte</span>[] buffer = <span style="COLOR: rgb(0,128,128)">Convert</span>.FromBase64String(inputString);
<span style="COLOR: rgb(0,128,128)">TripleDESCryptoServiceProvider</span> tripleDes = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,128,128)">TripleDESCryptoServiceProvider</span>();
<span style="COLOR: rgb(0,128,128)">MD5CryptoServiceProvider</span> MD5 = <span style="COLOR: rgb(0,0,255)">new</span> <span style="COLOR: rgb(0,128,128)">MD5CryptoServiceProvider</span>();
tripleDes.Key = MD5.ComputeHash(<span style="COLOR: rgb(0,128,128)">ASCIIEncoding</span>.ASCII.GetBytes(Key));
tripleDes.IV = IVector;
<span style="COLOR: rgb(0,128,128)">ICryptoTransform</span> ITransform = tripleDes.CreateDecryptor();
<span style="COLOR: rgb(0,0,255)">return</span> <span style="COLOR: rgb(0,128,128)">Encoding</span>.ASCII.GetString(ITransform.TransformFinalBlock(buffer, 0, buffer.Length));
}</pre>
<p>This completes the encryption/decryption process of a string data by employing the classes and methods contained in the System.Security.Cryptography namespace. The screenshots of the sample application that I created is shown below.<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtzrIXVBm28TRFL6L_DDrqmOwB4egOU3NdAP8YqRrzaLPydC2xa0eM48nMzpUtOdEavXlmGiFg4CQWwiJ-MPi0uWhyprZsxOPKPNZEcxSjKjpmRFoazV2cxM0HtM0W6KjFashJVw/s1600-h/TripleDES.JPG"><img id="BLOGGER_PHOTO_ID_5025572913247909954" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; CURSOR: hand" alt="" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtzrIXVBm28TRFL6L_DDrqmOwB4egOU3NdAP8YqRrzaLPydC2xa0eM48nMzpUtOdEavXlmGiFg4CQWwiJ-MPi0uWhyprZsxOPKPNZEcxSjKjpmRFoazV2cxM0HtM0W6KjFashJVw/s320/TripleDES.JPG" border="0" /></a></p>
<p>You can create your own Encryptor/Decryptor class library with these methods and develop more secure enterprise applications. Some of the areas of interest would be like encrypting the Passwords before saving it to the database or encrypting the QueryStrings in your web applications.
<p>Hope this was helpful….</p>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com3tag:blogger.com,1999:blog-27432690.post-52321345278075976282006-09-27T22:15:00.000-06:002007-09-13T17:41:04.289-06:00Caching in Windows ApplicationI was working on a Windows Service lately that generated hundreds of documents by processing data retrieved from several database tables. Each time, the service accessed at least 10 lookup tables apart from getting data from various other ones to generate a single document. One thing that concerned me most was its sluggish performance that resulted from its repeated calls to the lookup/reference tables. </span> <div><span style="font-family: arial"><br>I was wondering if there was a way to add caching feature to my windows service, where all the lookup tables are stored locally for a specified duration of time and minimize the overall database calls. You know, caching is one of many such features that are strongly tied to ASP.NET web applications only. Guys at Microsoft encourage you to use Caching Application Block or the latest Enterprise library to enjoy the same features in windows applications. <br>I stumbled upon a <a href="http://support.microsoft.com/kb/884191" target="blank">Microsoft Knowledge base article</a> a while ago that suggests using alternative mechanisms such as ASP.NET Cache, 'coz the cache application block had inconsistencies with multithreaded applications. Exceptions occurred when several threads tried to update the cache at the same instance. This got me thinking; why not use the ASP.NET cache in my Windows service application. I'm telling you, this worked like a charm, enjoying the benefits of caching that a ASP.NET web application would provide. <br>Here's what I did… <br>I created a new Class Library Project named WinCaching in C#. Added a reference to System.Web.dll. (Convince your Code QA/review team, why you're referencing this namespace from a windows app) <br>In this class I exposed a public property called Cache which returns the HttpContext.Current.Cache or HttpRuntime.Cache based on the type of application it is. Say, if I'm accessing this property in a WinForms application, the HttpContext.Current.Cache would usually be null, eventually returning the HttpRuntime cache to the caller. The HttpRuntime class provides a bunch of ASP.NET run-time features to the current WinForms or Windows Service applications. <pre>
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Caching;
namespace WinCaching
{
public class Caching
{
public static Cache Cache
{
get
{
return (System.Web.HttpContext.Current == null) ? System.Web.HttpRuntime.Cache : </pre><pre>System.Web.HttpContext.Current.Cache;
}
}
}
}
</pre><span style="font-family: arial">All the other classes that needs to use the caching feature in your application will have to do so by accessing this property. I'll show you how… <br>Create a WinForms application, add a reference to the WinCaching class library that we created above. <br>To insert data into the cache with expiration time of 60 minutes you can write as <pre>
WinCaching.Caching.Cache.Insert("TestKey", txtName.Text, null, DateTime.Now.AddMinutes(60), TimeSpan.Zero);
</pre><span style="font-family: arial">Similarly, to retrieve the same data, you can access the property as <span style="color: #660000"><span style="color: #0000ff"></span></span></span>
<p></p>
<p><span style="font-family: arial">string s = WinCaching.Caching.Cache[<span style="color: #800000">"TestKey"</span>].ToString(); </span></p>
<p><span style="font-family: arial">This way, you can reuse the same library for your caching needs in Windows as well as Web applications. Hope this trick helps you in improving your application's performance. </span></p></span></div></span>Thinathayalan Ganesanhttp://www.blogger.com/profile/14628531167675149779noreply@blogger.com2