Cool beans! Extension Methods on Interfaces

by Xavier Pacheco 17. February 2012 04:09

Now this is just cool. You probably already know about extension methods. If not, here’s a quick rundown. Say you have the following classes defined:

        public class Package
        {
            public decimal Weight {get; set;}
        }
 
        public class PackingList
        {
            public List<Package> Packages { get; set; }
        }

Now suppose you need to calculate the total weight for all items in the PackingList. Obviously, you could simply run the items through a for loop or and calculate it. However it would be nice if the PackingList had a TotalWeight() method that you could invoke that would calculate this for you. Also, let’s assume that for whatever reason you cannot modify the PackingList class (perhaps you don’t have the source).

Enter the extension method.

Consider the following code:

        public static class ExtensionMethods
        {
            public static decimal TotalWeight(this PackingList packingList)
            {
                decimal total = 0; 
                foreach (var package in packingList.Packages)
                    total += package.Weight;
 
                return total; 
            }
        }

Notice the this parameter. This indicates to the compiler that the TotalWeight() method is an extension method for the PackingList class.  Assuming all the namespace settings are proper, you would be able to invoke the following line of code after creating and populating a PackingList:

            Console.WriteLine("Total Weight is {0}", packingList.TotalWeight());

Alright, now that we covered that, here’s the cool stuff.

Let’s make PackingList implement the IEnumerable interface which only makes sense since it is a container of a list of Packages. Here’s the code:

    public class PackingList: IEnumerable<Package>
    {
        public List<Package> Packages { get; set; }
 
        public IEnumerator<Package> GetEnumerator()
        {
            return Packages.GetEnumerator(); 
        }
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator(); 
        }
    }

Now our extension method becomes:

        public static decimal TotalWeight(this IEnumerable<Package> packingList)
        {
            decimal total = 0;
 
            foreach (var item in packingList)
                total += item.Weight;
 
            return total;
        }

Note the first parameter type change. Not having to specify the Packages property might not seem like a big gain. But check this out. In C#, arrays implement the IEnumberable<T> interface. Therefore, by having the extension method take the IEnumerable<Package> parameter it also extends arrays!  Therefore, the following code also works:

 
            Package[] packageArray = {
                new Package { Weight = 2.0M},
                new Package { Weight = 5.2M},
                new Package { Weight = 3.2M}};
 
            Console.WriteLine("Total Weight is {0}", packageArray.TotalWeight());

Neat, huh?!

DotnetKicks

Tags:

C#

Snapshot tool

by Xavier Pacheco 30. January 2012 02:46

Every now and then, I find a useful development tool. Here’s one I use often, it is a Firefox snapshot addon that can take a snapshot of a web page (even the hidden area). It even prompts you for a next action (add to clipboard, email, save, etc).

https://addons.mozilla.org/en-US/firefox/tag/snapshot

DotnetKicks

Tags:

Development Tools

Tutorial on the Model-View-View-Model (MVVM) Pattern

by Xavier Pacheco 27. September 2010 02:23

I just came across perhaps one of the best tutorials of the Model-View-View-Model pattern by Jason Dolinger here. In this demo. Jason covers a number of topics including:

  • Benefits of MVVM
  • MVVM Definition and Usage
  • Binding: Individual properties and ObservableCollections
  • MVVM Notification
  • Advantage of MVVM with Unit testing
  • Using the Unity Container
  • Advantage of MVVM when Using Expression Blend
  • Adding Row-Level View Models

What I found particularly useful about Jason’s tutorial was that he begins with the typical, naive approach of creating WPF/Silverlight applications and illuminates their shortcomings. He then springboards into illustrating the proper way to design applications using the MVVM pattern.  I should note that in this tutorial Jason is developing a WPF application. However, as this blogger states, the practices shown also apply to Silverlight applications.

If you are creating Silverlight or WPF application, understanding the concepts of this tutorial are ABSOLUTELY ESSENTIAL.

DotnetKicks

Tags: , ,

BlogEngine.NET 1.6.1 Rocks

by Xavier Pacheco 25. June 2010 06:27

image

I am really liking the update to the BlogEngine.Net platform. There are several new features but my absolute is the Comment Management and Comment Spam Filtering feature. I get a ton of comment spam - you know, those stupid comments like, “Hi, interesting post. I have been pondering this issue,so thanks for posting. I will visit your blog again” or This is by far one of my favorite updates you have done, I don't agree on some points but you are good blogger for sure.” These aren’t real comments. Such comments are used to increase search engine ranking to the URL provided with the comment. You can read about comment spam here. Needless to say, I am thrilled that BlogEngine.Net has provided me a way to deal with this. According to their website:

