DotNet Support Blog

Introduction

In this tutorial we're going to examine the principals and construction of a basic ASP.NET 3.5 AJAX extender control. We'll discover how powerful extender controls can be for the reusability of code and behaviors. For more information on extenders refer to my books ASP.NET 3.5 AJAX Pocket Guide and ASP.NET AJAX Programming Tricks.

As we know, ASP.NET comes packed with a vast number of different controls, all having their own particular uses. However, it may become desirable to extend the behavior of these controls to better suit our needs. In most cases, the extension of these controls would involve building a new custom control, which inherits from the control we wish to extend and the new features coded. For example, consider a TextBox control, you may wish to limit the input of this control, change the background color when focus of the control has been changed, or display a watermark within the content of the control, etc. Building individual controls implementing each of the discussed behaviors, while definitely an option, is perhaps not the best option. What you’ll end up with is several different controls, all of which actually TextBox controls, however, each implementing a slightly different behavior, aside from being a tedious and repetitive task, it’s not the most efficient approach.

Welcome to concept of an extender control. Extender controls represent logical behaviors that can be attached to an existing control. Extender controls are server controls and can be attached to another control simply by identifying the client ID of the control we wish to extend.

Extender controls are standalone server controls, they implement from the Control class, have a Render() method and functions in a manner expected from any other server control. However, extenders offer the ability of injecting client-side code into the pages markup, hence granting the ability of extending the physical behavior of a server control. The controls an extender extends are not changed programmatically and are simply extended via client-side code, for example the addition of JavaScript event handlers to perform specific tasks based on a particular trigger. Extenders are specific to the ASP.NET AJAX Framework, this Framework simplifies the development of extender controls, as it offers a detailed client-side library we may make use of and also offers base classes we should inherit from when developing extender controls.

Extenders usually include a number of client-side objects defining the behavior of the target control. These objects are then written to the output stream by registering themselves with the ScriptManager control included within the page. A ScriptManager control must be present when making use of the ASP.NET AJAX base extender class.

Download all source files

Read more...

 

Often we need to capitalize the first letters of some word or some text (for example when we want to display users name or city name etc).
Since string class does not have a method to do this we could think that there is no built-in solution in C# for this problem...
But a little digging trough MSDN would help us find ToTitleCase method of TextInfo class in System.Globalization namespace that does exactly what we need: capitalizes the first letter of each word in the string.
here is how to use it:

using System.Globalization;

  ...

string capitalized = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("asp.net simply rocks!!!");

After the execution, capitalized string would have this value: "Asp.Net Simply Rocks!!!" which is exactly what we needed, right?
Off course, how will string be capitalized depends on the current culture that is set on your ASP.NET page, but we can easily override this and use the culture we want like this:

TextInfo UsaTextInfo = new CultureInfo("en-US", false).TextInfo;

string capitalized = UsaTextInfo.ToTitleCase("asp.net simply rocks!!!");

 

Wake up ASP.NET developers!

Posted In: . By Sothy Mom

The following contains unfair generalizations about developers, rough language and a bad attitude. Dear reader, this is tough love from yours truly.

You’re participating in the stagnation of the World Wide Web and you hold the human race hostage.

Ouch, that was a bit harsh, but it probably got your attention. That’s important because what I want to address is no laughing matter. There seem to be a huge unwillingness among ASP.NET developers to participate in evolving the web. This is not acceptable and surely not understandable since the web is what brings food on the table for most ASP.NET developers.

The hostage situation

It seems that other developers are much better to push the web forward than our camp is. Python, PHP, RoR and even Perl developers seem to be much more ideological in their approach to web development and makes a bigger effort in evolving it. That might be because these languages are more common in universities. In the meanwhile, ASP.NET devs just sit back and watch it happen without contributing or maybe even caring about it. That is not a flattering attribute by any means.

In case you are wondering, I’m talking about the semantic web or Web 3.0 if you will. Whenever I have written about it, no one really seems to care. Most other .NET bloggers haven’t written about it and the online discussions rarely have ASP.NET devs joining in. As I see it, ASP.NET developers don’t care about the future of the platform they work with every single day and that is a crime.

