Saturday, October 24, 2009

Linqify your legacy webapplications: five real-world refactor examples

Edit notes:
- Edited examples based on Bart's feedback (see comments).

This post is meant for developers who are upgrading legacy webapplications to .NET 3.5 and for developers who know Linq, but have a hard time finding scenarios to apply Linq.

I got my inspiration for this post by reading Professional Refactoring in C# & ASP.NET (Wrox Programmer to Programmer).

I downloaded the My Web Pages Starter Kit to find some examples, which is written for .NET 2.0. I upgraded it to .NET 3.5 to use Linq.

Below you can find some real-world examples of refactoring to use Linq.

Querying collections never has been this clean!


Example one

Before

   1:  bool blnTravelDiary = false;
   2:  foreach (string theme in themes) {
   3:      if (Path.GetFileName(theme) == "TravelDiary")
   4:              blnTravelDiary = true;
   5:  }


After

   1:  bool blnTravelDiary = themes.Any(theme => Path.GetFileName(theme) == "TravelDiary"); 



Example two

Before

   1:  foreach (RoleData data in _roles) {
   2:      if (data.RoleName.Equals(roleName, StringComparison.CurrentCulture))
   3:              return true;
   4:  }
   5:  return false;


After

   1:  bool exists = _roles.Any(roleData => roleData.RoleName.Equals(roleName, StringComparison.CurrentCulture));



Example three

Before

   1:  foreach (RoleData data in _roles) {
   2:      if (data.RoleName == rolename) {
   3:              found = data;
   4:                      break;
   5:           }
   6:  }

   7:  return found;


After

   1:  var found = from RoleData data in _roles
   2:              where data.RoleName == rolename
   3:              select data;
   4:  return found.FirstOrDefault();



Example four

Before

   1:  List<string> foundRoles = new List<string>();
   2:  foreach (RoleData data in _roles){
   3:      if (data.Users.Contains(username))
   4:              foundRoles.Add(data.RoleName);
   5:  }
   6:  return foundRoles.ToArray();


After

   1:  var data = from RoleData roleData in _roles
   2:             where roleData.Users.Contains(username)
   3:             select roleData.RoleName;
   4:  return data.ToArray();



Example five

Before

   1:  foreach (MembershipUser user in Membership.GetAllUsers())
   2:  {
   3:      if (string.Compare(user.UserName, txtUserName.Text, true) == 0)
   4:          {
   5:              Login1.UserName = user.UserName;
   6:                     return;
   7:          }
   8:  }



After

   1:  var matchingUsers = from MembershipUser user in Membership.GetAllUsers()
   2:                      where string.Compare(user.UserName, txtUserName.Text, true) == 0
   3:                     select user.UserName;
   4:   
   5:  var firstMatch = matchingUsers.FirstOrDefault();
   6:   
   7:  if (firstMatch != null) {
   8:      Login1.UserName = firstMatch;
   9:  }

Friday, October 23, 2009

The evolution of the Windows desktop in images, from Windows 3.1 To Windows 7.

@CodingHorror: I can't deal with Chrome themes or Windows 7 themes... at all. Give me plain, simple, clean, and uncluttered. kthxbye

Jeff Atwood tweeted this a few days ago. This triggered me to assemble a list of Windows desktops, from Windows 3.1 to Windows 7.

I also don't think the extra UI stuff in Windows Vista and Windows 7 add extra value. I'm still a big fan of the simple Windows XP UI.

Which one do you like best? Is there to much clutter in the new interfaces?

Check out the list of images below to see the evolution of the Windows desktop.

Windows 3.1


Windows 3.5


Windows 3.51


Windows 4


Windows 95


Windows 98


Windows 2000


Windows XP


Windows Vista


Windows 7



Sunday, October 18, 2009

Building a simple Twitter widget using TweetSharp and ASP.NET

Widgets are a great way to spread your content. Users can just copy and paste some simple HTML or JavaScript, and off they are. By embedding this HTML or JavaScript, content is loaded from another server. Perfect examples are Google ads and Amazon ads.

I wondered how hard it could be. That's why I wrote a small Twitter widget using ASP.NET and TweetSharp. This widget simply shows your Tweets. To keep things simple it's HTML hosted in an iFrame. This solution might be a scalability nightmare tho, because it's executing the code every time the page loads.

When finished the widget looked something like this.



Let's take a look how you can build your own.

Get tweets by username

I used the very Elegant TweetSharp API for this.



   1:  private IEnumerable<TwitterSearchStatus> GetStatuses(string screenName) {
   2:       var twitter = FluentTwitter.CreateRequest().
   3:                                  Search().Query().FromUser(screenName);

   4:       return twitter.Request().AsSearchResult().Statuses;
   5:  }      