Comments across all posts can be viewed, edited, deleted or approved in one convenient area.  Comments can still be manually moderated, but now moderation can be automated by running comments thru remote or local comment spam validation services.

There are other new features. You can see a list of them here.

The update was relatively easy. Most of the pain was getting the site to run under IIS 7 on my local machine so that I could test the update. Anyway, it required a few changes to my Settings.ini file, my theme’s .css file and deleting a directory that is no longer needed. That said, it was a smooth update.   By the way, there is a great post on dealing with the IIS 7 issues here.

Happy blogging!

 

DotnetKicks

Tags:

BlogEngine.NET

Internet access on PC through Android phone - yeah!

by Xavier Pacheco 28. April 2010 12:18

It really irritates me that most airports (and other establishments) do not provide free Internet access. I was thrilled to find out about EasyTether.  EasyTether is an Android application that tethers your phone to your PC giving you Internet access over your phone’s data plan. The speed is totally acceptable.

I have a T-Mobile G1 and there were some issues getting it to work properly. This does not seem to be a problem for others using newer Android devices. If you have a G1 and can’t get it working, follow this link for some help in getting it setup. I used the method of editing the registry and using drivers from the developer SKD to get this working. You’ll find these instructions on the link I provided.

Have fun!

DotnetKicks

Tags:

Technology | Tech-Tips | Android

warning MSB3214

by Xavier Pacheco 12. April 2010 08:30

I was trying to expose some .NET types through COM and kept getting the following warning:

warning MSB3214: "*.dll" does not contain any types that can be registered for COM Interop.

And of course, no types were exposed. Turns out that setting "Register for COM interop" under Project/Options is not enough. You must also specify the following in AssemblyInfo.cs

[assembly: ComVisible(true)] 
DotnetKicks

Tags:

Getting the most from your daily stand-up meetings

by Xavier Pacheco 2. March 2010 09:50

Most meetings, I loathe. Often they are drawn-out, not really useful except to maybe a few attendees and there are always those who seem to enjoy the platform to give their long-winded speeches. That said, meetings I actually enjoy and find very useful are Stand-up meetings.

Stand-up meetings are brief meetings held daily and typically at the same time and place where team members can report on their status on a given project. Typically, each member reports on three specific items. These are:

  1. What did I accomplish yesterday?
  2. What am I going to attempt to accomplish today?
  3. What problems am I facing?

Stand-up meetings are deliberately kept short, usually from 5-15 minutes. When meetings go beyond 15 minutes, it is usually an indicator that there is too much discussion. It is important to remember that stand-up meetings are not the place to solve problems or to elaborate on project specifics. Rather, they are the time to report status and identify potential issues that might hinder a developer’s progress.

To get the most out of daily stand-up meetings, each team member must be prepared with his or her status report. In other words, they should come to the meeting with perhaps a written statement of their status. Having to write the statement is a good discipline to help one from dragging on, yet allows for a meaningful status report. I like the idea of a 3x5 rule. That is, if what one has to report cannot fit on a 3x5 card, they are saying too much. As an example, one might report the following:

“Yesterday I installed our repository, restructured the submission services and finished the submission logic. Today I am going to finish the retrieval logic and configure the CI server to run test scripts on the XYZ project. The problems I am facing is that I’m not sure what to use as test data and there is no documentation on the database”

Note, that the report was brief and did not include details as to how the tasks were accomplished or other unnecessary discussion. Finally, the developer stated a possible problem. At this point it is appropriate to identify people who can help mitigate the issues that developer is facing. Note, this is not the time to actually solve any issues, only to identify who can help solve them. Therefore, a likely response might be:

“I can help you with the db structure, see me after the meeting” or “See so and so after the meeting, he has already come up with test data.”

Keep in mind that it is often, it is necessary to schedule another meeting.

