How Rockstars nest Repeater controls in ASP.Net

ASP.Net 4 Comments »

kick it on DotNetKicks.com

A couple of days ago while I was busy coding I ran into problem where I needed to nest Repeaters. There were a number of articles I found but they all dealt with nested Repeater controls using a DataSet as the data source but I needed to use a custom collection (List<T>).

Now I had not run into this requirement before as I have only been on ASP.Net 2.0/3.5 for about 6 months as we jumped from ASP.Net 1.1/Visual Studio 2003, after 3 years, right to the Visual Studio 2008 beta.

Legends of rock need not read further

To you more experienced 2.0+ guys this may be a moot point because you could do this with your eyes closed, while drinking an expresso, while also catching up on some Purple and Brown on YouTube. For that I commend you but will continue to address the rest of us mere mortal coders :D.

Why so touchy?

I suppose this issue may hold more importance to me because when I ran into the problem I was on a very tight deadline to produce a working prototype. The possibility that we might lose the client if they couldn’t have something to show at their next board meeting compounded my frustration with this road block. Needless to say, being the rockstar that I am, I got it done inspite of this issue and we are all set to give that demo for them.

The real point

Okay to the real point of this article. I threw together a simple project to illustrate how I resolved this problem and how you can avoid being caught of guard by it in the future.

The view

Here is the code for the nested Repeater controls on the WebForm.

<asp:Repeater ID="TeamRepeater" runat="server" OnItemDataBound="OnTeamRepeaterItemDataBound">
	<ItemTemplate>
		<h2><%# ((NestedRepeaterSample.HockeyTeam) Container.DataItem).Name %></h2>
		<ul>
		<asp:Repeater ID="PlayerRepeater" runat="server">
			<ItemTemplate>
				<li><%# ((NestedRepeaterSample.HockeyPlayer) Container.DataItem).Name %></li>
			</ItemTemplate>
		</asp:Repeater>
		</ul>
	</ItemTemplate>
</asp:Repeater>

As you can see I have gone with a hockey theme for this example, being Canadian and all, instead of some boring author and book list.

Some setup tasks

In order to get this show on the road I needed to do a few things.

Firstly I needed to create the two classed mentioned in the view code. Here they are.

public class HockeyTeam {
	string name;
	List<HockeyPlayer> players;

	public HockeyTeam(string name) {
		this.name = name;
		players = new List<HockeyPlayer>();
	}

	public List<HockeyPlayer> Players {
		get { return players; }
	}

	public string Name {
		get { return name; }
	}
}

public class HockeyPlayer {
	string firstName;
	string lastName;

