Tag | Extension Methods Posts

When you’re working with WIF and WSTrustChannelFactory when you call the Issue operation, you can also request that a RequestSecurityTokenResponse as an out parameter. However, what can you do with that object? Well, you could keep it around and use it for subsequent calls with the extension method CreateChannelWithIssuedToken – or can you? public static T CreateChannelWithIssuedToke... ChannelFactory<T> factory, SecurityToken issuedToken); As you can see from the method signature ...
This blog entry is intended to provide a narrow and brief look into a way to use the Select extension method that I had until recently overlooked. Every developer who is using IEnumerable extension methods to work with data has been exposed to the Select extension method, because it is a pretty critical piece of almost every query over a collection of objects. The method is defined on type IEnumerable and takes as its argument a function that accepts an item from the collection and returns an object ...
Edit: I've now written an improved version of this set of extension methods, which can be found here. Consider these deprecated!I recently wrote a Type.GetInstance() extension method, and used the opportunity to play around with Expression Trees, which I'd recently read up on in C# in Depth. Here's the set of extension methods I came up with, which allow you to quickly create an instance of a Type from the Type itself; like this:// No constructor arguments:MyClass myClassInstance = (MyClass)typeof(MyClass).Ge... ...
On November 12th 2011, I gave a presentation at Chippewa Valley Code Camp titled, “Kinecting the Dots with the Kinect SDK”. As promised, here is the Slides / Code / Resources to my talk. (click image to download slides) The Kinect for Windows SDK beta is a starter kit for applications developers that includes APIs, sample code, and drivers. This SDK enables the academic research and enthusiast communities to create rich experiences by using Microsoft Xbox 360 Kinect sensor technology on computers ...
Normal 0 false false false EN-US X-NONE X-NONE /* 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-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans... mso-ascii-font-family:Calibri; ...
So I am new to TDD and have been enjoying the ride of learning a new approach – today I came across an interesting situation that I thought I would blog about. I was writing a class that had all sorts of string manipulation in it. I needed some helper methods that would extend my string manipulation abilities. I had read somewhere that I should avoid static methods when doing TDD so I wrote the initial helper class to look something like this… public class StringHelper { public string ReverseStringEx1(string ...
I've never liked having to pass a string to Type.GetInterface() to check if a type implements an interface. This extension method to the Type class lets you check more neatly with a generic: ///<summary> /// Extension methods for the <see cref="Type"/> class. ///</summary> public static class TypeExtensions { ///<summary> /// Returns whether the type implements the given interface ///</summary> ///<param name="value"></param> ///<returns></retu... ...
The ViewModels in my current project had got quite complex; as well as properties copied from model objects, they increasingly had flags used by Views to know whether to render links or sub-sections. The logic which set these properties was bloating Controllers, so I factored it out into objects which populate all non-editable properties of a ViewModel; ViewModelBuilders. The system has the following components: ViewModels - objects which provide a View with the information it needs to be rendered. ...
Download Source Code Challenge Just had the first chance to apply PLINQ (Parallel LINQ) to the real task. When I am playing around with some new technology everything works fine, the real understanding comes along with challenges in a real use case. Currently I am working on application which processes large amount of text data gathering statistics on word occurrences (see: Source Code Word Cloud). Here what the simplified core of my code is doing. Enumerate through all files with *.txt extension. ...
In this Issue: Mike Talbot, Michael Crump, Kunal Chowdhury, Cheryl Simmons, Joost van Schaik(-2-), Shantimohan Elchuri, Jesse Liberty(-2-), Peter Torr, Pete Vickers, Derik Whittaker, and Den Delimarsky. Above the Fold: Silverlight: "Wordle Like Tag Cloud for Silverlight" Mike Talbot WP7: "Speed and distance calculation extension methods for Windows Phone 7" Joost van Schaik Shoutouts: Check out Pete Brown's interview on .NET Rocks: My .NET Rocks Interview Koen Zwikstra announced a July update: Silverlight ...
Introduction The official Kinect SDK has been out for a while now and I haven’t seen many people actually doing “how-to” post to get others started developing for it. I decided that I would help kick-start the movement by creating a series called, “Kinecting the Dots”. This is going to be a series of blog posts covering questions or concerns that I’ve seen in the community. I am planning on answering questions so if you have one that you want answered then please contact me by using the form above. ...
I’ve been playing with the Kinect SDK Beta for the past few days and have noticed a few projects on CodePlex worth checking out. I decided to blog about them to help spread awareness. If you want to learn more about Kinect SDK then you check out my”Busy Developer’s Guide to the Kinect SDK Beta”. Let’s get started: KinectContrib is a set of VS2010 Templates that will help you get started building a Kinect project very quickly. Once you have it installed you will have the option to select the following ...
The Kinect is awesome. From day one, I’ve said this thing has got potential. After playing with several open-source Kinect projects, I am please to announce that Microsoft has released the official SDK beta on 6/16/2011. I’ve created this quick start guide to get you up to speed in no time flat. Let’s begin: What is it? The Kinect for Windows SDK beta is a starter kit for applications developers that includes APIs, sample code, and drivers. This SDK enables the academic research and enthusiast communities ...
This blog is the first one of a series of blogs addressing programming practices and lessons learned related to cloud computing. While most developers will be familiar at least conceptually with the techniques exposed, I will provide background information and code samples in an attempt to explain why they are so critical in cloud software development. While most of the information provided will be using Windows Azure and/or SQL Azure, these concepts apply to cloud computing in general. Exponential ...
“Design Patterns 100? is a prerequisite for .NET Developers. (Part 4 – Excerpts from July 2010 – PhillyNJ.NET Presentation) Continuing our discussion from Part-3 we ask. What are the “Gang of Four” (GoF) Structural Patterns and where can we find them in the .NET Framework? Let’s look at a list of the Strutural Patterns as defined by the GoF. Adapter Pattern – is used to match interfaces of different classes Bridge Pattern – is used to separate an object’s interface from its implementation Composite ...
The list provided below is my “Best-Of” FREE Frameworks, Tools and Controls for Windows Phone 7. I have used everything listed below in an my WP7 applications. Most of them are in the marketplace at this point and some are still in development. Let’s get started. If you are developing WP7 Applications, this is one that you have probably heard of already. It is Microsoft’s official set of controls that comes complete with full source code of course. Project Description: Welcome to the Silverlight ...
In this Issue: Michael Crump, Jeremy Likness, Matthew Delisle, Xianzhong Zhu, Nigel Sampson, Jeff Prosise(-2-), Andrea Boschin, Mike Ormond, Jeff Wilcox, and Bil Simser. Above the Fold: Silverlight: "Silverlight Scaling and Anti-Aliasing Issues" Jeremy Likness WP7: "AgFx Windows Phone App and Data Caching Framework" Jeff Wilcox Shoutouts: The tool Mike Ormond discussed in a post listed below is WP7 Screenshot Tool by Cory Smith DiscountASP.NET has a post up about the latest SQL Injection attack going ...
I have written about adding support for specifications to NHibernate’s ISession type. Shortly afterwards Paul Stovell moaned on twitter that no one had demonstrated how to mock ISession. Since my implementation relied upon an extension method (QueryBySpecification) I googled how to mock extension methods – and discovered that you can’t. What I did find was Daniel Cazzulino’s post about converting extension methods to methods that return a Func that exposes your extension method. That way you can ...
You cant pass MultiD arrays accross the wire using WCF - you need to pass jagged arrays. heres 2 extension methods that will allow you to convert prior to serialzation and convert back after deserialization: public static T[,] ToMultiD<T>(this T[][] jArray) { int i = jArray.Count(); int j = jArray.Select(x => x.Count()).Aggregate(0, (current, c) => (current > c) ? current : c); var mArray = new T[i, j]; for (int ii = 0; ii < i; ii++) { for (int jj = 0; jj < j; jj++) { mArray[ii, ...
Applications get data from lots of different sources. The most common is to get data from a database or a web service. Typically, we encapsulate calls to a database in a Repository object and we create some sort of IRepository interface as an abstraction to decouple between layers and enable easier unit testing by leveraging faking and mocking. This works great for database interaction. However, when consuming a RESTful web service, this is is not always the best approach. The WCF Web APIs that are ...
In this Issue: András Velvárt, Tony Champion, Joost van Schaik, Jesse Liberty, Shawn Wildermuth, John Papa, Michael Crump, Sacha Barber, Alex Knight, Peter Kuhn, Senthil Kumar, Mike Hole, and WindowsPhoneGeek. Above the Fold: Silverlight: "Create Custom Speech Bubbles in Silverlight." Michael Crump WP7: "Architecting WP7 - Part 9 of 10: Threading" Shawn Wildermuth Expression Blend: "PathListBox: Text on the path" Alex Knight From SilverlightCream.com: Behaviors for accessing the Windows Phone 7 MarketPlace ...
I feel compelled to post this blog because I find I’m repeatedly posting this same code in silverlight and windows-phone-7 answers in Stackoverflow. One common task that we feel we need to do is burrow into the visual tree in a Silverlight or Windows Phone 7 application (actually more recently I found myself doing this in WPF as well). This allows access to details that aren’t exposed directly by some controls. A good example of this sort of requirement is found in the “Restoring exact scroll position ...
I have been using Rx for over a month now and can’t even begin at telling how beautiful it really is and how much it has simplified my life especially working with UI declaratively and without having to worry about Dispatchers, threading etc., and I ended up rewriting most of the custom controls I have build over time to support Rx. And have been a big fan of Observable pattern and WeakEventListeners again had their own limitation which I always found a bit intimidating and for me Reactive Extensions ...
This evening I thought I would look into something that I have been meaning to look into for a while, but just haven’t given the time of day. Initially I wanted to brush up on some LINQ, but after going over the definition of LINQ, I stumbled across extension methods… I have heard of them quite a bit – but never really bothered to see what they are… So the official MSDN explanation says the following… “Extension methods enable you to "add" methods to existing types without creating a new derived ...
I received (by chance, mostly) a Netduino last tuesday. Netduino is an open-source hardware project based on Arduino and the .Net Micro Framework. And it’s extremely cool. I’m a C# developer and I was always interested in electronics. This is an excellent tool to start to understand that incredible world. I was about to buy an Arduino when the Netduino fell on my lap, so I was really happy about it. Netduino has various disadvantages over Arduino (for starters, it’s more expensive, not all the shields ...
Extension methods were introduced with the .NET 3.5 framework as a mechanism to add methods to extend existing types without modifying the original assembly. This is how the Linq methods were implemented to enable some very powerfull predicate function based operations to be performed over all existing collection types. Searching for web controls on a page is one of those tasks that seems to come up for all kinds of reason while programming using web forms. I was reminded of this problem recently: ...
Its all about creating a dynamic menu control in WPF. The source for this menu control is xml file. This sample is also an good example of adding controls dynamically and assigning animations to them dynamically. sample xml file is given below. <MenuList> <Menu id="2" image="images/Firefox-48x48... name="browser"> <SubMenu image="images/Firefox-48x48... file="firefox.exe">Firef... <SubMenu image="images/Internet-Expl... file="IExplore.exe">IE&l... ...
In this Issue: Michael Washington, Richard Waddell, Jeff Blankenburg(-2-, -3-), Dejan Jakovic, Peter Kuhn, Domagoj Pavlešic, Thomas Martinsen, Jesse Liberty, and Joost van Schaik(-2-). Above the Fold: Silverlight: "Silverlight Unsaved Data Detection " Michael Washington WP7: "Extension methods for tomb stoning the Windows Phone 7 model" Joost van Schaik Expression Blend: "Simple Layout Techniques In Blend " Richard Waddell Shoutouts: Mark your calendars, because Beth Massi announced MSDN Radio on ...
Well, it's been a long time since my last post and unfortunately it's another simple thread to share my material but I'll resume posting here and there in the next couple weeks... Here's the link to my presentation and supporting material which was about Lambdas and Extension Methods using Visual Studio 2010... The powerpoint is there and so is the small project I used to demo my subjects... There's also the source code for the Umbrella project... Cheers ...
In this Issue: Sergey Barskiy, Tim Heuer, Shawn Wildermuth, Patrick Cauldwell, David Anson, Michael Sync, Jeremy Likness, Victor Gaudioso, René Schulte, John Papa, and Todd Knudsen. Shoutouts: Telerik's Premium Collection for .NET wins Jolt Product Excellence Awards: App Libraries and Frameworks SilverlightShow announced a Free SilverlightShow Webinar: Running Silverlight Outside the Browser and with Elevated Trust... see you there... I'll be the one in shorts with no shoes :) John Papa has a two-part ...
One of the new features of XNA 4.0 is the Content Project. Those of us who’ve worked in XNA 3.1 and earlier are familiar with the old Content folder, which was simply a folder inside your game project into which you’d place your raw content and from which your game would load the compiled XNB files. In theory it could be named anything since one of the things you would do in the constructor for your game is specify the name of the Content folder. XNA 4.0 has moved content (i.e. game assets like music, ...
Can Event-Based Components (EBC) be used to design libraries? Sure they can. FallenGameR asked a question along this line in response to my previous article. Let me demonstrate this with a simple library scenario: A function ToDictionary() is to be developed which converts a string like “port=8080;user=bart;passwo... into a Dictionary<string, string>. The usage should be like this: var td = new StringToDictionaryConverter(); var dict = td.Convert(“port=8080;user=... or var dict = new Dictionary<string, ...
In the past, I’ve had to put a type specific clone in each cloneable class, but with extension methods you can write a generic T specific clone class Program { static void Main(string[] args) { var b = new Blah() {X = 1, Y = 2}; var bb = b.Clone(); Console.WriteLine(string.Fo... {1}", bb.X, bb.Y)); } } public class Blah : ICloneable { public int X; public int Y; object ICloneable.Clone() { return MemberwiseClone(); } } public static class CloneExtension { public static T Clone<T>(this ...
I joined a fairly large project recently and it has a particularity… Once finished, everything has to be sent to the client under VS2005 using VB.Net and can target either framework 2.0 or 3.0… A long time ago, the decision to use VS2008 and to target framework 3.0 was taken but people knew they would need to establish a few rules to ensure that each dev would use VS2008 as if it was VS2005… Why is that so? Well simply because the compiler in VS2005 is different from the compiler inside VS2008… I ...
Lately I’ve ran into situations where I had to change elements or had to request a value in the DOM from Silverlight. jLight, which was introduced in an earlier article, can help with that. jQuery offers great ways to change CSS during runtime. Silverlight can access the DOM, but it isn’t as easy as jQuery. All examples shown in this article can be looked at in this online demo. The code can be downloaded here. Part 1: The easy stuff Selecting and changing properties is pretty straight forward. Setting ...
Have you ever needed to detect what part of the application is currently being viewed? This might be a bigger issue if you write a lot of shared/partial views or custom display or editor templates. Another scenario, which is the one I encountered when I first started down this path, is when you have some type of menu and you’d like to be able to determine which item represents the current page so you can highlight it in some way. A simple example is the menu that is created as part of the default ...
Recently, I started working on a new ASP.NET MVC 2 project and I wanted to reuse the data access (LINQ to SQL) and business logic methods (WCF RIA Services) that had been developed for a previous project that used Silverlight for the front-end. I figured that I would be able to instantiate the various DomainService classes from within my controller’s action methods, because after all, the code for those services didn’t look very complicated. WRONG! I didn’t realize at first that some of the functionality ...
Eager loading with EF To Do Eager loading use Projections (for e.g. : 1: var custWithAddresses = from c in context.Contacts 2: where c.LastName == "Gupta" 3: select new {c, c.Addresses} or use Include Query Builder Methods (Include(“Addresses”)) 1: from c in context.Contacts.Include("A... 2: select c; If there is multi-level hierarchical Data then to eager load all the relationships use Include Query Builder methods like customers.Include("Order.Or... to include Order and OrderDetail ...
I stole that from the back of a T-shirt I saw at the Orlando Code Camp 2010. This was my first code camp and my first time volunteering for an event like this as well. It was an awesome day. I cannot begin to count the “aaahh”, “I did-not-know I could do that”, in the crowds and for myself. I think it was a great day of learning for everyone at all levels. All of the presenters were different and provided great insights into the topics they were presenting. Here’s a list of the ones that I attended. ...
Time for some book news update. CLR via C#, 3rd Edition seems to have been out for a little while now. The book was released in early Feb this year, and needless to say my copy is on it’s way. I can barely wait to dig in and chew on the goodies that one of the best technical authors and software professionals I respect has in store. The 2nd edition of the book was an absolute treat and this edition promises to be no less. Here is a brief description of what’s new and updated from the 2nd edition. ...
Extension methods are a concise way of binding functions to particular types. In my last post, I showed how Extension methods can be created in the .NET 2.0 environment. In this post, I discuss calling the extensions from other languages. Most of the differences I find between the Dot Net languages are mainly syntax. The declaration of Extensions is no exception. There is, however, a distinct difference with the framework accepting excensions made with C++ that differs from C# and VB. When calling ...
Not that anyone would still need this, but in case you have a situation where the code MUST be .NET 2.0 compliant and you want to use a cool feature like Extension methods, there is a way. I saw this article when looking for ways to create extension methods in C++, C# and VB: http://msdn.microsoft.com/e... The author shows a simple way to declare/define the ExtensionAttribute so it's available to 2.0 .NET code. Please read the article to learn about the when and why and use ...
After working with FluentNHibernate and seeing examples of registries in StructureMap, I started craving the same thing for my registrations with Windsor. Our registrations often look like the following: public static void Register(IWindsorContainer container) { container.Register(Componen... container.AddComponent<I... Foo>(); ... } There are a few things I don’t like about this approach: Passing a container around through static methods is a hack. ...
Hi, I am currently involved in a project that requires information about the size of files to be displayed to a user. Quite a common scenario I'll imagine. There are many examples online of how to convert bytes to megabytes and gigabytes and display a friendly message to the user. All the ones I've seen however, involve creating a method that does this which takes a value as a parameter and returns a string. My solution for this project was to implement an extension method for variables of type long. ...
While my home development computer is fried I’m going to hack away at my backlog of non-code related posts. Today I’d like to discuss some of the advantages and disadvantages of using Microsoft MVC over WebForms. First of all, MVC is not the end all, magical platform that many people would like you to believe. In fact I wouldn’t even recommend it to beginner developers. However, if you have experience with .NET and you’re willing to put in the time to learn how MVC works, you will find that it offers ...
The main purpose of this post is to show what's required in the main 3 .net languages for filtering and sorting. I decided to put these two problems together because they presented themselves to me simultaneously . There are many instances where I need to Sort custom objects and many instances where I need to filter out duplicates from a list of custom objects. For filtering (Distinct), the effect happens with the framework finds unique values for the object. For the Sort, the default comparer will ...
This is a continuation from Deployment of Theme and Resource files Resource File Deployment (Resx) The second item was deploying Resource files to the App_GlobalResource directory present as a subdirectory under each IIS site for each SharePoint Web Application zone. Remember that you can have multiple IIS Sites for each “Logical” SharePoint Web Application. The other requirement we had was that each Web Application needed to have its own set of resource files and were to be deployed and scoped as ...
This article is a two-part series regarding the LinqToWikipedia provider. The first article covers the basic concepts of Linq as well as the client usage of this particular provider while the second article covers the inner workings of the LinqToWikipedia provider to give you an understanding of what it takes to create your own IQueryable provider. NOTE: You should download the latest build from Codeplex so you can follow along with the code samples. Creating your own IQueryable provider First off ...
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 ...