It’s a crime because you as a developer limit the billions of web users from utilizing all the wonderful possibilities of the semantic web. It’s a crime because you hold them hostage for personal convenience. It’s more convenient to sit back than to learn something new, but this time it’s different. This is not equivalent to learning LINQ or the MVC Framework. This is bigger than you and it’s bigger than the client/company you are working for. This is what will define our online future.

It’s growing

You might think I’m being a bit dramatic about this matter and you are absolutely correct. According to Tim Berners-Lee, the semantic web is growing exponentially these days, but the ASP.NET camp is sleeping through it. The problem is that it will make the growth slower and then we are back at the hostage situation. If we don’t help push native support for these things in the next version of the .NET Framework and Visual Studio, then we become even further alienated and left behind. This matter demands dramatic change in the way we approach web development, so I think it is more than justified to be dramatic.

The semantic web is starting to become useful due to its growth lately, but for it to become truly useful, it has to be widely adopted by big, medium and small websites containing any structured data worth sharing (since it’s on the Internet in the first place, it most likely is worth sharing).

Make a small effort

What puzzles me again and again is that only a fraction of web developers use microformats or any other semantic formats. In the light of how easy and useful it is, it leaves me saddened. It is not a duty to implement semantic mark-up; it is a privilege to help drive the future of the web – and with a minimal effort as an added bonus.

So, if you have a website containing user profiles, calendar events or any other structured data, then please tag them up with the appropriate microformat and XFN tags. If you want to do a little more, then FOAF is a good place to start. Remember, it starts with us, the developers, so wake up! (the lack of the word 'please' is not accidental, although appropriate).

Semantic fun-facts

Did you know that Yahoo has a new search engine in beta that utilizes microformats in a very cool way?
Did you know that Technorati has an hCard microformat parser service?
Did you know that Google has a Social Graph API that takes advantage of microformats and FOAF?
Did you know that LinkedIn is the largest publisher of the hResume microformat?
Did you know that the Operator toolbar for Firefox let’s you utilize microformats on any web page?
Did you know that I've written a guide to implementing microformats in ASP.NET?

 

Do you use database projects in Visual Studio? If not, then now is a good time to start. It is the best way I have found to source control my databases without actually sticking the database file itself in the repository. It is very simple to add to your solution and creates a default directory structure for your create scripts, change scripts and queries. Best of all the project will be recognized by source control and added to the source code repository. This means you can keep versioned scripts for maintainability. It also gives you the option to do the dreaded rollback!

Lets start by creating a database project of our own. To start, we will create a blank Visual Studio solution.

screenshot-2008-05-05_18_56_00

Now click File -> Add -> New Project.

screenshot-2008-05-05_18_57_08

You should get the dialog below. Now we will look in the node of "Other Project Types", click "Database" then select "Database Project". This will give us the opportunity to name our database project. We will call this one by the database we are going to be using, good ol' Northwind.

screenshot-2008-05-05_18_58_44

Next you will be asked to setup a database reference. So here all we have to do is add a new reference to the Northwind database.

screenshot-2008-05-05_18_59_29

My database will be in SQL Server, yours can be in any of the choices shown below.

screenshot-2008-05-05_19_01_31

Now we just set the server name and choose the Northwind database.

screenshot-2008-05-05_19_02_07

You should then test your connection (out of good practice) and see the dialog below upon success.

screenshot-2008-05-05_19_02_15

Now we will see our database reference shown in the original list of references. Just double click on your newly added reference.

screenshot-2008-05-05_19_02_31

Now your project should look something like the shot below.

screenshot-2008-05-05_19_02_51

Once we get this far, we need to start filling our folders with database scripts. You can add new folders if you wish, but I think the default folder structure is good enough. Now then, we can use the database publishing wizard to get our first create script into the "Create Scripts" folder.

Double click the reference to your database in the database references and it should bounce you to the server explorer window with your data connection all setup.

screenshot-2008-05-05_19_05_20

Right click your data connection and click "Publish to provider..." to start the database publishing wizard.

screenshot-2008-05-05_19_05_31

Now we select the database we would like to publish, so again I will choose Northwind.

screenshot-2008-05-05_19_05_52

Now with the "Script to file" option chosen, we will browse to the "Create Scripts" folder in our database project to put the outputted .sql file.

screenshot-2008-05-05_19_06_51

