Tag | Extension Methods Posts

But first, a brief introduction as to what prompted this line of posting. At PDC ‘09 I had the pleasure of making acquaintances with Jon Galloway and Steve Andrews who challenged me to do more than practice & talk with co-workers and put together a talk and the suggested topic for said talk was – functional programming. Well, I’m not quite at the talk stage yet, but figured that the blog format worked as a good starting point. So, what is functional programming? Wikipedia offers the following ...
I wrote these utility extension methods to get the previous quarter end/month end and next quarter end/month end values for Financial calculations. Next Quarter End: 1: public static DateTime NextQuarterEnd(this DateTime date) 2: { 3: IEnumerable<DateTime> candidates = 4: QuartersInYear(date.Year).U... + 1)); 5: return candidates.Where(d => d.Subtract(date).Days > 0).First(); 6: } 7: 8: public static IEnumerable<DateTime> QuartersInYear(int year) 9: { 10: ...
Suppose you have to write a test to verify that an edit form will throw a certain exception under certain conditions. If you don't use VB 9 features, you might end up with this effusion of verbosity: Try editForm.Save(MyDataContext) Throw New AssertFailedException("Save should have thrown an exception") Catch ex As Exception If Not (ex.GetType().Equals(GetTyp... Then Dim errorMessage = String.Format("Save should should have thrown BusinessOperationException; threw {0} ...
Recently I had an interesting task to consume a particular XML document and populate a C# object from it. The structure of the XML document looked roughly like this: 1: <root xmlns="http://www.w3.org/20... 2: <entry> 3: <id>1</id> 4: <title>abc</title> 5: <content> 6: <div xmlns="http://www.w3.org/19... 7: <table> 8: <tr> 9: <td>Item1</td> 10: <td>111</td> 11: </tr> 12: <tr> 13: <td>Item2</td> ...
I just love Linq in SharePoint. I think it is just an awesome way to write quick queries and get at data quite quickly. I've been working with it for a while on several projects and have been seeing some quirky things with it. First, the one problem that has been blogged about the most is that linq does with SPSite and SPWeb objects do not get properly disposed after they are used. You can google around for these issues and fixes. I implemented extension methods that properly disposed of the SPSite ...
Lately I’ve been working with EF 4.0 and finding that many of the new features are catching up with the features previously available in other framework like LINQ to SQL. One example of this is the ability to easily attach objects (for example, disconnected objects that come in from another tier). For example, imagine you had a web service where a consumer submitted an object to get saved – you’d want to instantiate a new context, attach the incoming entity, and save the object. In previous versions ...
Maybe I am just crazy, but it seems like removing or deleting items from a collection is always an after thought. Take IList for example, a list of items, with the ability to add and remove from it. We have a flurry of extension methods that are inherited from IEnumerable to add items but it seems like no one thought maybe it would be nice to beef up the remove method with some extension methods. Maybe I missed an extension namespace, maybe I am just crazy. How many times do we have to write the ...
I have written far too many null checks in my life. Why do we have even null values? They only seem to provoke a NullReferenceException in our code after all. F# for example has the option type with the value None which is semantically the same as null without being null which makes it impossible to access invalid values by accident. It is of course possible to create null values in F# but it is not the most natural thing in a functional programming language. How can we make C# safer without writing ...
My thoughts and observations of this year’s Microsoft PDC conference in LA. Day 1: Just registered for the conference. They had many reps available to move attendees through the registration process. We arrived early, and had to stand in line for 15 minutes, while all the reps stared blankly back at us; “We don’t open until 7.” Wow.. Great Customer Service. Let me take this moment to comment on the Conference bag this year. ITS A CHEAP PIECE OF CRAP. Literally, it looks like a “reusable” grocery ...
While I was planning to write about the same topic and have the draft ready in my Windows Live Writer waiting to complete, I found an interesting question in StackOVerflow and couldn’t just resist to answer: ORM/Persistence layer Advice The question starts with: I'm starting a new project and I'm looking around for either a very good ORM or for a non-SQL-based persistence layer. Then follows up with a REALLY GOOD summary of what he believes about each known ORM he knew out of his own findings and ...
Who here uses IDictionary classes in their projects? Raise your hand. Keep your hand up if you cannot bear the sight of having to call another ContainsKey method. Keep it up if you cry at the idea of having to use the “out” keyword in conjunction with the TryGetValue method... Keep the hand up if you consider that removing items should be allowed from inside a foreach loop. Is your hand still up? Yeah, mine too . Alright let’s all take a break. This is just one of the numerous annoying little things ...
So the other day at work we were doing an architecture/design review on a project to share knowledge gained with other project teams. After making the code available one of the other architects came to me with a specific piece of the code in hand asking us to justify why it seemed so complex (in this case the comment was mainly because the code used lambda's generously and he had limited exposure to them previously). Here is the code in question: Original Approach public void Save(IJob job) { this.AutoCommit(s ...
In this Issue: Colin Eberhardt, Boyan Mihaylov, Silverlight SDK, Christopher Bennage, Stephen Forte, Jacek Ciereszko, Jesse Liberty, and Mark Tucker. I'm still at least 2 days behind, but the crunch is over, so now I can maybe catch up. From SilverlightCream.com: Helpful extension methods for Show / Hide animations in Silverlight Colin Eberhardt is sharing some of the code he uses regularly by way of Extension Methods to Show/Hide animations, and boy that demo works great... thanks Colin!Creating ...
Maybe it is just me, but I’m not a big fan of huge amounts of XML configuration. I can get by with a few name-value pairs in an app.config or a web.config but much more makes me nervous that I’m going to mistype something and not know about it until run time. I’ve been using Unity and it has the ability to load up its configuration from the app.config or web.config. Here’s a sample: Yeah…..what else ya got? It offers a “fluent” API for programmatic registration. Sweet! Now I just have to convert ...
[Source: http://geekswithblogs.net/E... If you make heavy use of lazy-loaded properties, the repetitive if-backing-field-null-then-... code can be centralized in an extension method on the object class: /// <summary> /// Extension methods for <see cref="Object"/> /// </summary> public static class ObjectExtensions { /// <summary> /// Lazy-loads a property /// </summary> /// <typeparam name="T">Type of property</typeparam> /// <param name="obj">Extended ...
Really no magic here and just a simple add on to my previous post just in case you need something that can easily copy the contents of a given directory to another location. public static void CopyContentsTo(this DirectoryInfo source, string desinationDirectory) { if (string.IsNullOrEmpty(desin... { throw new ArgumentNullException("root... } if (!Directory.Exists(desinati... { Directory.CreateDirectory(d... } foreach (string file in Directory.GetFiles(source.F... ...
The .NET Framework does not offer support for a directory copy method OOB. Fortunately in .NET 3.5 we can decorate the DirectoryInfo method with our own CopyTo method using an extension method. See the below example… public static class DirectoryInfoExtensions { public static void CopyTo(this DirectoryInfo source, string rootDestinationDirectory, bool recursive) { if (string.IsNullOrEmpty(rootD... { throw new ArgumentNullException("dest... } if (!Directory.Exists(rootDest... ...
[Source: http://geekswithblogs.net/E... Keeping up the fluent work, I've put together a fluent interface which wraps the framework HtmlTextWriter. For ASP.NET MVC, this makes generating HTML in extension methods to HtmlHelper safer than string.Format() and more readable than HtmlTextWriter: public static string Image(this HtmlHelper helper, string imageRelativeUrl, string altText) { return FluentHtmlTextWriter.Begin() .WriteTag(HtmlTextWriterTag... .WithAttribute(HtmlTextWrit... ...
Since the beginning of July, I've been working on a java project. The language is very close to C#, although it has some minor irritating differences, like the lack good generic support, extension methods and closures. The big difference however is not in the language, the tools, the libraries or the utilities. One of the big differences I've seen is the community. I've been on many projects that have worked exclusively with Microsoft tools, libraries and (god forbid) examples. When the subject is ...
The MVC framework does not come with a built-in RadioButtonList comes standard in ASP.NET web forms. The MVC Futures assembly (which can be downloaded here) does come with this HtmlHelper but there are some issues with it including the ones described here by Elijah Manor. He concludes that the method in the futures assembly isn’t very useful and states, “To get around this I ended up writing a foreach creating individual Html.RadioButton and labels.” However, he did not show the code he wrote to ...
Recently we have to create methods that will manually compare 2 objects and see if they are equal – essentially check if all their properties / fields are equal. Some of the fields are Nullable Types, which have been available since .NET 2.0 (VS2005). It is a nice construct to have, especially to represent database fields that can also be null – this makes coding simpler because a nullable type can also contain null as a valid value. Interestingly, talking some some people that have done .NET for ...
I was spending some time discovering design patterns. When searching for the decorator pattern, I also aimed to retrieved results for SharePoint. This way I found a nice site about a datalayer for SharePoint. It's based on extension methods and generics. It wraps the SPListItem class, and adds some new "custom" functionality. That way, by using the wrapper, you can access your SPListItem objects more strongly typed ...
Technorati Tags: MVC,ASP.NET,Extension Methods,Html Helper A lot of hype around MVC these days. So, of course, yours truly is working on some project utilizing MVC. While brushing the dust off my raw HTML tag memory and designing the obvious: lists, grids, repeated item displays and the such, I thought "why not use the asp.net controls instead?" For one, most of the ASP.NET data bound controls have a rich site of event post backs to hook up. MVC says: no dice! You can't rely on the event dispatch ...
Recently I have published a series of articles that has been devoted to possibilities of Windows 7 for developers to work with the task panel. I have received a large quantity of responses for this time. Thanks you very much for it. That is interesting, questions were absolutely various subjects. However, the most part of questions was on a theme of use of similar functionality in WPF applications. Really, in the majority of examples I have lost sight WPF applications. I will try to compensate this ...
Normal 0 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.000... mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} If you are planning to choose ...
Here's a really short and simple bit of code that has the potential to be a bit of a time-saver. The FindControl method of the Control class is used to find a specific child control of a given parent, searching by ID. This method, however, doesn't search the control hierarchy recursively: it searches the direct children of the specified parent control only. While writing a recursive version of this method is trivial, a rather nice way to make the method reusable is to implement it as an extension ...
Trying to make some use out of the extra time I have being unemployed I started playing with creating Extension methods which became available with .NET 3.0. Cool functionality when you want to add functionality without altering the original code. I posted an article out on Code Project (http://www.codeproject.com... that shows how to create an extension for System.String and allows the user to encrypt/decrypt any string object without knowing anything about using ...
New OS Windows 7 contains a considerable quantity of innovations and improvements. These improvements concern safety, productivity, reliability etc. Also, the big attention is given to the user interface. In several posts we will talk about the innovations and program model. The first that is appreciable in Windows 7 is, of course, updated task bar. In new taskbar many conceptual changes. One of such changes - possibility of display of progress of performance of a task (progress bar). In this picture ...
(This posting is a continuation of this blog posting.) If you want to implement this the OOP way, here you have the subclass code (which I'll use myself). using System.Collections.Generic; // Remember to set this to your proper namespace (or use a using statement in // the class with the LINQ projection) namespace MyNamespace { /// <summary> /// Extension methods for the Dictionary generic class. /// </summary> public class ImprovedDictionary<T1,T2... Dictionary<T1,T2> { /// ...
Ever needed to instantiate a Dictionary from a LINQ projection? It is certainly doable, although not extremely straightforward. My first thought was to try and do this: var result = from o in ctx.Orders where o.ID = OrderID select new MyOrderClass { ID = o.ID, Created = o.Created, ExtraData = new Dictionary<string,string... Add("key1", o.Value1). Add("key2", o.Value2") }; If this would work, it would probably be the most clean-looking solution. The only problem with this though is that the ...
In this Issue: Ashish Shetty, Nikhil Kothari, Chris Cavanagh, Rishi, Nigel Sampson, Tim Heuer, Ruurd Boeke, Alex Golesh, Lee, and Pete Blois. Shoutouts: Pete Brown is asking for input for the book he's gearing up for: Silverlight 3 Book – Tell me what you want ... good luck with that Pete! Koen Zwikstra has an evaluation of his Document Toolkit available: Document Toolkit Evaluation... very cool, Koen! From SilverlightCream.com: Silverlight out-of-browser apps: The Install Ashish Shetty has the first ...
At MIX 2009, the Expression Blend team cam up with a new concept called Behaviors. In fact, the only thing new is the way that the Behaviors are packed. WPF developers have been doing what we called "Attached Behaviors" for quite some time already: see this thread (dated July 2008) to read a discussion around this topic at the WPF Disciples group. Read the rest of this entry » ...
The VISUG (the main .NET Usergroup in Belgium) and Microsoft Belgium are organizing 3 events for .NET developers. These events will cover existing technologies and are free to attend. I’m presenting the sessions on LINQ and data access in .NET 3.5 on April 15 from 02:00 PM till 04:00 PM. This presentation takes place at the Microsoft Offices in Zaventem. A language focused overview of the foundations of LINQ in C#3.0 (50 minutes) In this session the language enhancements in C#3.0 on which LINQ is ...
A while back, I blogged about using the Enterprise Library Validation Application Block (VAB) with ASP.NET MVC. As MVC has matured as a framework, this scenario has becoming simpler. In early releases of MVC, I implemented the execution of the VAB validation in the controller methods. However, I now prefer to put that logic in the binders themselves. In earlier versions of the framework, the model binders that came out of the box dealt well with simple objects but if you had more complex View Models ...
People seem to be genuinely confused about how extension methods work. I've had this conversation a number of times at work, most recently just yesterday. People keep trying to make them act like instance methods, but the fact is, they're just static methods. When you call an extension method, you're calling a static method. Period. There's no difference in the generated IL between a static method and an extension method. None. So, if you're wondering how an extension method works, the answer is ...
In this issue: Jobi Joy, Andy Beaulieu, Rishi, Nikhil Kothari, Pete Brown, Fredrik Normén, Tim Heuer, Kirupa Chinnathambi, Cameron Albert, Shawn Wildermuth, Jeff Wilcox, Terence Tsang, Andrej Tozon, and Somasegar. Shoutouts: First a big congratulations to Bill Reiss for becoming the very first official Silverlight MVP: I'm just speechless… What an honor to be the first Silverlight MVP Want a sneak peek into LOB apps by the guys on the product team? Tim Heuer gave this link: Silverlight Sneak Peek: ...
Recently I've started working more and more with the ADO.NET Entity framework and I must say that I like it a lot. There are folks who absolutely love EDM and folks that think its really evil. It's still a v1.0 product and I treat it as such. The designer does leave a lot to be desired.A lot of bells and whistles will be added to the VS 2010 release to address a lot of the designer "desirables". It's not been an easy buy in at work for adopting EDM, but my team has been among the first to have adopted ...
This is part 2 of a two posts series about the property IsSynchronizedWithCurrentItem. In the previous post, we saw what it does in Windows Presentation Foundation. In this post, we will see that this property is missing in Silverlight, and propose a way to simulate it. Read the rest of this entry » ...
Routing Library resides in the System.Web.Routing Namespace of the .NET Framework 3.5, which provides us the flexibility to use URLs that has no mapping to a physical file. This means ASP.NET MVC framework provides flexible URL mapping engine and enables us to write SEO (Search Engine Optimization) friendly URLs with very little effort. No one can deny the importance of SEO, to be successful in search based marketing. What better way to analyze a business than from what customers are looking for ...
In this issue: Maurice de Beijer, Jesse Liberty(2), Corey Schuman, Mike Snow, Tim Heuer, and Radenko Zec. Shoutouts: Andras Velvart sent me a link to a stunning commercial application using Silverlight and DeepZoom... don't take my word for it, try it out: Zoomery. If you're interested in 3D in Silverlight, check out what Telerik has going on: 3D in Silverlight from Telerik Dan Wahlin has his My Latest Silverlight Articles post up. From SilverlightCream.com: Using Ninject with Silverlight to make ...
The Problem I have been developing with Silverlight for a few months now, and I have really been enjoying myself. It has been the enabling technology my project and we have been extremely productive in the environment. Unfortunately, Silverlight is still in version 2.0 and there are some missing capabilities. One such hole in the framework is "Drag and Drop". There is no support for it directly. There are several blog examples on the web, but I have yet to find a fully encapsulated, generic solution ...
The System.Core assembly in .NET 3.5 contains the main LINQ methods for dealing with objects such as the Max() extension method. Like many of the LINQ extension methods, the Max() method has many overloads that allow you to do things like this: 1: List<int> list = new List<int> { 1, 2, 17, 14, 21, 4 }; 2: Console.WriteLine("Max: " + list.Max()); //<- "Max: 21" This is all well and good but what if you need to do something a little more interesting? There are endless examples to think ...
I have been writing a lot of unit tests lately using Microsoft Test. This included converting a bunch of old NUnit tests to the MS Test format, which was relatively painless. While examining the code coverage results (after all, what good are unit tests if you don’t know what portions of the code are being tested and not tested), I have noticed that the results sometimes lie. For example, I have a class that contains some extension methods for manipulating enums. One of those methods takes an enum ...
ORM made easy with Linq to SQL and Extension Methods Download Sample Code Few things get developers as passionate, angry, or roused as ORM (Object Relational Mapping) strategies, short of dissing Mountain Dew. This is probably because there are so many ways to do it and doing it wrong can result in big, big headaches. Nevertheless, this is an area that is really pretty straight forward. I’ve got some stuff over here that is shaped one way and some stuff over there that looks (maybe very) different, ...
In the latest edition of the Silverlight toolkit (December 2008), there is a bug with the ViewBox control. First a reminder: A ViewBox is an element used to zoom a scene. For example, if the ViewBox' content has a dimension of 800x600, and the ViewBox itself has a dimension of 400x300, the content will be automatically zoomed. For example: Read the rest of this entry » ...
I do performance measurements quite regularly which involves to call a piece of code several times to measure how long it did take. I am sure nearly everybody has done this already. But as a physicist I know that (nearly) every measurement has fundamental problems which never go away. Key to a successful measurement is that you exactly know what you are measuring and not what you think you measure. The easiest way to get out of this dilemma without too much knowledge is to simply ignore the fact ...
Today I learned I have a lot to learn! Patterns, Delegates, Lambdas, PSake, Extension Methods, etc, etc, etc. Photo credit to Hikako. So far we have went through patterns and principles. Ones that come to mind are the Strategy Pattern, Static Gateway Pattern, Decorators, and Specification Pattern. We also got into SRP (single responsibility principle), OCP (open closed principle), Composition over Inheritance, BDD (behavior driven design), DDD (domain driven design), and then we talked a little about ...
Those of you who know me know that I am a big proponent of code style and standards. One of the best resources I have found for documenting a clear and thorough set of code standards is the Framework Design Guidelines book by Brad and Krzysztof. The book was recently updated for the new language features in the .NET Framework 3.0 and 3.5 releases. Some of the existing guidelines have been expanded with new annotations and more detail, and new guidance covering such features as extension methods and ...
Howdy, hello, and welcome to my new technical blog. The purpose of my blog is to look at features and tricks that exist in current and slightly less-than-current versions of .NET that, for one reason or another, I never bothered to learn. Don't get me wrong, I love the latest, greatest, on-the-far-horizon stuff as much as anyone, but the reality is for those of us building Line-of-Business apps, we are frequently limited in choice of which .NET framework we can target, and as such have to make optimal ...
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 ...