ISO 8601/RFC 3339 Compatible Dates
Posted: October 4, 2009 Filed under: .NET General, Code | Tags: Dates, Extension Methods, ISO, RFC Leave a comment »There are not standard format specifiers for date that takes a date and converts it to an ISO 8601 or RFC 3339 compatible date. Here are two extension methods that does just that.
public static string ToISO8601(this DateTime date)
{
return date.ToString("yyyy-MM-dd");
}
public static string ToRFC3339(this DateTime date)
{
return date.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ");
}
Generating a Slug From a String
Posted: October 2, 2009 Filed under: .NET General, Code | Tags: Extension Methods, Slug, Unicode, url Leave a comment »I can’t (and won’t) take full credit for this extension method. The hardcore Unicode stuff is from Michael Kaplan’s blog (jeez, he is hardcore). There is a little danish “stuff” included, for special characters æ, ø and å, which can also be written “ae”, “oe” an “aa”.
public static string ToSlug(this string message)
{
// replace space with -
message = Regex.Replace(message, @"[\s/\\\.,+|_]+", "-");
// normalize the message
message = message.Normalize(NormalizationForm.FormD);
message = message.Replace("ø", "oe").Replace("Ø", "Oe").Replace("æ", "ae").Replace("Æ", "Ae").Replace("å", "aa").Replace("Å", "Aa");
StringBuilder result = new StringBuilder();
for (int i = 0; i < message.Length; i++)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(message[i]);
if (uc != UnicodeCategory.NonSpacingMark)
{
result.Append(message[i]);
}
}
return Regex.Replace(result.ToString().Normalize(NormalizationForm.FormC), @"[^a-zA-Z0-9\-]", "").ToLower();
}
MD5 Extension Method
Posted: September 29, 2009 Filed under: .NET General, Code | Tags: Extension Methods, hash, md5, Secure Hash 1 Comment »A nifty little extension method that generated the MD5/SHA-1 hash of a string. These methods are a continuation of my previous post:
public static string MD5(this string value)
{
System.Security.Cryptography.MD5 algorithm =
System.Security.Cryptography.MD5.Create();
byte[] data = Encoding.ASCII.GetBytes(value);
data = algorithm.ComputeHash(data);
string md5 = "";
for (int i = 0; i < data.Length; i++)
{
md5 += data[i].ToString("x2").ToLower();
}
return md5;
}
Just substitute MD5 for SHA1, SHA256, SHA384, SHA512 or RIPEMD160 which ever hash algorithm fits your needs.
Relative Time Description
Posted: September 28, 2009 Filed under: .NET General, Code | Tags: Dates, Extension Methods Leave a comment »Showing an absolute date on a webpage, e.g. January 22, 2009 13:01, is of course a very normal way to do it, apart from various different date formats, it is easily read and consumed. However if the date is shown in a context where the absolute date is of little importance, but it is more important to know if it was a long time ago, just now or maybe just in a couple of minutes, a relative and more descriptive method is better.
For example the date mentioned above might be described as “8 months ago”. Just by giving it a quick glance you get an idea about when this event occurred.
For this here are a couple of extension methods that generate this descriptive text based on a given time:
public static string ToRelativeTime(this DateTime from)
{
DateTime now = DateTime.Now;
return from.ToRelativeTime(now);
}
public static string ToRelativeTime(this DateTime from, bool usePreAndSuffix)
{
DateTime now = DateTime.Now;
return from.ToRelativeTime(now, usePreAndSuffix);
}
public static string ToRelativeTime(this DateTime from, DateTime to)
{
return from.ToRelativeTime(to, true);
}
public static string ToRelativeTime(this DateTime from, DateTime to, bool usePreAndSuffix)
{
string prefix = usePreAndSuffix && (from > to) ? "in " : string.Empty;
string suffix = !usePreAndSuffix || (from > to) ? string.Empty : " ago";
// is more than 1 year?
if (from > to)
{
DateTime d = from;
from = to;
to = d;
}
int years = to.Year - from.Year;
if ((to.Month < from.Month) || ((to.Month == from.Month) && (to.Day < from.Day)))
{
years--;
}
if (years > 1)
{
return string.Format("{0}{1} years{2}", prefix, years, suffix);
}
else if (years == 1)
{
return string.Format("{0}1 year{1}", prefix, suffix);
}
// less than 1 year, is more than 1 month?
int months = to.Month - from.Month;
if (months < 0)
{
months += 12;
}
if ((to.Day < from.Day) || ((to.Day == from.Day) && (to.TimeOfDay < from.TimeOfDay)))
{
months--;
}
if (months > 1)
{
return string.Format("{0}{1} months{2}", prefix, months, suffix);
}
else if (months == 1)
{
return string.Format("{0}1 month{1}", prefix, suffix);
}
// less than 1 month, is more than 1 day/week?
TimeSpan diff = to - from;
if (diff.Days > 7)
{
return string.Format("{0}{1} weeks{2}", prefix, diff.Days / 7, suffix);
}
else if (diff.Days > 1)
{
return string.Format("{0}{1} days{2}", prefix, diff.Days, suffix);
}
else if (diff.Days == 1)
{
return string.Format("{0}1 day{1}", prefix, suffix);
}
// less than 1 day, is more than 1 hour?
if (diff.Hours > 1)
{
return string.Format("{0}{1} hours{2}", prefix, diff.Hours, suffix);
}
else if (diff.Hours == 1)
{
return string.Format("{0}1 hour{1}", prefix, suffix);
}
// less than 1 hour, is more than 1 minute?
if (diff.Minutes > 1)
{
return string.Format("{0}{1} minutes{2}", prefix, diff.Minutes, suffix);
}
else if (diff.Minutes == 1)
{
return string.Format("{0}1 minute{1}", prefix, suffix);
}
// less than 1 minute
if (diff.Seconds == 1)
{
return string.Format("{0}1 second{1}", prefix, suffix);
}
else if (diff.Seconds < 1)
{
return string.Format("{0}less than 1 second{1}", prefix, suffix);
}
return string.Format("{0}{1} seconds{2}", prefix, diff.Seconds, suffix);
}
This can of course be optimized for localization etc.
ADO.NET Entitity Framework vs. LINQ to SQL
Posted: November 1, 2008 Filed under: .NET General | Tags: ado.net, entity framework, linq to entities, linq to sql 1 Comment »I have never been a huge fan of all the ADO.NET stuff – one exception: the DataReader. Everything else seems to me just to be bloated functionality around what I really need. How ADO.NET handles connections and commands are in my opinion overly "complex" – not that they are complex in any way, they could just be done way simpler. Whenever I have been writing code that access a database, I tend to rely on my trusted companion: the Enterprise Library. It provides such a nice and clean abstraction to the unneeded (IMHO) overhead posed by Connection, Command and Parameter handling.
Compare:
Database db = DatabaseFactory.CreateDatabase("my connectionstring");
using (IDataReader reader = db.ExecuteReader("my stored procedure", "my parameter 1", myParameter2, etc))
{
// do my thang
}
To:
using (SqlConnection conn = new SqlConnection("my connectionstring"))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "my stored procedure";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.CreateParameter();
param.ParameterName = "@param1";
param.DbType = DbType.String;
param.Value = "my parameter 1";
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "@param2";
param.DbType = DbType.Int32;
param.Value = myParameter2;
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "@param3";
param.DbType = DbType.Int32;
param.Value = etc;
cmd.Parameters.Add(param);
using (IDataReader reader = cmd.ExecuteReader())
{
// do your thang
}
}
And don’t get me started on the DataSet…
Now, MS has implied that LINQ to SQL will be deprecated and focus will be moved to the ADO.NET Entity Framework and LINQ to Entities. This has already stirred up the .NET community: David Hayden, Ian Cooper, Ayende Rahien to name a few.
I have never really considered using LINQ to SQL in big applications, mainly because I think LINQ to SQL imposes some constraints on my applications – one simple thing like the “low coupling” principle is not something that comes out of the box, it has to be tweaked and twisted to even give just a hint of low coupling. However I see LINQ to SQL as a very, very nice low-level method to create a basic SQL based data foundation.
For example, I am privately playing around with a blog engine based on ASP.NET MVC and LINQ, both XML and SQL. In this case LINQ to SQL is near-perfect for my needs. It provides sufficient abstraction from the database without imposing too much overhead, by providing flexibility in all future scenarios if the database suddenly need to be converted to an Oracle DB or refactored/de-normalized due to poor performance or whatever. It allows me to write SQL like-statements that (to a large extent) is verified at compile time. Sure I could do the same in LINQ to Entities, but it feels like firing up a super-tanker for something that really just need to be according to the KISS principle. LINQ to SQL is to a large extent very much KISS’ish, and fits perfectly in to the use I required for my playground project here.
I like to throw in this favorite quote of mine:
"Perfection is not when there’s nothing to add, but when there’s nothing to take away."
- Antoine de Saint-Exupéry
Or Occam’s Razor for that matter:
“All other things being equal, the simplest solution is the best”
Another thing about LINQ to Entities (and this is just based on a my brief experience with the ADO.NET Entity Framework), the designers within Visual Studio are not very good pretty bad very bad.
When creating a new “ADO.NET Entity Data Model” it does allow a reverse engineering possibility for an existing database. The model you end of with is simply a 1:1 mapping between entities and tables, i.e. the Active Record pattern. This is fine, but LINQ to SQL does the same – again “supertanker”. The Entity Framework is designed to be an abstraction of your database not “just” an Active Record pattern, i.e. your data model does not need to reflect your database schema in a 1:1 mapping. This is pretty neat, and can be useful, especially on larger projects where you are not creating the database schema yourself, or you are working on top of an existing SQL database. BUT if I create a very simple SQL database for a very specific scenario, I don’t really need this.
Another thing that is very bad in the designers is that once your model has been reverse engineered and you want to begin modifying/abstracting it, things get very, very tedious. The tools in the designer are not helping very much, i.e. apa
rt from initial reverse engineering the database, utilizing the schema meta data to create properties etc. is not possible. The model is (granted) fairly intuitive, but the task of adding properties that map to columns, etc. is just overly “complex” (again complex in as it could be done way simpler).
The key feature of the Entity Framework to work on-top of any database has also on my first shot failed. Maybe it is poor database design, I’m not really a DBA so I’ll let others be the judge of that. But I have a scenario where I have a n:n relation between two tables – Person and Group. But instead of having the foreign keys in my cross reference table being the primary key hereof, I have an explicit primary key:
When creating the ADO.NET Entity Data Model in Visual Studio (by reverse engineering).
That is of course fair enough, so I remove the PersonGroup entity and create a many-many association between Person and Group with the following setup:
I get this error:
Error 3025: Problem in Mapping Fragment starting at line 115: Must specify mapping for all key properties (PersonGroup.Id) of table PersonGroup.
You also have to map ALL columns in the database to properties in the entity model, maybe I don’t what that! What if my entity model is really built on top of an already running database, and my job is to create a another user interface for e.g. a mobile device which requires just a subset of the database schema. I don’t want to map the entire shebang, for one because it is very tedious and second because the rest of the schema might contain sensitive information that should not be exposed on the mobile device (or whatever reason).
What is it with that homemade Entity-SQL stuff, that really smells too much like reinventing the wheel – we already have SQL (a standard) which on top of that has T-SQL and then we have LINQ in our managed code – this is really enough query languages for one application! Do we really need yet another proprietary query language (although it has a lot of similarity with SQL – but so does T-SQL and LINQ)? I don’t think so!
Not to mention that for demoing LINQ to SQL is just perfect – however I don’t (sadly) think that could justify MS investments in the LINQ to SQL framework alone.
This is just my gut feeling, maybe it has no substance when it comes to reality! But one thing I know is: I like LINQ to SQL for what it is, but equally much for what it isn’t.
Please prove me wrong!
Cool upcoming .NET stuff from Microsoft
Posted: September 13, 2008 Filed under: .NET General, ASP.NET | Tags: ASP.NET, MVC, On .NET, Oslo, Silverlight, upcoming, Velocity, Zermatt 1 Comment »Silverlight 2.0
Version 2.0 of the ubercool Silverlight, Microsoft’ pendant to Adobe Flash, is drawing nigh. Currently available as beta 2, release in june ’08. Silverlight 2.0 allows embedded code client-side, by some magic, that does not even require having the .NET framework installed on the client.
ASP.NET MVC Framework
Quoting the ASP.NET MVC page:
ASP.NET MVC enables you to build Model View Controller (MVC) applications by using the ASP.NET framework. ASP.NET MVC is an alternative, not a replacement, for ASP.NET Web Forms that offers the following benefits:
- Clear separation of concerns
- Testability – support for Test-Driven Development
- Fine-grained control over HTML and JavaScript
- Intuitive URLs
References: Official page, Scott Guthrie MVC Preview 5 Release post
Zermatt
Quoting Zermatt home page:
Zermatt is a framework for implementing claims-based identity in your applications. By using it, you’ll more easily reap the benefits of the claims-based identity model described in this paper.
References: Official page, Vittorio Bertocci blog, Keith Brown blog
Velocity
Quoting Velocity Blog
(…) a distributed caching product to provide the .NET application platform support for developing highly performant, scalable, and highly available applications.
References: Velocity blog
Oslo
Quoting the official Oslo page:
”Oslo” is the codename for Microsoft’s forthcoming modeling platform. Modeling is used across a wide range of domains and allows more people to participate in application design and allows developers to write applications at a much higher level of abstraction. “Oslo” consists of:
- A tool that helps people define and interact with models in a rich and visual manner
- A language that helps people create and use textual domain-specific languages and data models
- A relational repository that makes models available to both tools and platform components
References: Official page, Douglas Purdy – "What is Oslo?", Don Box blog, Various MS SOA articles (incl. non Oslo stuff)
Must have tools for .NET developers
Posted: September 12, 2008 Filed under: .NET General, Reference Sheet | Tags: ASP.NET WPF, On .NET, tools Leave a comment »Like so many others have done before me I would like to present my take on a compiled list of favorite tools for developing using .NET.
Here goes:
The most useful tool ever to reverse engineer assemblies – yes, it is a gray-zone regarding IP, but nonetheless very, very use full. Kudos to Lutz Roeder for this ultimate tool, and thank you very much for your effort in this. Lutz announced some days ago that he would end his work on Reflector. Red Gate (known for their useful tool SQL Compare – as mentioned later on
) has taken over and "(…) will continue to maintain a free version for the benefit of the community". Do they implicitly say that there will be a commercial version!? I hope not – that would for sure have some effect on the Reflector community.
I really, really hate to include a commercial product in my toolbox, but being there are no free alternatives to a much required tool, I will include the best one I know of (or rather the only one I have used, but it is extremely useful and good so why bother with the others!?). Please drop a comment if you know of free and/or good/better alternatives. Price tag on the basic SQL Compare is $395.
Query Analyzer for LINQ. Very nice tool to help build, execute and debug queries, wether it be LINQ for SQL, LINQ for Objects or LINQ for XML.
StyleCop is a Visual Studio plug-in that performs code analysis directly on source code with the intent on enforcing a common coding standard for layout, readability, documentation and maintainability. SDK documentation for creating custom rules is available. StyleCop was originally created by one devoted (and might I add brilliant) Microsoft employee (Jason Allor) in his spare time. The tool has been used internally in Microsoft for years, but was first made available to the general public earlier this year. Follow Jason’s/the StyleCop blog here.
FxCop is a tool to analyze managed assemblies for possible security issues and possible design and performance improvements that can be implemented.
Sorry, but yet another commercial product. If you are using the most excellent version control system Subversion (if not then consider it!), there is a most excellent plug-in for Visual Studio. Comes with a free server version as well, which simplifies setup of Subversion on a Windows box. A free alternative – however I did not find it nearly as good as Visual SVN – is AnkhSVN. Neither unfortunately though are MSSCCI (Microsoft Source Code Control Interface) which means that they do not plug-in to the native source control module in Visual Studio. Price tag for Visual SVN is $49. For more information about Subversion you can read the SVN Book online.
For ASP.NET Developers
Must haves:
Firefox with Firebug and Web Developer Toolbar
Firefox speaks for itself, and so should Firebug, but a brief introduction: Firebug allows you to inspect and modify HTML, CSS and DOM. Debugging JavaScript and explicitly capture JavaScript XmlHttpRequest calls for debugging AJAX. The Web Developer Toolbar provides some additional functionality to what Firebug adds, but to some extent is a complimentary plugin.
Internet Explorer with Developer Toolbar
It is inevitable that as a web developer you need to assure cross-browser compatibility. Therefor a similar tool exists for Internet Explorer 6 and 7, however it not nearly as cool, so for general debugging, etc. Firebug is the choice, but for IE specific, the Internet Explorer Developer Toolbar does come handy.
Another tool that can help in debugging web applications/services is Fiddler. Fiddler acts as a HTTP proxy, logging all HTTP traffic from the local computer to other computers. This however means that out-of-the-box HTTP debugging when using Cassini (i.e. the development web "server" in Visual Studio) is not possible. It has to be tweaked.
For WPF / Silverlight Developers
Kaxaml is a lightweight XAML editor with the split design / output view similar to the Visual Studio IDE. Kaxaml is a complimentary tool to Expression Blend, however Blend provides much more functionality, hence "lightweight".
Mole is a reverse engineering tool, similar to Reflector. However Mole disassembles the XAML of a WPF/Silverlight application and provides a tree view of the XAML structure. Nice for "how did they do that", but again gray zone concerning IP.
"Dark Horses"
Since I have not had any real experience with these I will put them on a "dark horse" list, just for reference, since they might prove themselves valuable given the time/opportunity to use them.
Quoting the FDS site:
Framework Design Studio is a set of tools for reusable library designers. The package contains a GUI tool for viewing, reviewing, and comparing versions of managed APIs. It also contains a command line tool for generating API diff reports. Simple user guide explaining the basics of the tool is included in the setup.
Temporary Stream
Posted: July 28, 2008 Filed under: .NET General, Code | Tags: stream Leave a comment »Scenario: you need to store a large block of data, e.g. as the result of an XSL transformation on an XML document. Using a MemoryStream would simply kill your server/application since it would use too much memory. Using a FileStream can be a but tedious since it would require write permissions on a specific folder…
Wait, doesn’t this sound just like a temporary file, i.e. storing a file in the TEMP path.
Yes, it does – and a simple solution is actually just to use a FileStream with a twist:
public class TempFileStream : FileStream
{
public TempFileStream()
: base(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite)
{
}
public override void Close()
{
base.Close();
if (File.Exists(Name))
{
File.Delete(Name);
}
}
}
Here we simply create a new temporary file with R/W access. In the Close method of the FileStream we simply delete the file. Nice and simple and your temporary file only "lives" during your "using" statement…
FormsAuthentication.HashPasswordForStoringInConfigFile() continued…
Posted: July 27, 2008 Filed under: .NET General | Tags: ASP.NET, formsauthentication, hash, md5 1 Comment »In "response" to my own previous post: two little extension methods that does exactly what "we" need:
public static string GetHashValue(this MD5 hash, string value)
{
return GetHashValue(hash, Encoding.UTF8.GetBytes(value));
}
public static string GetHashValue(this MD5 hash, byte[] value)
{
byte[] data = hash.ComputeHash(value);
string md5 = "";
for (int i = 0; i < data.Length; i++)
{
md5 += data[i].ToString("x2").ToLowerInvariant();
}
return md5;
}
Usage:
MD5 md5 = MD5.Create();
Console.WriteLine(md5.GetHashValue("test"));
Using Type.IsAssignableFrom() to check inheritance
Posted: July 13, 2008 Filed under: .NET General, Reference Sheet | Tags: inheritance Leave a comment »Having been in the situation needing to check if a given instance of an object either implements an interface or a class in the form of a given Type object (i.e. "if A is B" wont do) I decided to write a little "note to self" post which others might find useful.
This is basically just a "wrapper" around Scott Hanselman’s post from a long time ago Does a Type Implement an Interface?
For a "class type" you can use the Type.IsSubclassOf() method and for an interface you can use something in the line of:
{
// MyClass implements IMyInterface
}
However the string literal looks bad also neither solution provides a simple check for "is this type implementing/a subclass of this interface/class".
The gist of Scott’s post is that using Type.IsAssignableFrom() can solve your problem concerning interfaces, but the same logic applies for classes. So:
{
// MyClass implements IMyInterface
}
if (typeof(MyClass).IsAssignableFrom(typeof(MySubClass)))
{
// MySubClass is a subclass of MyClass
}
if (typeof(IMyExtendedInterface).IsAssignableFrom(typeof(IMyInterface)))
{
// IMyExtendedInterface extends IMyInterface
}
Actually this is exactly what the MSDN page for Type.IsAssignableFrom() states:
true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c
First in "layman" terms it means:
TypeB b;
if (typeof(TypeA).IsAssignableFrom(typeof(TypeB)))
{
a = b; // this will work
}
But what does the underlined text then mean in the context of this check? The samples on this on the MSDN page are totally nonsense (e.g. text states "List<int> assignable from List<Type>" but in fact List<int> and int[] are compared).
The point in that statement is that A<T> is assignable from A<S> if T is assignable from S.
So it is a little more inclusive (which is no surprise) than just checking inheritance, but as long as the "master" class/interface is known explicitly (which is most often the case, since a scenario for this is checking if a type specified in config is in the correct inheritance tree) the check will be safe.