Now we get to choose some options. I am going to set the output for SQL Server 2005 and select to script the database schema only.

screenshot-2008-05-05_19_07_18

Now we can review the summary of what we have configured and click finish.

screenshot-2008-05-05_19_07_26

Upon clicking finish, we will see the progress of the .sql file being scripted to the hard drive.

screenshot-2008-05-05_19_08_07

Ok, for some reason I couldn't find a refresh button in the database project to see the file that was created so we will right click the "Create Scripts" folder and click "Add Existing Item..."

screenshot-2008-05-05_19_10_15

Then browse to our .sql file and click the "Add" button.

screenshot-2008-05-05_19_10_27

Now we should see it in our project and we can also see the contents of the generated script by opening it in the editor.

screenshot-2008-05-05_19_12_20

screenshot-2008-05-05_19_12_31

It really is just that simple. I mean if nothing else you have a designated place to put all your SQL scripts for your database. The big plus is that your scripts will be source controlled. Also, anyone who opens the solution will know exactly which databases are used by the project.

 

LINQ.Flickr 1.3

Posted In: . By Sothy Mom

Just released another version of LINQ.Flickr. The release is out with several bug fixes, code optimization, new feature and overall mocking support. I have used Typemock for the unit test of the product. In coming posts, I will show how powerful mock can be in faking routine like upload photo. But, you can dig it right away, if you go by the release page and download a copy of the product. Truly speaking, testing was never fun for serviced API till mock engine is at my hand.

The release is not all about re-factoring and mocking , but now you can query, add , delete photo comment , query people and popular tags and do more that are mentioned in the release page.

Now, doing complex query is even more fun. lets take this.

var query = from photo in _context.Photos
where photo.Id == photoId && photo.PhotoSize == PhotoSize.Medium
select new FlickrPhoto
{
    Id = photo.Id,
    Description = photo.Description,
    Title = photo.Title,
    Url = photo.Url,
    User = photo.User,
    Comments = ((from comment in _context.Photos.Comments
                 where comment.PhotoId == photoId
                 select new PhotoComment
                 {
                     Author = comment.Author,
                     AuthorName = comment.AuthorName,
                     PermaLink = comment.PermaLink,
                     PhotoId = comment.PhotoId,
                     Text = comment.Text,
                 }).ToList<PhotoComment>()),
    Tags = photo.PhotoTags.Select(tag => tag.Title).ToArray<string>()
};

FlickrPhoto newPhoto = query.Single();

The query is about getting the photo info for a specific photo id and I have now combined it with tags, comments to make it more useful. Also, few posts back, I have mentioned about using a RestToCollecitonBuilder  to build an object on REST response,  it is in action in this release as well.

Finally, don't forget the link and it's www.codeplex.com/linqflickr . In the end, this project is not about querying Flickr and getting photo out of it, but it could be a great learning tool for Mocking, for building custom LINQ provider (with LinqExtender) and other things that you might need to know like, how to define a service endpoint by interface.

 

Unit Testing Events

Posted In: . By Sothy Mom

In this article I will show you how you can unit test your events. I will show you a simple technique that will enable you to test if your events fire exactly as often as you want them to and I will provide you with two implementations. One implementation works well with the .NET Framework 2.0 and the second one uses .NET 3.0 in order to minimize the code necessary.

I am assuming you are familiar with NUnit.

In .NET 2.0 it is useful if you introduce a helper class which looks like this one:

class EventCounter    {
   private int _counter;

   public int Value
   {
      get { return _counter; }
      private set { _counter = value; }
   }

   public void Increment(object o, EventArgs e)
   {
      Value++;
   }
}

The class doesn’t do much. It has only one member (Value) which is increased whenever the Increment method is called.

Well, I must admit that this is one of the most weird classes I ever wrote but it is quite useful in testing code... take that:

[Test]
public void TestIfListChangedEventIsFiredOnceWhenMovingElement()
{
   ResponsiveList<string> collection = new ResponsiveList<string>();
   EventCounter counter = new EventCounter();
   collection.Add(“item 1”);
   collection.Add(“item 2”);
   collection.Add(“item 3”);

   collection.ListChanged += new EventHandler(counter.Increment);
   collection.MoveElement(0, 2); //moves item from index 0 to 2       
   Assert.AreEqual(1, counter.Value);
}

