So the day has dawned, very symbolic that this day happens to be the first of a new year… enough of that. The day has finally come where I post a JavaScript entry! Who would have thought that???
Over the last couple of months I have had a very passionate relationship with a new hottie I discovered. She is named jQuery and OMG can she do tricks… OK, stop this talk right now
Basically I have had my head in AJAX for ASP.NET doing what others before already realized probably wasn’t the best approach. Finally I got around to have a look at jQuery and I must admit that (especially for my ASP.NET MVC project(s)) I haven’t looked back!!!
Today I had a little feature I wanted to solve with some AJAX:
I have a list of objects displayed in a certain view. One property on these objects is calculated and involved some semi-heavy database and calculation stuff and therefore requires both time and system resources to get. This value is not in particular important to the current view, but is a nice-to-have information. This means that the value as such does not need to appear in the view after rendering. I therefore figured it could be nice to have in a dynamic tooltip, i.e. “on tooltip hover, calculate/retrieve the value and display it as a tooltip”.
Having used other of Jörn Zafferer jQuery plug-in’s previously (with great success) I turned my attention to his tooltip plugin.
Having read the documentation it is apparent that, while you can specify a callback function (namely the “bodyHandler” property) to determine which “value” to display in the tooltip, there is an issue with this: it is synchronous! And by definition AJAX is asynchronous. The problem here is that if you do a $.get() call you the return value of the bodyHandler callback is “out of scope”, since it is first available once the AJAX call is completed, i.e.:
bodyHandler: function() {
$.get("/MyController/MyAction", { id : "myid" }, function(data) { /* do what with "data"? */; }, "html");
},
showURL: false
});
My solution to this was the following:
bodyHandler: function() {
var result = $("<span/>").html("some loading indicator");
$.get("/MyController/MyAction", { id: "myid" }, function(data) { result.html(data); }, "html");
return result;
},
showURL: false
});
I think that is pretty nifty! Of course the “some loading indicator” can be tweaked (e.g. use a AJAX load indicator). And this is of course not specific to ASP.NET MVC!
UPDATE:
There is a problem with this approach! The jQuery tooltip plugin used seems to invoke the bodyHandler callback directly “on mouse over”, ie. not after the delay. This means that although the tooltip displays nicely after the specified delay, the Ajax call was performed at T=0. What this effectively means is that if you eg. have a table where all values in column 1 have this Ajax-tooltip-thingy. If you then move the mouse in over a couple of the values each time you the cursor is over the value an Ajax call is executed. Not so good unless you want to utilize all resources in your server
Back to the drawing board…
19
ASP.NET MVC HtmlHelper methods and CSS class
4 Comments · Posted by veggerby in ASP.NET MVC
If you in ASP.NET MVC use a Html helper method to render out e.g. an input box:
Sometimes you might need to add an CSS class attribute to your input box (this should be a fairly standard thing). For this there exist overload methods that takes a “htmlAttributes” parameter of type object. Now my experience with this is somewhat similar to Ayende Rahien experience – although I have not begun banging my head against the wall out of frustration. This is not a rant, I love ASP.NET MVC, I just had an experience with something simple that was hard to figure out because of some of the design decisions – not that they are bad, they can just be confusing – especially with the lack of documentation at the current stage (yes, I know it is just a beta). So if you try this:
You will (of course) get a compiler error, since “class” is a keyword and cannot be used like this. So how do you specify the class? Well, like this:
Just for future reference
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:
using (IDataReader reader = db.ExecuteReader("my stored procedure", "my parameter 1", myParameter2, etc))
{
// do my thang
}
To:
{
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!
13
Cool upcoming .NET stuff from Microsoft
1 Comment · Posted by veggerby in .NET General, ASP.NET
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)
ASP.NET · MVC · On .NET · Oslo · Silverlight · upcoming · Velocity · Zermatt
12
Must have tools for .NET developers
No comments · Posted by veggerby in .NET General, Reference Sheet
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.
ASP.NET WPF · On .NET · tools
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 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…
27
FormsAuthentication.HashPasswordForStoringInConfigFile() continued…
1 Comment · Posted by veggerby in .NET General
In "response" to my own previous post: two little extension methods that does exactly what "we" need:
{
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:
Console.WriteLine(md5.GetHashValue("test"));
ASP.NET · formsauthentication · hash · md5
16
Using ASP.NET Development Server in Firefox
No comments · Posted by veggerby in Uncategorized
Scott Mitchell wrote a post about performance using Cassini (the "integrated" Development Server in ASP.NET) when running sites under Firefox. Having myself been living with this issue for a long time, but just blamed my dev setup, this news is sweet music in my ears.
Just did the "network.dns.ipv4OnlyDomains" fix (i.e. about:config -> set network.dns.ipv4OnlyDomains to "localhost") and everything seems like I just received the latest state-of-the-art dev machine (well almost
).
Therefor if you have not done it already, what are you waiting for go right ahead! Just type about:config in your location bar.
13
Using Type.IsAssignableFrom() to check inheritance
No comments · Posted by veggerby in .NET General, Reference Sheet
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.
6
Abuse of FormsAuthentication.HashPasswordForStoringInConfigFile() method?
3 Comments · Posted by veggerby in .NET General, ASP.NET
I can’t help but get a annoyingly creepy feeling whenever I see people using FormsAuthentication.HashPasswordForStoringInConfigFile() to generate a hash cipher for a given value (for example here). On the other hand I can’t really decide wether I think it is the method which has a bad name/should be "located" somewhere else or it is the "abuse" of it as it is today.
If we look at the actual implementation of HashPasswordForStoringInConfigFile using Reflector:
{
HashAlgorithm algorithm;
if (password == null)
{
throw new ArgumentNullException("password");
}
if (passwordFormat == null)
{
throw new ArgumentNullException("passwordFormat");
}
if (StringUtil.EqualsIgnoreCase(passwordFormat, "sha1"))
{
algorithm = SHA1.Create();
}
else
{
if (!StringUtil.EqualsIgnoreCase(passwordFormat, "md5"))
{
throw new ArgumentException(SR.GetString("InvalidArgumentValue", new object[] { "passwordFormat" }));
}
algorithm = MD5.Create();
}
return MachineKeySection.ByteArrayToHexString(algorithm.ComputeHash(Encoding.UTF8.GetBytes(password)), 0);
}
The net result of this of course is that you do get the MD5/SHA1 hash of the password or value.
However the method name is HashPasswordForStoringInConfigFile, i.e. the name suggests it is for hashing passwords and further more it is a method of a class called FormsAuthentication… see a pattern!? The name does not suggest it is a generic MD5 method (although the implementation shows it is that).
IMHO using HashPasswordForStoringInConfigFile as a generic MD5 calculation method does nothing but make code less readable and hence harder to maintain. The very, very least a developer can do is to comment the code, but we all know when that’ll happen…
Look at the alternative:
{
MD5 algorithm = MD5.Create();
byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
string md5 = "";
for (int i = 0; i < data.Length; i++)
{
md5 += data[i].ToString("x2").ToLowerInvariant();
}
return md5;
}
The ONLY problem with not doing this stuff yourself is the conversion from a string and back to a string…
Yes, this might be a little slower due to the string stuff, but you can always "inherit"
the MachineKeySection.ByteArrayToHexString method.
The point is that using FormsAuthentication.HashPasswordForStoringInConfigFile to calculate all MD5/SHA-1 hash values just because the implementation happens to support this seems wrong. Writing this I think I actually blame Microsoft the most for not providing this method somewhere else and named more appropriately.
That was just a little rant…
ASP.NET · formsauthentication · hash · md5