	public HockeyPlayer(string firstName, string lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public string Name {
		get { return firstName + " " + lastName; }
	}
}

Nothing complicated here.

Now with our HockeyTeam and HockeyPlayer classes created I am going to populate them. In a real situation they would probably be filled from a database.

void CreateCollections() {
	//assume we would load this from a database or
	//some other data source
	teams = new List();

	HockeyTeam leafs = new HockeyTeam(”Maple Leafs”);
	leafs.Players.Add(new HockeyPlayer(”Mats”, “Sundin”));
	leafs.Players.Add(new HockeyPlayer(”Darcy”, “Tucker”));
	leafs.Players.Add(new HockeyPlayer(”Bryan”, “McCabe”));

	HockeyTeam senators = new HockeyTeam(”Senators”);
	senators.Players.Add(new HockeyPlayer(”Daniel”, “Alfredsson”));
	senators.Players.Add(new HockeyPlayer(”Jason”, “Spezza”));
	senators.Players.Add(new HockeyPlayer(”Wade”, “Redden”));

	HockeyTeam penguins = new HockeyTeam(”Penguins”);
	penguins.Players.Add(new HockeyPlayer(”Sidney”, “Crosby”));
	penguins.Players.Add(new HockeyPlayer(”Marian”, “Hossa”));
	penguins.Players.Add(new HockeyPlayer(”Petr”, “Sykora”));

	teams.Add(leafs);
	teams.Add(senators);
	teams.Add(penguins);
}

Now being Canadian I love hockey but for some reason I like the Maple Leafs despite their futile efforts, it seems, year after year. There is some significance to the teams I chose for this example.

Firstly, Toronto is my favorite team so that’s a given. I enjoy nothing more than seeing Toronto spank the Sens until they cry, except maybe Toronto destroying Montreal. My hate for Montreal would not let me include them in this demo.

Finally, the Penguins Sidney Crosby holds a warm spot in my heart since he is from Cole Harbour, Nova Scotia, just over an hour from where I live.

Bringing it home

Next we need to do some work when the TeamRepeater binds an item. This includes identifying the current item being bound and casting it to our HockeyTeam class, locating the PlayerRepeater within the TeamRepeater, and then binding, to the PlayerRepeater, the players from the current team being bound. Here is the code.

protected void OnTeamRepeaterItemDataBound(object sender, RepeaterItemEventArgs e) {
	RepeaterItem item = e.Item;
	HockeyTeam currentTeam = (HockeyTeam) item.DataItem;
	Repeater PlayerRepeater = (Repeater) item.FindControl("PlayerRepeater");
	PlayerRepeater.DataSource = currentTeam.Players;
	PlayerRepeater.DataBind();
}

So now with everything in place we can look at our Page_Load method.

protected void Page_Load(object sender, EventArgs e) {
	CreateCollections();
	TeamRepeater.DataSource = teams;
	TeamRepeater.DataBind();
}

Again nothing special, just create the collections and bind to the data source.

Conclusion

Well if you stuck around until this point; thanks for enduring my long winded walkthrough. When you fire this up you should see each team listed with a nice bulleted list of players underneath them.

Hopefully this will help someone in some way if for nothing more than pure entertainment and reminiscing about the days when you weren’t a demi-coder and had to worry about menial tasks like this. Cheers!

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Welcome from DotNetKicks

ASP.Net No Comments »

kick it on DotNetKicks.com

I just wanted to say a hello to the users coming over from dot net kicks. It is always good to talk with fellow .Net coders.

This is the first time I have made it to the front page (original post) and wanted to mention a thank you to dot net kicks for the great content that it pumps out. I always find good stuff each day that helps me become a better developer.

I hope that this is just the first of many articles that I can contribute to a great community. If you like this blog please consider signing up for the RSS feed.

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Adobe Responds To Silverlight

News, Silverlight 18 Comments »

kick it on DotNetKicks.com

Outside of the .Net community it is hard to find someone that has anything positive to say about Silverlight. Whether it is becuase they are misinformed, hate MS, or they have formed this opinion after objective research of the technology, the fact remains Silverlight isn’t getting much respect and it has a huge mountain to climb in terms of an install base.

On the other side of the coin Flash has the upper hand. They have a staggering install base and have already been accepted by developers as an industry standard for developing animations.

As we all know this doesn’t ensure Adobe will rule this market forever and they are making some moves in order to preserve their market share and try and steal Silverlights thunder.

Part of Silverlights perceived, depending on who you talk to, advantage is the blending of client side and server side in the application as well as reusable controls, a concept us .Net coders already enjoy in our everyday lives.

The move that Adobe is making is to include the ability in include C, C++, Java, Python, and Ruby code into Flash that will get compiled into ActionScript. This is a smart move by Adobe which will strengthen Flash and remove the major reason a developer might decide to switch to Silverlight.

I have heard many scoff at Silverlight but when a major player like Adobe stands up and takes a step like this it is clear that they are not naive to the potential of Silverlight.

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Not #1 yet, but climbing

News 6 Comments »

I may be the only one who cares about this post but I am going to make it anyway. To me this is a milestone worthy of recognition, from a novice SEO’s perspective, such as myself.

I have always read SEO blogs and about the various techniques that should send you to the top of Google. For me reading and actually achieving seemed miles apart, at least until today.

As of the time of this post a Google search for ‘web development blog’ (without quotes) will put this blog at #5. No it is not #1 but for me it is a big deal and proof that my hard SEO work is paying off. With this new found encouagement in hand I plan to set off on more keyword SEO adventures to help this blog reach to the far corners of the Blogosphere.

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Some things I enjoy at work

Personal No Comments »

There are some things that I get to enjoy each day at work that I would otherwise not likely be able to afford if I were working as a freelancer. There are some things that I would have to get just to be able to work from day to day like Visual Studio and other development tools.

The company I work for does work for clients across the continent and in some cases don’t ever speak to the customer face to face. A recent case for this was when we deployed a remote server for a customer to host some of their various applications for the multiple locations. This solution allowed them to connect remotely from anywhere and access their server.

The main tool that allowed us interact with this customer without ever getting on a plane and flying the 1000 miles was video conferencing. Now video conferencing systems have come a long way in the last few years. They have improved greatly from the days when they were little better than speaker phone and a web cam quality sound and video.

These modern systems can do many things like split the screen into many sessions if you have multiple people to connect remotely.

This is one of many things I benefit from at my job that lets me interact with customers that I wouldn’t otherwise have access to.

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

I am suffering from too much GUI

Personal, Software Design No Comments »

I was thinking about some of my skills sets today and this lead me to a realization.

I consider myself to be good with relational databases. I may not be an expert guru, but I have designed and implemented some pretty complex systems, very well IMO.

The realization was that I rely to much on GUI interfaces. Yes, they are great and help get things done faster but in the instant the GUI was not available would I be able to function? True, I could always jump onto Google but my productivity would be greatly reduced because I would have to look up a lot of things.

I also realized that I tended to be more disciplined when a GUI was available. For example, when working with MSSQL I used plenty of Sotred Procedures and was extremely careful to make sure all contraints and relationships were in place. However, when using MySQL, usually phpMyAdmin, I rarely used an SP or setup relationships.

So why is that? Because for MSSQL there are nice GUI interfaces to let me quickly and easily add all those good things but in phpMyAdmin there is noway to add them except through queries.

Conclusion, I am lazy. I am working on this but it is true. This is by no means a good excuse to ignore good practices.

So here’s to using a little less GUI and brushing up on some advanced SQL techniques in the near future.

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Build your own CAB series

Software Design No Comments »

Jeremy Miller has been writing a wonderful series on building your CAB/exploring design patterns. I highly recommend you read the series.

Click here for the first article in the series.

Click here for a list of articles in the series.

When last we left our hero, D’Artagnan was chasing the evil Lady de Winter across the breadth of France trying to intercept her on her dastardly mission when he found himself beset by disparate responsibilities within the tight confines of a single autonomous view with no room for sword play. D’Artagnan, being a perspicacious young man, quickly sees a way to separate the numerous concerns he’s facing by opening his attack with…

:D

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Add Ebay auctions to your website in 5 minutes

PHP, Projects 5 Comments »

Update: I mentioned that I would cover including your Ebay affiliate link in the feed in a later article, however, had I paid closer attention I would have seen that the affiliate link can easily be included when you create the feed.

Under advanced search go down to “Affiliate Tracking Information” and click show. Choose Commision Junction as the provider and enter your PID. That’s it know the feed links will include your affiliate id and you can get commissions on traffic you refer.

Have you ever wanted to add Ebay auctions to your website? Well, I’ll show you in a few easy steps how to do just that.

Getting started

Before we get into the real meat of this post we need to put some things in place. You will need the class file, which is below, and the url to the RSS feed you want to use. With these two things in place you will be able to add your feed in just four lines of code.

The RSS feed

Whenever you do a search on Ebay you are provided with an rss feed for that search. You will see the small orange RSS image after the search results in the Tools section. Here is an example of a seach RSS feed.

The class file

Save this file as EbayRssFeed.class.php and place it in the same directory as the php file you want to include the feed on.

<?php
	class EbayRssFeed {
		private $url;
		private $feed;