Build the widget

This method builds the HTML. I used the HtmlTextWriter class for this. A safe way to build HTML.


   1:   private String BuildWidget(string username, IEnumerable<TwitterSearchStatus> statuses) {
   2:              StringWriter stringWriter = new StringWriter();
   3:              
   4:              using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter)) {
   5:                  htmlWriter.RenderBeginTag(HtmlTextWriterTag.B);
   6:                  htmlWriter.Write("My tweets");

   7:                  htmlWriter.RenderEndTag();
   8:   

   9:                  htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
  10:                  htmlWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
  11:   
  12:                  foreach (var status in statuses) {
  13:                      htmlWriter.RenderBeginTag(HtmlTextWriterTag.Li);
  14:   
  15:                      htmlWriter.Write(String.Format("({0})", status.CreatedDate.ToString("hh:mm")));
  16:                      htmlWriter.Write(" ");
  17:                      htmlWriter.Write(status.Text);
  18:                      
  19:                      htmlWriter.RenderEndTag();
  20:                  }           
  21:   
  22:                  htmlWriter.RenderEndTag();
  23:   
  24:                  htmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, "http://twitter.com/" + username);                
  25:                  htmlWriter.RenderBeginTag(HtmlTextWriterTag.A);
  26:                  htmlWriter.Write("Follow me");
  27:                  htmlWriter.RenderEndTag();
  28:   
  29:                  htmlWriter.RenderEndTag();
  30:              }
  31:   
  32:              return stringWriter.ToString();             
  33:          }



Writing the widget to the page

On the Page_Load event of the Page I get the username from the QueryString, get the statuses for this username, pass them to the BuildWidget method and write that result to the Reponse Stream.


   1:  protected void Page_Load(object sender, EventArgs e) {
   2:              string username = Request.QueryString["username"];;
   3:              if (!String.IsNullOrEmpty(username)) {
   4:                  Response.Write(BuildWidget(username, GetStatuses(username)));
   5:              }
   6:          }



Embedding the widget in a page

I hosted the widget in an iFrame. Set the src attribute of the iFrame to the url of your widget.


   1:  <div style="width:30%;height:100%;float:right"> 
   2:              <iframe scrolling="yes" 
   3:                  style="" 
   4:                  frameborder="1" 
   5:                  src="http://localhost:1524/TwitterWidget.aspx?username=JefClaes" 
   6:                  marginheight="0" 
   7:                  marginwidth="0">
   8:              </iframe> 
   9:          </div> 



That was pretty easy right?

Get the source.

Saturday, October 17, 2009

Format your code using Syntax Highlighters

Yesterday I asked on Twitter if it bothers people that I use screenshots for codesnippets, and Lee Dumond honestly answered that screenshots suck.

Well he is right. On my monitor the screenshots look pretty good, but on laptops/smaller monitors they aren't handy at all.

Today I looked for Syntax Highlighters. Looks like there are two big players in the syntax highlighting business, and a few smaller ones.

I made a summary of interesting Syntax Highlighters I found. I will be experimenting with those in the coming weeks.

If you use one that isn't in this list, please let me know by leaving a comment!

(Edit: Don't forget to scroll to look at the list of supported languages and features!)

Saturday, October 10, 2009

Is this something the blogosphere could use?

Social networking is one of the core elements to promote your blog.

I can imagine that this becomes a hassle if you are a professional blogger and have to promote multiple blogs. Technology is able to bring a solution offcourse.

What you see below is a picture of the PostBroadcaster. The PostBroadcaster is a service which keeps an eye on your Rss feed, and as soon as it sees an update in your Rss feed, it broadcasts this to multiple social networking sites.



Please give me your opinion. Could this be "something"?

Friday, October 2, 2009

RSS in .NET

A few days ago, I was playing with some RSSFeeds.

As far as I knew, I had to build an HttpWebRequest, get the HttpWebReponse and parse the response. While searching for the RSS defenition, I realised that this must have been done 1000 times before.

I googled RSS .NET and found one relevant link to a dead/failed open source project. Looking further I came across some articles which used an XmlReader and LinqToXml, but this wasn't what I was looking for. I asked whether there is any good RSS library in .NET at StackOverflow, and one smart guy pointed me to the System.ServiceModel.Syndication namespace. This is new in .NET 3.5 and after looking around some more I found out that it's a pretty unknown namespace.

After playing with it for 15 minutes I was pretty sure this was exactly what I was looking for.

Reading and creating RSS has never been this easy/safe.
You can find how to read an RSS Feed an how to create a new RSS Feed below.

Reading an RSS Feed




Create an RSS Feed




Pretty simple right?

Download the source.