This test checks if the ListChanged event of the class ResponsiveList is fired when elements are moved within the list using the MoveElement method.

Using this class you can not only test if your event fires, you can also test if your event fires exactly as often as you want it to. I found this approach extremely useful and more than once it showed me that some events where fired too often or not at all.

It is a good idea to not only test wether an event fires or not but also test if it fires as often as desired. Firing too many events can result in bad performance and can cause bugs which can be very hard to uncover.

As mentioned before the above code is very old and given the power we have with anonymous methods you don’t even have to use such a weird EventCounter class anymore. Nowadays (.NET 3.0) you could write this unit test like this:

[Test]
public void TestIfListChangedEventIsFiredOnceWhenMovingElement()
{
    ResponsiveList<string> collection = new ResponsiveList<string>();
    collection.Add(“item 1”);
    collection.Add(“item 2”);
    collection.Add(“item 3”);

    int counter=0;
    collection.ListChanged += (sender,e) =>
    {
        counter++;
    });
    collection.MoveElement(0, 2); //moves item from index 0 to 2

    Assert.AreEqual(1, counter);
}

As Niki points out, even in .NET 2.0 you can use a similar approach and spare yourself from using a helper class:

[Test]
public void TestIfListChangedEventIsFiredOnceWhenMovingElement()
{
    ResponsiveList<string> collection = new ResponsiveList<string>();
    collection.Add(“item 1”);
    collection.Add(“item 2”);
    collection.Add(“item 3”);

    int counter=0;
    collection.ListChanged += (delegate)
    {
        counter++;
    });
    collection.MoveElement(0, 2); //moves item from index 0 to 2

    Assert.AreEqual(1, counter);
}

 

  

 

FOAF parsing and crawling in C#

Posted In: . By Sothy Mom

I’ve been looking deeply into FOAF lately and last week I worked on a parser that could wrap a FOAF document into a strongly typed class for easy consumption by C#. Now I want to share it with anyone interested. It appears there are no FOAF parsers available in C# yet. I wasn’t able to find any.

The parser

The class FoafParser has two public methods, Parse and ParseFriendsAsync, which handles two different approaches in fetching FOAF documents.

The Parse method

This method takes a URL as a parameter which must point to an online FOAF document. It then parses the foaf:Person element which contains fields such as name, birth date, photo, homepage etc. It then looks for people in the FOAF document that are described as someone you know, parses the information available and adds it to a public collection property. The following example parses a FOAF document and binds it to an ASP.NET Repeater.

FoafParser parser = new FoafParser();
parser.Parse(new Uri("
http://example.com/foaf.xml"));
if (parser.IsParsed)
{
  ltOwner.Text = parser.Owner.Name;
  repFriends.DataSource = parser.Friends;
  repFriends.DataBind();
}

The ParseFriendsAsync method

When you list people you know in a FOAF document, it is common to only provide very little information such as the full name. When that is the case it is also common to provide a link to that persons FOAF document using the rdfs:seeAlso tag. We can then use that link to retrieve all your friend's FOAF documents and parse them as well.

It can take a long time to retrieve all those documents one at a time, but if we do it asynchronously then we can speed things up substantially. When you have called the Parse method on the FoafParser class, you can then call ParseFriendsAsync. It loops through all the friends that the Parse method found in search for the rdfs.seeAlso tag. When it finds it, a web request is made to retrieve the FOAF document of that friend and then parse it for information.

When the ParseFriendsAsync method is finished, it triggers an event you can listen to. All the friends with FOAF documents have now been updated in the collection.

private void RetrieveAsync()
{
FoafParser parser = new FoafParser();
  parser.Parse(new Uri("
http://example.com/foaf.xml"));
if (parser.IsParsed)
  {
    parser.FriendParsingComplete += new EventHandler<EventArgs>(parser_FriendParsingComplete);
    parser.ParseFriendsAsync();
  }
}

void parser_FriendParsingComplete(object sender, EventArgs e)
{
// Now the Friends collection has been updated asynchronously.
FoafParser parser = (FoafParser)sender;

  Response.Write(parser.Friends.Count);
}

Download

In the zip file below you’ll find the FoafParser.cs class as well as an example .aspx page and code-behind file.

FoafTester.zip (3,77 kb)