ReadOnly and EnableViewState don’t play
nice

ASP.Net No Comments »

I ran into an interesting situation today. From what I read it an old issue as well. In ASP.Net 2.0 if you set EnableViewState equal to false and assign a text box as read only the value will be lost on post back.

Rick Strahl posted a nice article on this back in late 2005 which helped me get around this issue.

2005? What? Okay I have to admit that until today I have not been developing my web applications with view state turned completely off. I have turn individual controls on and off as performance required but view state has never been a real issue for me. Today I decided to bite the bullet and just get used to having view state off and it took less than an hour to run into this so here is how to get around it. Yeah I know you probably already know but on the off chance you don’t…then here it is.

Just place the following code in the Page_Load method.

TextBox1.Text = Request[TextBox1.UniqueID];
Did you like this post? Be sure to grab my RSS feed so you don't miss out on more great articles.

Friday roundup for April 11, 2008

ASP.Net, News No Comments »

Here is what I liked this week.

Microsoft Sets Three Week Deadline for Yahoo! In Public Letter
In a letter sent today, Microsoft writes to Yahoo’s board of directors to tell them that they would like to ‘negotiate a definitive agreement on a combination of our companies.’ Their message is a combination of friend and foe: ‘If we have not concluded an agreement within the next three weeks, we will be compelled to take our case directly to your shareholders.’

How to Impress at Your Next Interview
I have had the opportunity to interview a lot of prospective developers. In that time I have come to understand more clearly what it is that impresses me most. And it might not be what you expect.

Google Takes Down HuddleChat After Complaints
The App Engine team was looking for some sample apps to help kick the tires on their new system, so we invited Googlers to build some as side projects. A couple of our colleagues here built HuddleChat in their spare time because they wanted to share work within their team more easily and thought persistent web chat would do the trick. We’ve heard some complaints from the developer community, though, so rather than divert attention from Google App Engine itself, we thought it better to just take HuddleChat down.”

Yahoo’s Big Day of Fun
It’s been a busy few days for Yahoo. With scorned love letters being passed back and forth with Microsoft, to adding video to Flickr, buying a Web analytics company and now testing out Google ads, you have to give Yahoo credit. We haven’t seen this much excitement coming out of the number two engine in quite some time.

How Much Is Our Blog Worth?
If we’d go by these rules, we wouldn’t sell our blog for anything less then: $344,236! Shocking amount isn’t it? And we haven’t even calculated the value of the brand you’d be selling. The “status” and numerous new networking opportunities that would come knocking when you buy an established blog.

The War Against Blog Commentors Who Use Keywords as Names
A couple months ago, I followed an interesting discussion at Remarkablogger related to a new comment policy that Michael Martine posted for his blog. It seems that Michael had become frustrated with the increasing number of comments on his blog that appeared to be more interested in plugging their websites keywords than adding to the dialogue. After some very interesting and thoughtful comments from his readers on the new policy change, Michael posted a slightly modified policy.

The empty try block mystery
I had used .NET Mass Downloader tool to download .NET 2.0 Framework sourcecode some time ago. While reading Timer.cs (System.Windows.Forms.Timer) and a couple of other classes I noticed something interesting.

Does the following piece of code look odd to you? Notice the empty “try” block and all processing being done in the “finally” block.

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

Friday roundup for April 4, 2008

ASP.Net, Browsers, JavaScript/Ajax, SEO/Marketing, XHTML/CSS No Comments »

Here are some interesting stories from this week.

IE 8 strict mode doesn’t allow for CSS opacity?
So the fact that this has been labeled as by design suggests that IE8 will be the only browser produced in the last 10 or so years that will not support opacity in its strictest mode. Thats rediculous.

Google Will Sell Performics, SEOs Exhale
Exciting news from The Official Google blog today that reveals Google will stop scaring SEOs everywhere and will sell off Performics, the search marketing company that they accidentally acquired when they bought DoubleClick last year. To avoid the conflict of interest that comes when you’re a search engine selling search engine optimization services, Google will split Performics into two companies – an affiliate marketing company and a search marketing company – and then sell the search marketing half.

Webforms is dead. Long live MVC!
Scott Hanselman’s fourth screencast *confirms* that the interfaces and abstractions made as part of the MVC (HttpContextBase, IHttpRequest, IHttpResponse, etc.) will not be put into the existing Webforms model. That means that once MVC is released, the old HttpContext object in WebForms will *not* inherit from HttpContextBase, nor will the WebForms versions of HttpRequest and HttpResponse objects implement the interfaces.

But I’m not moving my mouse!
The IE team reacted correctly: the bug has been solved in IE8b1. When the mouse does not move any more the mousemove event stops firing, as it should.

However, this same bug was recently introduced in Safari (Windows) and Opera!

Safari 3.0 and Opera 9.26 support mousemove correctly, but Safari 3.1 and Opera 9.5b have copied the IE bug.

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

SqlDateTime.TryParse, almost

ASP.Net, SQL 4 Comments »

kick it on DotNetKicks.com

I talked about an issue I ran into between DateTime.MinValue and SqlDateTime.MinValue in a previous post. One other point I noticed while researching the topic was that, unlike almost all other types, SqlDateTime doesn’t have a TryParse method.

I really like the TryParse method because it helps me write code that is more terse and clean. I can easily use the TryParse methed as the condition for an if statement to handle the outcome without have to resort to ugly try catch blocks all over the place.

