The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local

Challenge:

I was playing with nice and very useful class TimeZoneInfo in .NET Framework 3.5. Using which we can convert DateTime from SourceTimeZone to DestinationTimeZone by just one line.
[sourcecode language=”csharp”]
<pre>DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
try
{
TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
Console.WriteLine("{0} {1} is {2} local time.",
hwTime,
hwZone.IsDaylightSavingTime(hwTime) ? hwZone.DaylightName : hwZone.StandardName,
TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define the Hawaiian Standard Time zone.");
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the Hawaiian STandard Time zone has been corrupted.");
}
</pre>
[/sourcecode]
I was playing more with it and suddenly following error popped up when I selected My Source TimeoZone to “(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi” and Destination TimeZone to “(UTC) Dublin, Edinburgh, Lisbon, London”
System.ArgumentException was unhandled
Message=“The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly.  For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.\r\nParameter name: sourceTimeZone”
Source=”System.Core”
ParamName=”sourceTimeZone”
StackTrace:
at System.TimeZoneInfo.ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags)
at System.TimeZoneInfo.ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
at TimeZoneCoverter.Form1.button1_Click(Object sender, EventArgs e) in E:\TestHarness\TimeZoneCoverter\TimeZoneCoverter\Form1.cs:line 69
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at TimeZoneCoverter.Program.Main() in E:\TestHarness\TimeZoneCoverter\TimeZoneCoverter\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Solution:

I’ve faced this problem so long back, When I worked on this class for achieving one functionality. But as I haven’t blogged it [Due to deadlines :(] I can’t recall solution easily. But finally I got the solution and without wasting a minute I wrote it down here. So,  If in future you/me face this problem we can kill it quickly. So, here you go:
DateTime dateTimeToConvert = new DateTime(dateTimePicker1.Value.Ticks, DateTimeKind.Unspecified);
As shown in above code we’ve provided DateTimeKind to Unspecified. Earlier it as like this:
DateTime dateTimeToConvert = dateTimePicker1.Value; //Error prone code
HTH!
Happy TimeZoneInfo Coding! 🙂

2010 in review

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:
Healthy blog!
The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image
About 3 million people visit the Taj Mahal every year. This blog was viewed about 46,000 times in 2010. If it were the Taj Mahal, it would take about 6 days for that many people to see it.
 
In 2010, there were 32 new posts, growing the total archive of this blog to 125 posts. There were 40 pictures uploaded, taking up a total of 7mb. That’s about 3 pictures per month.
The busiest day of the year was November 23rd with 246 views. The most popular post that day was “The underlying connection was closed: The connection was closed unexpectedly.” While returning Data Table from WCF service..

Where did they come from?

The top referring sites in 2010 were google.co.in, forums.asp.net, google.com, consultingblogs.emc.com, and blogs.msdn.com.
Some visitors came searching, mostly for there is no script engine for file extension .vbs, there was an error while trying to serialize parameter, c multiple inheritance, and svn: can’t create tunnel: the system cannot find the file specified..

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

“The underlying connection was closed: The connection was closed unexpectedly.” While returning Data Table from WCF service. September 2008
12 comments

2

Hosting a WCF Service in IIS 7.0 September 2008
3 comments

3

IF…else with Eval is not supported+GridView+ASP.NET March 2008
4 comments

4

Checking Execution Time with C#.NET+ Use of it In WSSF+WCSF February 2008
1 comment

5

svn: Can’t create tunnel: The system cannot find the path specified. August 2009
2 comments

See you in 2011!

Thanks for flying with kiranpatils.WordPress.com in 2010.
I look forward to serving you again in 2011! Happy New Year!
Wish you a happy new year and happy coding! 🙂

SharpZipLib is not working When compression is enabled on IIS

Challenge:

Before so many months back I was facing problem related to SharpZipLib. Basically Using SharpZipLib we were zipping a file at runtime and allowing users to save that zipped file at his/her local machine. It works fine on my local box. But when we roll it out on another IIS server it was not working. [General developers problem :)].
When we delved more in to that, then found that another IIS server has been configured for “HTTP Compression“.

Solution:

Okay, so now we were knowing that Issue is due to IIS Server which has HTTP Compression enabled. Unfortunately we can’t disable it as it will affect the performance. So, now we just have one way to make it working which is through code. We tried lot and finally we found a way to do it, it was just one line change in our Response’s ContentType.
Before we see working code, let’s see the code which was having a problem:
[sourcecode languag=”csharp”]
private void DownloadZip(byte[ bufferzip)
{
// Load Zip file
if (bufferzip != null && bufferzip.Length > 0)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.ContentType = "application/zip"; //This line was causing a problem!
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=\"MyFile.zip\"");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.BinaryWrite(bufferzip);
HttpContext.Current.Response.End();
}
}
[/sourcecode]
Now, it’s time to see a working code!
[sourcecode languag=”csharp”]
private void DownloadZip(byte[ bufferzip)
{
// Load Zip file
if (bufferzip != null && bufferzip.Length > 0)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.ContentType = "application/octet-stream"; // This is real Hero!
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=\"MyFile.zip\"");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.BinaryWrite(bufferzip);
HttpContext.Current.Response.End();
}
}
[/sourcecode]
Now, if you compare the working and non working code you will see the difference. HttpContext.Current.Response.ContentType = “application/zip”; was causing an issue and changing it to HttpContext.Current.Response.ContentType = “application/octet-stream”; solved it!