		public function __construct($url) {
			$this->url = $url;
			$this->feed = simplexml_load_file($url);
		}

		private function getItems() {
			return $this->feed->channel->item;
		}

		public function writeFeed() {
			$items = $this->getItems();
			echo "\n\n<!--EBAY RSS FEED-->\n";
			for($i=0;$i<count($items);$i++) {
				echo "<div class=\"EbayRssFeed\">\n\t<div class=\"EbayRssTitle\">" .
					"<a href=\"" . $items[$i]->link . "\">" . $items[$i]->title . "</a></div>" .
					"\n\t<div class=\"EbayRssDescription\">" . $items[$i]->description . "</div>\n</div>\n\n";
			}
			echo "<!--/EBAY RSS FEED-->\n\n";
		}
	}
?>

Adding the feed

Now that we have that out of the way let’s add that RSS feed.

First we will create the class instance.

//include the class file
require_once("EbayRssFeed.class.php");

//the url to our RSS feed
$file = 'http://rss.api.ebay.com/ws/rssapi?FeedName=SearchResults&siteId=0&language=en-US&output=RSS20&catref=C5&sacqy=&sacur=0&sorefinesearch=1&from=R14&fbd=1&saobfmts=exsif&_trksid=m37&dfsp=2&sacqyop=ge&saslc=0&floc=1&sabfmts=0&saprclo=250&saprchi=&saaff=afdefault&sabdlo=2&ftrv=1&sabdhi=&ftrt=1&fcl=3&frpp=50&afcj=&nojspr=y&satitle=vacation&afmp=&sacat=29578&saslop=1&fss=0';

//create the instance
$ebay = new EbayRssFeed($file);

Now, that wasn’t too hard was it?

Place the following code in your php page where you would like the feed to show.

<?= $ebay->writeFeed() ?>

Finishing up

Your done! That really is all there is to it. I plan on covering this in a later post and integrating your Ebay affiliate id so you can earn some cash from the users that are referred by your feed.

You can check out a demo that I made. Enjoy!

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Creating an UpdateProgress programmatically

ASP.Net 3 Comments »

kick it on DotNetKicks.com

I’d like to point out that this took me a while to figure out and in the end it was DisturbedBuddha over at the ASP.Net forums that gave me the solution. I thought I would share this with you as I know I would never have been able to imagine how to makes this work on my own.

I used a sample program and constructed it in 2 ways. First I created it the “normal” way by placing all the controls in the .ASPX file. Second I created the same program all in the CodeBehind. I needed to do this becuase I planned to wrap some AJAX functionality into a Composite Control.

I will attach the project at the bottom of this post.

The simple program contained a Label that read “init” on first load, a button that ran a javascript function to postback an event argument that would trigger the Label to be updated to “callback” and display a nice Ajaxy loading animation.

Was able to get everything to work great except I couldn’t get the UdateProgress’s ProgressTemplate created. Below I will post the VB and C# code of how to do this.

The code

VB

Partial Class Default9
    Inherits System.Web.UI.Page

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        ' !!!THIS MUST BE DONE IN THE PRERENDER EVENT!!!
        ' Create the label.
        Dim lab As New Label
        lab.ID = "Label1"
        lab.Text = "Please wait..."