On Ian’s suggestion in the comments to my previous article I decided to take a stab at writing an extension method to implement this functionality. Now I said almost in the post title because I couldn’t get the TryParse method attached to the SqlDateTime native class. Now this could be due to this being my first attempt at an extension method so if anyone has any advice or suggestions on making this solution better feel free to leave them in the comments and I’ll update the code.

The solution

As I said I couldn’t get the method attached to the native type so this is the next best thing. I have declared a XSqlDateTime type that contains the TryParse method.

public static class XSqlDateTime {
	public static bool TryParse(string str, out SqlDateTime output) {
		try {
			output = SqlDateTime.Parse(str);
			return true;
		}
		catch {
			output = SqlDateTime.MinValue;
			return false;
		}
	}
}

This is easily used like so.

SqlDateTime date;
XSqlDateTime.TryParse("1/1/1953 12:00 AM", out date);

Just like all other implementations of TryParse on other types, if this method returns false it will assign the default type value to the output variable. In this case it is SqlDateTime.MinValue.

Hope this is useful to someone. I know it is for me. Cheers.

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

Friday roundup for March 28, 2008

ASP.Net, Browsers, JavaScript/Ajax, News 1 Comment »

Here is what I found interesting this week.

Key events and Safari 3.1
There has been a change in Safari 3.1 for how keypress events are handled. John Resig interviewed Yehuda Katz to get the skinny and understand why this was done.

eBay Discriminates Against Ebook Sellers, Squashes All Digital Downloads
In what will go down in Internet history as probably one of the lamest decisions ever in e-commerce, running second only to the firing of AOL CEO Jon Miller in 2006, eBay announced yesterday it will no longer allow any digitally downloadable product to be sold via an auction.

Where’s my .NET 3.5 (on IIS), Dude?
The not so obvious ‘problem’ is that if you fire up a machine that has .NET 3.5 installed, you might be surprised to find that the IIS service panel’s ASP.NET does not show an option to select the .NET Runtime of 3.5.

Opera and WebKit pass Acid3 test
The latest builds from Opera and WebKit are scoring a perfect 100/100 on the Acid3 test. Wow!

Where is Firefox on Acid 3? Here.
Some people have been surprised to not hear much from Mozilla around Acid 3. WebKit and Opera are duking it out, but what about Firefox?

Mike Shaver of Mozilla has posted on his views that Acid 3 is a missed opportunity and is pretty damning of the whole thing.

Using the YouTube API via Ext
With the YouTube API recently released, there’s bound to be lots of cool controls coming out soon. Thorsten Suckow-Homberg spent a weekend hacking up a Ext-based user extension that leverages YouTube’s chromeless API to build The Ext.ux.YoutubePlayer.

20 Types of Pages that Every Blogger Should Consider
When you use WordPress you’re given the choice when publishing between doing it as a ‘post’ or as a ‘page‘. Posts go up on your blog while ‘pages’ are static pages that you can publish without it having to go up on your blog.

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

C# DateTime.MinValue is not the same as SqlDateTime.MinValue

ASP.Net, SQL 12 Comments »

kick it on DotNetKicks.com

Working with non-nullable types in C# can be a bit of a pain. For instance when I have a date as a string and need to parse it into a DateTime what should the value be if the parse fails? I can’t use null because DateTime is not a nullable type.

This is exactly the dilema I encountered today. No worries, I’ll use DateTime.MinValue that way it is constant and I don’t have to worry about being consistent if I had chosen an arbitrary value of my own.

Well as it turns out I did have some worries. Sql Server 2000’s minimum DateTime value is not the same, in fact it is quite different. This kept causing errors.

For your reference here are some values you should take note of.

DateTime myDate = DateTime.MinValue; //=> 1/1/0001
SqlDateTime mySqlDate = SqlDateTime.MinValue; //=> 1/1/1753
//also note that SQL Server's smalldatetime min value is 1/1/1900

So my problem was easily averted, after a quick Google search. I just had to use SqlDateTime.MinValue instead of DateTime.MinValue.

Cheers

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

Friday roundup - March 8, 2008

ASP.Net, Browsers, JavaScript/Ajax, Silverlight No Comments »

I have decided to start doing a Friday round up of all the interesting articles I find during the week. Here are some stories I found interesting for the week of March 3 to March 8. Enjoy!

Internet Explorer 8 will render in Standards Mode by default
The IE team has announced that it will render HTML markup in “the most standards compliant way it can.” It is nice to see that MS has decided to actually listen to what web developers want, in regards to IE, for a change.

The Top 5 Recommendations For Monetizing Your Blog
The readers over at ProBlogger have given their top recommendations on how to make some money with your blog.

Acid 3 released, Webkit praised
Jon Tan ran a few tests and posted the results. Hixie commented on his blog about the release, and praised WebKit on how they have been closing a large number of bugs

Silverlight to run on Symbian phones
Microsoft is working with Nokia to get Silverlight running on Symbian mobile phones. Would this help influence your decision to use Silverlight for UI over other technologies?

MVC Framework Preview 2 released, Jeff Palermo disappointed
Jeff gives a good overview, along with his opinion, of the changes that have been made in preview 2.

Internet Explorer 8 beta 1 is now available for download.
Take the first release of IE8 for a test drive. Will it deliver this time?

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

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.

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.
WP Theme & Icons by N.Design Studio
Entries RSS Login