Reference links:

http://community.sharpdevelop.net/forums/p/10467/28859.aspx#28859
http://www.jlaforums.com/viewtopic.php?t=7295390
http://support.microsoft.com/kb/841120
Happy Coding! 🙂

Would like to provide take snapshot of URL/Page in your ASP.NET application?

Challenge:

Few days back, my colleague asked me that how he can have functionality using which user can take snapshot of provided URL in his ASP.NET Application.

Solution:

I did also not know, but found the requirement very interesting. So. As usual had a chat with my best friend Google and found one nice tool named as IECapt.
I am not going to write how to use it, because someone has already done that. You can read it from here:
http://www.enestaylan.com/eng/post/2010/01/05/Taking-Snapshot-in-ASPNET.aspx
IECAPT Home Page: http://iecapt.sourceforge.net/
Just a note: IECapt# dll is also available. But it is not working with ASP.NET application. So, recommended way is to use IECapt.exe only!
Happy Sharpshooting! 🙂

Session values lost when any exception occurs

Challenge

If you’ve stored some values in session and your session values getting lost when any exception occurs. Then this article may provide you hint to solve it.

Solution

In my case the reason was as below:
Basically I was creating a directory under my web root directory and when any exception occurred I was deleting that directory. And that was the main reason for losing my session values.
So, Now I am creating/deleting directory outside my web root directory and problem is solved!
And deepest reason is Application Restart – Whenever any directory gets created/deleted under web root ASP.NET restarts the application pool. To read more about ASP.NET Application restart read my blog post.
Happy Coding! 🙂

directory

 

Could not load type 'System.Web.UI.ScriptReferenceBase' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Challenge

If you are getting following error:
Could not load type ‘System.Web.UI.ScriptReferenceBase’ from assembly ‘System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35′.
Then you are on the right article

Solution

It’s highly likely that you compiled your code using .NET 3.5 Service Pack 1 but deployed to a system that has .NET 3.5 without Service Pack 1.
ScriptReferenceBase is a new class for Service Pack 1, clearly a refactoring of ScriptReference to allow common code for the new CompositeScriptReference class. If you compile your code using SP1, you will include a reference to this class, which does not exist in .NET 3.5 pre-SP1. When the non-SP1 runtime tries to load the class, you will receive the exception above.
Solutions are:

  • Compile using .NET 3.5 without SP1.

OR

  • Install SP1 on the target system

 

Create PerfMon WebPage

Challenge