With such a limited scope for a meeting, one might wonder why have them at all. Why not just email the PM status? Here are a few reasons why stand-up meetings are important.

  1. Stand-up meetings increase accountability by surfacing commitments and responsibilities to the entire team. Not only do developers report status but so does the PM. Since these meetings are held daily, everybody becomes aware of the overall project status by tracking with what others are doing.
  2. Stand-up meetings help detect and reduce bottlenecks to the project quickly. Since these meetings are held frequently, problems are quickly identified and addressed. In my experience, weekly meetings are not frequent enough to accomplish this. By practicing this daily, risk mitigation becomes a priority.
  3. Stand-up meetings help developer commit to realistic goals. It is much easier to commit to a days worth of work than to try to guess what one might accomplish in a week. This also helps the PM in knowing how much work the entire team can actually get done which results in better estimates given to management.
  4. Stand-up meetings unify the team by getting team members on the same track with the project and encouraging communication and team effort in dealing with problems.

There are many more benefits to the stand-up meeting and you find numerous articles on the Internet and in most books on the Agile development process. Here are a few links on stand-up meetings:

It's Not Just Standing Up: Patterns of Daily Stand-up Meetings

Daily Stand Up Meeting

Stand-up Meeting Antipatterns

DotnetKicks

BlogEngine.Net: Page Level Security

by Xavier Pacheco 23. August 2009 13:17

I needed a way to achieve page-level security for a BlogEngine.net deployment. Brian Carter on his blog provides a pretty good solution with a user control that you simply put on the page you want to secure.  You’ll find it here: BE.N Page Security User Control. One modification I had to make was to the SecurityRole.ascx.cs file. The Page_Load even contains logic to redirect a user to the login page if that user does not belong to the role specified in the user control parameter (see his website for instructions). I simply modified the path to my own page as shown below.

            if (!isInRole) Response.Redirect("~/page/LeaderNot.aspx");
 

Have fun!

DotnetKicks

Tags:

ASP.NET | .NET | BlogEngine.NET | C#

Systools for Delphi 2009 available

by Xavier Pacheco 14. July 2009 09:12

Just a quick post to let all you loyal Systools users that can find the Delphi 2009 packages here:

https://forums.codegear.com/thread.jspa?threadID=18029&tstart=0

DotnetKicks

Tags:

Delphi

Two PostList Extensions to the BlogEngine.net Platform

by Xavier Pacheco 5. June 2009 02:06

My blogging platform of choice is the open-source BlogEngine.net. Why? Because if there's a feature not inherently supported, I can simply fire up Visual Studio and write it myself. Ok, so BlogEngine.net is not for the faint of heart when it comes to blog deployment, but for power bloggers who are unsatisfied with the limitations of other platforms, BlogEngine.net is that way to go.

This post is about two features that I needed to develop myself. I am making them available here for other BlogEngine.net users.

1. An Author-filtered post list for non-blog pages

BlogEngine.net has the capability to add static web pages. This enables you to use BlogEngine.net as more than just a blogging platform. I have used BlogEngine.net to develop regular websites, for instance see www.CubScoutPack55.com and www.xapware.com.

I needed to add a bloglist to a static page, however the list should display only posts for a given author. Note that this is not the same as the standard filtered postlist supplied with BlogEngine.net. Already, there is a user control (\user controls\PostList.aspx) that you can embed within a static page by entering the following text into the page's markup:

uc1

That's all fine except that I need display only posts by a specific author. Therefore, I created the AuthorPostList.ascx user control. The entry in the static page markup now becomes:

uc2

You will see this implemented in the cub scout site: www.CubScoutPack55.com where each den page has its own author, the Den Leader for that page. When a certain Den Leader, say for instance the Tiger Den Leader, enters a blog post, his post will show up only in his page. This is handy because it allows me to distribute blog posts according to the poster.

You can download the control at the bottom of this post. To use it, simply pop it in your "/User controls" directory and add the following text to any static page.

uc3

2. A Category-filtered post list for non-blog pages

I recently created a blog for my family at: www.PachecosInColorado.com. We have a major event happening and wanted to create a static section within our site to keep our family and friends up to date (we are adopting from Ethiopia). In the same way that I embedded author specific posts on a static page, I want to embed category specific posts on a static page. Therefore, only posts related to the "Adoption" category would appear on the page for adoption. Posts in other categories like recipes, home-schooling, etc, would be filtered out.

My solution was to create the CategoryPostList.ascx user control. It is also located in the user controls directory. To use it, you simply put the following into the markup of the page where you want the posts to appear:

uc4

That's it! You can download this control here. Try it out and feedback, corrections, comments, questions are welcome.

The Controls

AuthorPostList

CategoryPostList

DotnetKicks

Tags: ,

ASP.NET | BlogEngine.NET

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 X Talks Tech