Tag | Extension Methods Posts

I was recently combing through my code and adding HTMLEncode()s where necessary. By the way, don't leave this to the end - you have no excuse since you're reading this post. The first thought that comes to mind to add this is simple, add a central function, perhaps a shared (vb) or static (c#) function to handle this. It'd likely look something like: Public Function HTMLEncode(ByVal s As String) As String Return If(Not String.IsNullOrEmpty(s), System.Web.HttpUtility.Html... s) End Function ...
When .NET 2.0 was released, a TryParse() method was added to many value types such as Int32, DataTime, etc. This was a huge improvement because there was no longer a need to catch expensive exceptions and drag down performance. However, one drawback of the TryParse() method is that the syntax is a little clunky. The most common example looks like this: 1: Person person = new Person(); 2: string value = "21"; 3: int num; 4: int.TryParse(value, out num); 5: person.Age = num; So it's great that we can ...
It is now past 10:00 PM, and my first day of Nothin but .net is over. It's been a very intense day. Jean-Paul Boodhoo is taking us off the beaten paths of MSDN style development, and tries to stretch our minds to think out of the box. First, we spent quite a while verifying the prep exercises. A good effort was made by everyone to finish it. The solution that got selected as the starting point for our source repository was the design that adhered best to the open/closed principle. This design used ...
Introduction I recently starting fooling around with the new XML LinQ stuff in .Net, and it is very impressive. One thing that I found missing was the ability to serialize objects directly into XElements. However, Microsoft did provide the means to get me to hit the ground running and it took a couple of minutes for me to get it right. Readers and Writers One thing the classical .Net XML always lacked was an "XmlNodeWriter", a writer that basically allows you to create DOM XML nodes using a standard ...
I have enlisted to JP Boodhoo's Nothin but .net class in Düsseldorf, Germany from September 22nd to the 26th. To quote JP: "This is a very intense week. Your mind will not have very much in the way of downtime. Days in past courses have gone anywhere from 10 – 20 hours in length!!" He prepared a download of several items to prepare for the course. There's a 30+ minute video where he explains step by step what you should prepare on your PC before starting the class. This includes where to download ...
As a followup to my previous entry on faster reflection with expression trees, I have released the source on code plex and that is where i will actively be distributing updates through. Some noteable changes are that now you retrieve an FastProperty instance through a factory method which will cache the property for subsequent reference. Also, I have merged everything into one class because I realized I was looking at what information I needed in the wrong places. Now you can just say FastProperty<object,obje... ...
In response to a comment on one of my previous posts (Safely Overriding Equals), I've decided to post some comments about Extension methods in general. A friend asked me what I gained out of extending string to convert to an enum. He asked, "is it just 'syntactic sugar'?" The simple answer is, "Yes." In fact, this is true of many extensions. Clearly, the major advantage of extensions is changing the syntax of how they are called. In fact, I have written a few extensions that support chaining and ...
It seems that enums might be the neglected step-child when it comes to Generics and Extensions. I've tried defining generics that are constrained to enums. No luck. I faced much frustration trying to get my generic methods to work. I finally came up with a method that meets my need. But, I had to add a little bit of run-time type checking. Instead of repeating Enum.Parse throughout my code, I wanted to create a simple generic extension method that would do it for me. I just discovered that my extension ...
So, I've settled on a pattern that I found somewhere on the web to safely override Equals. I don't remember where I found it, and there are certainly many other good implementations (probably better than mine). Regardless, I found that I do have a repeating pattern. I decided to set out to limit this duplication if I could. Here is what I came up with. 1: public static bool SafeEquals<T>( this T left, object right, Predicate<T> test ) 2: { 3: if( right != null && right.GetType().Equals( ...
The string.Join method can come in handy when you want a comma separated list of strings. However, there's a major limitation. To use it, you must provide a one-dimensional string array. What if you have a collection of objects and you want to "Join" a property on the objects (e.g., a comma separated list of IDs). Well, since I couldn't find anything within the framework that would do this for me, I wrote an extension method that meets my need. Updated from James Curran's suggestion in the comments. ...
To set a normal text box in the MVC framework, the most typical code would look like this: 1: <%=Html.TextBox("FirstNa... ViewData.Model.Contact.Firs... The key here is that you should set the name of the textbox to be the exact same name of the property name. If you do this, then it enables you to use extension methods such as the UpdateFrom() method to automatically populate your object from Request.Form parameters when you post to your controller action. This is all well and good but ...
UPDATE: This post is now out of date as of the CTP5 release of the MVC framework. For the lastest version, see this post here. One of the areas of MVC that is still an open area in development is how best to handle UI validations. There are numerous approaches currently being examined. MVCContrib Validator Toolkit for MVC The Enterprise Library's VAB is great because it allows you to specify all your validation logic in your business layer where it belongs rather than in your UI. Additionally, it ...
Imagine that every project in codeplex had to be decomposed into codeplex hosted unit tested functions which complied to some xunit standard - that would go along way towards code reuse, and move away from reinventing the wheel. worked on 2 Silverlight projects recently - see screenshots: and Last 3 months learned the following: NET Components revise – reread Yuval Loweys book – revised best mechanism for interface usage, delegates (circa .NET Framework 2.0), threading. The Interface stuff leads ...
Many thanks to Lorin Thwaits and the sponsors: Infusionsoft, Neudesic, and JumpBox, and all the volunteers and presenters at Desert Code Camp today in Phoenix. The turn-out seemed lighter to me than some of the ones in the past, but the sessions I attended were crowded with people sitting on the floor. I started the day off with Simon Allardice giving a great presentation on Silverlight Zero to Hero. High entertainment as usual, Simon... and great information and perspective! Next I was torn between ...
I get a bit sick of checking for null on my IEnumerable objects before doing a foreach over them. In my opinion I think the CLR should check if the list is null, and if it is just exit out of the foreach iteration as if there were no items in it. Well, I was goofing around with Extension Methods a bit and figured out how to get this kind of functionality (sort of). Now unfortunatly Extension Methods cant override an existing method on a type, so I cant just create a new GetEnumerator extension method ...
I cannot believe that I am the first person ever to encounter the following error: MSB3095: Invalid argument. Illegal characters in path. [Update] As Tom pointed out in the comments, this issue is directly related to the encoding of my *.refresh file. Thanks Tom. I searched Google and other search engines with no success. I found "MSB3095: Invalid Argument", and I found "Illegal characters in path.", but never in the same place. I did not actually resolve the issue; I was able to work around it. ...
Recently, after some analyzing some of the controllers I was building using ASP.NET MVC, I found that my controllers typically have the same pattern. They all have some dependencies injected into them through the constructor, each action calls a method on one of the dependencies (typically using the arguments of the and gets a result back), and depending on the result, an ActionResult is returned. Now, writing the tests wasn't tough. But, I dunno, I guess I'm REALLY lazy. So I started looking today ...
As I mentioned during my rant earlier this week, localization is fairly difficult with WPF. As it stands right now, the only real tool support Microsoft offers for localization is a tool called LocBaml.exe, which they clearly mark as "not production-ready." Samples available online describe how to utilize it, but there are significant drawbacks to its current implementation. First, since LocBaml generates CSV files, it is difficult or impossible to localize most anything other than simple strings; ...
As I've mentioned in recent posts such as here, here and here, I've been very interested in Domain Specific Languages (DSLs), especially with regards to F# and the DLR as well. I recently re-listened to Software Engineering Radio Episode 52 with Obie Fernandez discussing DSLs in Ruby. One of the things that attracted me to Ruby for this was the flexibility of the syntax for closures, mixins, etc. Anyhow, it's a good listen and if you're new to the subject, you should give it a go. Also, there is ...
C# 3.0 has certainly introduced some really cool features. I have used the Automatic Properties extensively as well as object and collection initializers. These are real time savers. However, the most exciting feature (IMHO) are Extension Methods. My last post shows one example of how powerful extension methods can be. Here is another example (inspired by Scott Gu). 1: public static class Extensions 2: { 3: /// 4: /// Do not use this extension for large sets because it iterates through 5: /// the ...
How many times have you written something like this? 1: public string MyStringProperty 2: { 3: get 4: { 5: object s = ViewState["MyStringProperty"]; 6: if( s == null ) 7: { 8: s = "MyDefaultValue"; 9: } 10: return (String)s; 11: } 12: set { ViewState["MyStringProperty"] = value; } 13: } 14: 15: public bool MyBooleanProperty 16: { 17: get 18: { 19: object b = ViewState["MyBooleanPropert... 20: if( b == null ) 21: { 22: b = true; 23: } 24: return (bool)b; 25: } 26: set { ViewState["MyBooleanProperty"] ...
I have been working on getting around the concurrency issues that LINQ has while working with disconnected DataContext's in an nTier environment. I currently have a Timestamp field in all of my tables to act as a row version number to help LINQ keep track of what is going on with my data. Up to this point I haven't had any issues as I have been working with objects that were either stored in session/cache as whole objects or I have been reconstituting the object from a new DataContext prior to updating ...
Next Tuesday, Feb. 12th at 5:30pm, I'm presenting at the Arizona .NET Users Group at the Microsoft campus in downtown Phoenix. The presentation is going to be a deep exploration of the new features of C# 3.0 - including LINQ, lambda expressions, extension methods, simple properties, partial methods, anonymous/implicit types, and object and collection initialzers. It will also cover some of the new .NET Framework 3.5 class libraries, but only insofar as they support the C# 3.0 language features (for ...
I know there are GetById, GetById<> methods in Document object. But, I often miss a method that I feel should be in Volta, which iterates through its child nodes and find an element for me. Let us say, there is a HTML like the following:<div id="divContainer"> <b>Some text</b> <div id="firstDiv"> <i>Some more text</i> </div> <div id="secondDiv"> Okay, I gotta go now </div> <div anyAttribute="anyValue"> Babye </div> </div>The ...
Download Solution - OfflineHtml.zip So, one of the cool controls available to us in WinForms is System.Windows.Forms.WebBro... The WebBrowser control is essentially a managed wrapper around some COM interfaces that bind to Internet Explorer and provides us with several interesting capabilities. First of all, one can use WebBrowser to easily display a web page in a WinForms application. All you have to do is set the WebBrowser.Url property and the control takes care of getting the assets from across ...
Here is simple LINQ example where I have used Extension methods "Where", to select the participants whose score is greater than 80. var participants = Competition.GetParticipants() .Where(participant=> participant.Score > 80) .OrderByDescending(participant => parricipant.Score) .Select(participant => new { participant.Id, Name=participant.Name }); Note: here we are sending a Lamda expression (participant=>participan... as parameter of the "Where" extension method. Ever wondered ...
The "C# 3.0 in a nutshell" book has some neat free extras that are worth mentioning for those who haven't already heard of (they have been released for long). Those are like must-have LINQ tools and helpers. The homepage of LINQKit (the major part of the extras I'm going to cover here) provides great information and short code samples about the components: LINQPad This is a snippet compiler (application to run/try small codes in separation than big VS projects, like this), that's customized for LINQ ...
Lately, I've been evaluation my use of extension methods. Extension methods have a good use, but that can quickly turn to overuse and confusion. The Evil When I start seeing these methods, I really start to wonder if it's really necessary. In fact, I run away screaming with my hands flailing above my head. internal static class ExtensionMethods { public string IsValidEmailAddress(this string email) { ... } public DateTime IsBefore(this DateTime date) { ... } } For readability sake, it's very tempting ...
The year has come and gone. We've just completed the celebration of Christmas in our new home with our new daughter -- she's almost one now! Work is still going well. I'm working on the replacement to VisiWatch again after a long departure to work on some internal workflow fixes and changes. I've also made some good headway into eliminating some of the legacy Access databases and I've set SQL Reporting Services although right now it's not doing anything in production mode. We've upgraded some things ...
I was working on a series of dialogs that required validation, and since there's a funky validation setup in place, I thought I might build up a nice extension library. Noting that ASP.NET validation is far beyond Windows Forms, I thought it might also be a good opportunity to use extension methods. Sadly, extension methods aren't supported by the C# 2.0 compiler (which I was using, part of Visual Studio 2005), nor are they supported by the .NET Framework 2.0. So, I wouldn't get IntelliSense support, ...
Few days back ASP.NET MVC Framework was released. Since, the framework is new there are not many UI controls available yet! But off course this is all going to change. Actually this has already started to change since Rob Conery created the MVC UI Helper Controls. Scott Hanselman used some of Rob's cool controls in his demo. The purpose of the UI helper controls is to help the developer to quickly create UI controls. So, instead of using the foreach loop to populate a DropDownList you can use the ...
ScottGu and Brad Abrams have announced the release of the first preview of the ASP.NET 3.5 Extensions. The release includes great new features like: MVC Framework ASP.NET Silverlight controls AJAX Enhancements like History support Dynamic Data Controls Entity Framework ADO.NET Data Services Grab it from here: ASP.NET 3.5 Extensions Also available is the MVCToolkit (courtesy of Rob Conery) which contains a bunch of helper extension methods you can use in your Views. You can get it here: MVC Toolkit ...
Extension Methods is a new feature of the C# language (I think it is called C# 3.0). Extension methods allows you to extend the CLR types. This includes all the types which inherit from the System.Object class. Let's see a small example where I have extended a String to add a new "Reverse" method which gives me the string in reverse. public static string Reverse(this string s) { string r = String.Empty; for (int i = s.Length -1; i >= 0; i--) { r += s[i].ToString(); } return r; } I am using the ...
Date: Monday November 19th, 2007 Event Description: Conversation about the new language features in .NET 3.5 have been dominated by the inclusion of Linq. In this session we will look at some of the features that have been lost in the shuffle. We will deep dive into anonymous constructors, simple properties, anonymous types, the ‘var’ keyword, lambda expressions, extension methods and more. Speaker Biography Donald Belcham, C# MVP Donald Belcham is an independent contractor in Edmonton. He has worked ...
Back Links LINQ Overview, part zero Forward Links LINQ Overview, part two (Lambda Expressions) In part zero I stated my intentions, now it is time to act. If you've ever programmed in C (no, I didn't forget the #) you may have had a function prototype laying around similar to: int Deposit(struct account *acct, double amnt); If one were to rewrite this today in C# you'd probably have a class to represent accounts and your method definition would just be: public void Deposit(double amount) You would ...
Ever since attending the C# 3.0: Beyond LINQ presentation at Desert Code Camp (excellent presentation Donald), I've been a little more wary of a couple of the new features introduced by C# 3.0. I wanted to go over them and point out some of the pitfalls that they can lead to. Note that I'm not trying to discourage its use - BUT - if you know how something works in the underlying technology, you're more likely to choose the correct techniques for a given situation. All static code analysis and time ...
I have started looking at improvements to the NMock2 code with respect to writing a branch of the code in .NET 3.5. The availability of extension methods in C# 3.0 have solved a common code issue of mine where I want to use Dictionary.TryGetValue to see if there is a value in a dictionary for a given key and create a default if not. Which leads to the following code. public static class ExtensionMethods { public static U SafeGetValue<T,U>(this Dictionary<T,U> dictionary, T key) where ...
One of the things in VS 2008 that has intrigued me has been Extension Methods. I've been trying to think of ways to use these in my applications and coming up with ways to move functions associated with various processes to Extensions in our own APIs. ScottGu recently posted an interesting article on his weblog about writing an Extension for creating JSON. One thing I dislike doing and have to do fairly often is cast Object sender to various things to pull information out of it. The most common reason ...
Not too long ago, I talked about Extension Methods in .NET 3.5 and also about a way to provide data binding an enum type with descriptions. Today, Simo talked about how often he forgets the syntax of parsing a string value to it's Enum value. In his post, he refers to a generic Enum parse method that Scott Watermasysk created just over a year ago (in 2006). In Scott's post, Kenny Kerr points back to his article (from 2005) about how to create a generic parse method in C++/CLI. Reading through all ...
C# 3.0 Lambda Expressions play an integral part of making the LINQ framework work. Outside of LINQ it is recommended that they be used sparingly because they are less "discoverable." However, there are a couple of nice scenarios where extension methods have good potential to make your code more elegant as a stand-alone language enhancement. Take an example where you have a nullable value in the database and you represent this as a Nullable<DateTime> on your C# object (e.g., EmploymentEndDate). ...
As I mentioned in my previous post, if you create an extension method with the exact same signature as an existing method your extension will be ignored. However, one thing that I didn't mention is that if the extension method has a different signature, it will show up in that methods overload list. To make this a little bit clearer, if you create the following extension method 1: namespace DataValidationHelpers 2: { 3: public static class DataValidation 4: { 5: public static string ToString(this ...
At one time or another most of us have wished we could add functions to one of the intrinsic .NET classes. The solution has always been to either create a static (or sealed) class that contains these "helper" functions or derive a new class that adds the desired functionality. A good example of this is testing a string to see if it contains only alphanumeric characters. In order to do this, we need to define a helper class: 1: namespace DataValidationHelpers 2: { 3: public static class DataValidation ...
I've been reading about the new extension methods in VB 9.0. They look to be extremly useful for placing custom functionality on other peoples classes, even sealed classes. Read more about them here: http://blogs.msdn.com/vbtea... Scott Ann Arbor .Net Developers Member ...