If you’ve used PerfMon – tool from microsoft for performance monitor. [if you haven’t then it is really good to use tool for monitoring your application’s performance once It is deployed on server. Try it today!].
While monitoring performance we need to run perfmon tool [START | RUN | perfmon]. But what if admins need to view it from web browser and it can be from anywhere.

Solution

Here’s the solution for that. We can configure perfmon to run inside a webpage [But you need IE!].
Step by step guide is here: http://www.myitforum.com/inc/arts/9435MMC%20to%20webpage.doc
Reference : http://www.myitforum.com/articles/15/view.asp?id=7407
Happy Performance Monitoring! 🙂

Merging two XML files in to one dataset

Challenge:

Since so long back one of my best buddy Devang asked me that how can we merge two Datasets in one. In short, suppose you’ve two XML Files and you want to read them in different dataset. So, obviously they both will belong to two different data sets. But you would like to have both of them in a single dataset. How can you do it?
Before you see the solution code. Let’s see the problem by code
[sourcecode language=”csharp”]
private const string FILE1_PATH = "~/Books1.xml";
private const string FILE2_PATH = "~/Books2.xml";
protected void Page_Load(object sender, EventArgs e)
{
// Read First Xml
DataSet dataSet1 = new DataSet();
dataSet1.ReadXml(Server.MapPath(FILE1_PATH));
// Read Second Xml
DataSet dataSet2 = new DataSet();
dataSet2.ReadXml(Server.MapPath(FILE2_PATH));
// Merge — Will not work
dataSet1.Merge(dataSet2);
// Read in Table — Will not work
dataSet1.Tables[0].ReadXml(Server.MapPath((FILE1_PATH)));
dataSet2.Tables[0].ReadXml(Server.MapPath((FILE2_PATH)));
// Merge DataSet2.Table in first dataset — WILL NOT WORK — DataTable already belongs to another DataSet.
dataSet1.Tables.Add(dataSet2.Tables[0]);
}
[/sourcecode]

Solution

When we try to use following line.
[sourcecode language=”csharp”]
// Merge DataSet2.Table in first dataset — WILL NOT WORK — DataTable already belongs to another DataSet.
dataSet1.Tables.Add(dataSet2.Tables[0]);
[/sourcecode]
It will throw following error:
DataTable already belongs to another DataSet.
System.ArgumentException was unhandled by user code
Message=”DataTable already belongs to another DataSet.”
Source=”System.Data”
StackTrace:
at System.Data.DataTableCollection.BaseAdd(DataTable table)
at System.Data.DataTableCollection.Add(DataTable table)
at _Default.Page_Load(Object sender, EventArgs e) in c:\TestHarness\MergeTwoXmlFiles\Default.aspx.cs:line 35
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
Reason fort an error is dataset2’s Table number 0 can’t be added to dataset1’s tables collection as it is already in dataset2’s tables collection — Recall Reference types?
So, final solution is as below:
[sourcecode language=”csharp”]</pre>
// Remove table from second dataset
DataTable dt = dataSet2.Tables[0];
dataSet2.Tables.Remove(dt);
// and add it to first one
dataSet1.Tables.Add(dt);
[/sourcecode]
Happy Dataset Merging! 🙂

1,00,000 blog hits… and Counting

Today we passed an impressive milestone of 1,00,000 blog hits and this not end this is just beginning because I know that you — my blog readers – will keep visiting, reading, and sharing my blog. Thanks to each and every visitor for contributing in to this count so all credit goes to you! — Thank you again!

100000 Blog hits
100000 Blog hits

I remember that I’ve started blogging from December 2007 and till today I’m learning how to write a good blog — yeah agree that each and every day I’ve learnt a lot!
Here’s the Stats Summary which I would like to share with you:


Quick Facts

  • Total Posts : 117
  • Total Comments : 246
  • Total Categories : 44
  • Total Tags : 73
  • Total Visits 2007 : 438
  • Total Visits 2008 : 23,606
  • Total Visits 2009 : 46,991
  • Total Visits 2010(Till today) : 29,117
  • Average Visits per Day : 124-129

Happy Reading! 🙂