Colin Cochrane

Colin Cochrane is a Software Developer based in Victoria, BC specializing in C#, PowerShell, Web Development and DevOps.

.NET Code Tips: Converting A UNIX Timestamp To System.DateTime

After having to deal with UNIX timestamps in an application I am currently developing, I realized that there's probably a few people out there who are wondering how to convert a UNIX timestamp into a useable System.DateTime in a .NET application. 

Well the good news is that it's quite simple.  All a UNIX timestamp represents is the number of seconds since January 1st, 1970 12:00:00 AM.  So all we have to do is create a new System.DateTime structure, set it to 1/1/1970 12:00:00 AM, and use the AddSeconds() methods to tack on the timestamp.

Visual Basic:

   1: Function ConvertTimestamp(ByVal timestamp as Double) As DateTime
   2:     Return New DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp)
   3: End Function

C#:

   1: static DateTime ConvertTimestamp(double timestamp)
   2: {
   3:   return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp);
   4: }

 

Keep in mind that this method will return the time as Coordinated Univeral Time (UTC), so if you want to convert the value to local time you can simply modify the procedure as follows:

Visual Basic:

   1: Function ConvertTimestamp(ByVal timestamp as Double) As DateTime
   2:     Return New DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp).ToLocalTime()
   3: End Function

C#:

   1: static DateTime ConvertTimestamp(double timestamp)
   2: {
   3:   return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp).ToLocalTime();
   4: }

It's that easy to turn a UNIX timestamp into a .NET System.DateTime object. 

Happy coding!

Visual Studio 2008 Initial Impressions - Part One

The release of Visual Studio 2008 and the .NET Framework 3.5 this past Monday has created a considerable buzz in the .NET community.  With language enhancements such as LINQ (Language Integrated Query) and lambda expressions as well as a plethora of refinements to the IDE itself there are a lot of new tools available at our disposal now.  I was very eager to get acquainted with these new tools so I installed a copy of Team Edition and spent almost every free moment this week familiarizing myself with them.  Here are some of my initial impressions.

1) LINQ To SQL Classes

I work with a lot of applications that depend heavily on a backend database, so I've coded my fair share of business logic layers which can be quite tedious.  LINQ To SQL Classes take a lot of the grunt work out of that process by providing a convenient visual designer that performs automatic object-relational mapping.  All you have to do is drag a table or stored procedure from the Server Explorer to the design window and the designer automatically creates a strongly-typed object or method that is ready for use in your application.




2) Intellisense Enhancements

There were a couple of really nice usability enhancements to Intellisense in Visual Studio 2008.  Now, as you type, the Intellisense list automatically filters the list down based on what you've entered in so far.  For instance, if you have entered "MyObject.ToS" the list would be filtered to only show the items that start with "ToS", which does a nice job of speeding things up.  The other enhancement addresses the issue that many people had with previous versions of Visual Studio and the way that the Intellisense list would often obscure chunks of your code, forcing you to close the window if you had to check something that was underneath it.  Now you just have to hit "Ctrl" while the list is open and it will become semi-transparant, allowing you to see the code underneath.

 



3) Improved IDE Performance

Not a "feature", necessarily, but a welcome improvement to Visual Studio.  You'll notice this as soon as you load the environment for the first time and discover how quickly the environment loads.  The performance improvements don't stop there either, as the IDE is a lot faster and responsive throughout.


Stay tuned for Part Two where I'll go in to some more features of LINQ as well as some of the language upgrades given to Visual Basic.

SEO Best Practices - Dynamic Pages in ASP.NET

kick it on DotNetKicks.com

One of the greatest time-savers in web development is the use of dynamic pages to serve up database driven content.  The most common examples of which are content management systems and product information pages.  More times than not these pages hinge on a querystring parameter such as /page.aspx?id=12345 to determine which record needs to be retrieved from the database and output to the page.  What is surprising is how many sites don't adequatly validate that crucial parameter.

Any parameter that can be tampered with by a user, such as a querystring, must be validated as a matter of basic security.  That being said, this validation must also adequately deal with a situation when that parameter is not valid.  Whether the parameter is for a non-existant record, or whether the parameter contains letters where it should only be numbers, the end-result is the same: the expected page does not exist.  As simple as this sounds there are countless applications out there that seem to completely ignore any sort of error handling, and are content to have Server Error in "/" Application be the extent of their error handling.  Somewhere in the development cycle the developers of these application decided that the default ASP.NET error page would be the best thing to show to the site's visitors, and that a 500 SERVER ERROR was the ideal response to send to any search engine spiders that might have the misfortune of coming across a link with a bad parameter in it.

With a dynamic page that depends on querystring parameters to generate its content, the following basic measures should be taken:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load    
'Ensure that the requested URI actually has any querystring keys
If Request.Querystring.HasKeys() Then

'Ensure that the requested URI has the expected parameter, and that the parameter isn't empty
If Request.Querystring("id") IsNot Nothing Then

'Perform any additional type validation to ensure that the string value can be cast to the required type.

Else

Response.StatusCode = 404

Response.Redirect("/404.aspx",True)

End If

Else

Response.StatusCode = 404

Response.Redirect("/404.aspx",True)

End Sub


This is a basic example, but demonstrates how to perform simple validation against the querystring that will properly redirect anyone that reaches the page with a bad querystring in the request URL.  A similar approach should be taken when attempting to retrieve the data in the case that the record is not found.

Another useful trick is to define the default error redirect in the web.config file (<customErrors mode="RemoteOnly" defaultRedirect="/error.aspx">), and use that page to respond to the error appropriately by using the Server.GetLastError() method to get the most recent server exception and handling that exception as required.

There are many other ways to manage server responses when there is an error in your ASP.NET application.  What is most important is knowing that you need to handle these errors properly, up to and including an appropriate response to the request.