        ' Create the UpdateProgress.
        Dim uprog As New UpdateProgress
        uprog.AssociatedUpdatePanelID = UpdatePanel1.ClientID
        uprog.ID = "UpdateProgress1"

        ' Create the ProgressTemplate based on a class the implements ITemplate.
        Dim value As New MyTemplate
        uprog.ProgressTemplate = value

        ' Add the Label to the UpdateProgress and the UpdateProgress to the form.
        uprog.Controls.Add(lab)
        Form.Controls.Add(uprog)
    End Sub

End Class

' THIS GOES IN YOUR PAGES CODE BEHIND ALSO!
Public Class MyTemplate : Implements ITemplate

    Public Sub InstantiateIn(ByVal container As Control) Implements Web.UI.ITemplate.InstantiateIn
        ' This is empty.
    End Sub

End Class

C#

partial class Default9 : System.Web.UI.Page
{
	protected void Page_PreRender(object sender, System.EventArgs e)
	{
	 // !!!THIS MUST BE DONE IN THE PRERENDER EVENT!!!
	 // Create the label.
	 Label lab = new Label();
	 lab.ID = "Label1";
	 lab.Text = "Please wait...";

	 // Create the UpdateProgress.
	 UpdateProgress uprog = new UpdateProgress();
	 uprog.AssociatedUpdatePanelID = UpdatePanel1.ClientID;
	 uprog.ID = "UpdateProgress1";

	 // Create the ProgressTemplate based on a class the implements ITemplate.
	 MyTemplate value = new MyTemplate();
	 uprog.ProgressTemplate = value;

	 // Add the Label to the UpdateProgress and the UpdateProgress to the form.
	 uprog.Controls.Add(lab);
	 Form.Controls.Add(uprog);
	}
}

// THIS GOES IN YOUR PAGES CODE BEHIND ALSO!
public class MyTemplate : ITemplate
{
	public void InstantiateIn(Control container)
	{
	 // This is empty.
	}
}

I hope this helps someone else out. DisturbedBuddha says he is planning to post on his blog explaining the ins and outs of why this appraoch is necessary.

Download

This project was created using Visual Studio 2008 with the .Net Framework 2.0.

Get project source

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

I still don’t need another credit card!

Personal No Comments »

After posting about telemarketers and credit cards yesterday I had a few more thoughts that I would like to share with you.

I never fails to amaze me how randomly telemarketers seem to select their victims..er…potential clients. I mean, as I mentioned I live in rural Atlantic Canada, there are very few places here, that I am aware of, that except American Express (pretty much anything other than Visa or MasterCard) but a lot of the credit card calls I get are offering me an American Express card.

Telemarketer: We are pleased to offer you a no fee, $50,000 limit, American Express Centurion card, I just need you to confirm some information….[insert some sort of dialog that I don’t hear as I try to stop the rambling fool and tell them I don’t want it]…

But seriously though do these companies not do any sort of research on the regions they are soliciting? Why would I want a card that I probably can’t use at most places I shop? Why would they want to waste their time and employee salary on soliciting a region that has no need of what they are tryign to sell? If I ever figure out that answer I’ll be sure to let you know.

In the mean time I keep screening my calls hoping to avoid repeat that same conversation again.

Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.
WP Theme & Icons by N.Design Studio
Entries RSS Login