Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

Sunday, October 12, 2008

Code Nuggets: A Side-effect of Using DropDownList AppendDataBoundItems With DataBound Items

Picture this: You have a webform with two DropDownLists, both of them are databound to some data you get from a database. Now the first DropDownList's selection determines the contents of the second dropdown. So you simply do a AutoPostBack = true for the first dropdown and populate the second dropdown in the handler function. Right?

But wait. What if you are required to put in a static item in the dropdown? Something like "-- Please Select --" as the first item in the list to force the user to make a conscious choice. Hmmm, so you look around and find the nice little property named AppendDataBoundItems that will take care of that. All you have to do is declare the first (static) item in the Items collection in the designer (or put a <asp:ListItem> tag inside your <asp:DropDownList> tags) and set AppendDataBoundItems to true. This nice little property tells the DropDownList to add the databound items after the statically declared items, so you can have your happy little "-- Please Select --" in your dropdown.

The Side-effect:

The side-effect becomes evident when you play around with your two dropdowns. Its immediately clear that something is not quite right. The AppendDataBoundItems property forces your dropdown's items from the previous postback to be treated as static objects on this display. Sort of where you get an ever-growing second dropdown with a hangover from the postback, which is clearly not what you wanted in the first place!

The Nugget:

So the quick solution is to use a loop to remove items selectively from your dropdown. Remember you still want to retain your first item, so that's why you use a loop. And a while loop at that.

while (DropDownList1.Items.Count != 1)
{
    DropDownList1.Items.Remove(DropDownList1.Items[1]);
}

There. You won't have a problem with your static-dynamic dropdowns anymore! You can even extend it to other purposes, if you have several static items that you want to preserve, or if you want to preserve static items that are of a particular value. The possibilities are endless, and the pain in your back is gone.

Other Possible Solutions Others Propose:

Some people think that doing a DropDownList1.Items.Clear() would do the trick, but it doesn't. Remember, you want to retain your first object. Or if you want to add your first (static!) object manually again then perhaps you can do that.

Yet others propose a rather swashbuckling DropDownList1.EnableViewState = false, do this only at your own risk and if you are sure that your user would never have to land on this page again during the current flow of your application (of course for which you cannot be sure, what if there is a network timeout?).

A Note:

Perhaps you'd want to use a for loop in place of that while loop, trying to do a quick

for (int i = 0; i < DropDownList1.Items.Count; i++)
{
    DropDownList1.Items.RemoveAt(i);
}

but believe me, it wouldn't work. Why? Because the DropDownList shrinks as you remove items from it, so your loop is bound to fail at some point, terminating earlier than it should. And of course I don't have to remind anyone that you cannot remove items from a collection while using an Iterator.

So that's it, I think the nugget had pretty much sauce alongside it!

(You can get a low-down on AppendDataBoundItems on ScottGu's blog or Andrew Rea's blog)

Sunday, April 20, 2008

The Apple Software Update

With all the talk about Apple apparently forcing Safari on unsuspecting users through the Apple Software Update, I wanted to get a piece of it too. Apple Software Update is usually installed if any software from Apple is installed on your computer, like iTunes or QuickTime. I had iTunes installed on my system as I found it quite convenient to use my iPod with, and since then it (iTunes) has become my de facto audio player.

So I fired up Apple Software Update, and voila! There was no Safari in the list, let alone being checked by default. There was an update to Apple Software Update though, and an update to Apple QuickTime + iTunes. So I randomly updated Apple Software Update to the latest version, and when the update completed, there I had little Safari sitting innocently on my list checked already :)

Moral of the story: Update your Software Update before quipping on Apple.

Epilogue: I might give Safari a spin, because I had played a bit with it when the public beta came out last year. But I am not terribly impressed, not much to ditch my existing Firefox 3 Beta 5, which itself is light years fast of Firefox 2.

Monday, March 31, 2008

PHP: Getting your user's IP Address

It's easy, just use $SERVER['REMOTE_ADDR']. Echoing the user's IP address would look something like this:

echo "IP Address: " . $SERVER['REMOTE_ADDR'];
But that works only in PHP versions greater than 4.1.0. If you're still using earlier versions, use HTTP_SERVER_VARS, and for heavens' sake, upgrade.

Source: PHP: Predefined Variables - Manual (This page should be on the thumbs of all PHP developers)

Tuesday, August 29, 2006

Blogger Babes

It turns out Blogger beta isn't a wasted effort at all! For one thing, you get the "dog" (looks to me so) replacing the B of the Blogger. I realized only today that using the beta is a privilege accorded only to a few lucky ones (I didnt notice because privileges are so natural for me *snicker*).

As I said somewhere, it is good for the non-tech people, as it uses those AJAX enabled snippets to arrange layouts according to the user's taste. The general population (who doesn't even have the desire) wouldn't now have to get their hands dirty with HTML and CSS. Adding custom code for statistics is just drag-and-drop, keeping the flow intuitive.

Close to hell for us techies, 'cause you cannot live if you cannot customize; and that's just what Blogger doesn't let us do at the moment.

The better thing is that, with the beta release, Blogger marks the shift to the dynamic web. Wonder why it has taken them so long, all the rest of the services are long established on it.

By dynamism of the web, I mean that you no longer have to publish your blog every time you make a change in the template. Old blogger used to publish pages of your blog to its server, and serve the appropriate pages whenever a request arrived. With the beta, the pages would be created on the fly, no more publishing.

All the bitching was due to the fact that I had recently delved into the Blogger codebase, and had come up with really interesting tricks like customizing the individual pages, recent comment box on the sidebar, intuitive layouts; and then *poof*... Blogger beta strips me of any right to modify my template.

These snippets are available if any of the old Blogger people (or the beta users who haven't switched to layouts) want them for their blogs.

Sunday, August 27, 2006

The Craze Beta

What is with everyone coming up with the beta editions of their offerings these days? Starting with Gmail Beta, we get Windows Live Mail Beta, Yahoo! Mail Beta, Yahoo! Photos Beta, Flickr Beta, and now, sweet Blogger goes beta too!

For many services, going beta just means getting AJAX-ified, with little or no improvement in features (Windows Live Mail leads the contest), only getting a face-lift and incorporating oh-those-cool-functions on the page that have nothing whatsoever to do with cutting the round trip time...!

With a sense of loyalty to the technology and the tech community (not to mention the need to be the first in trying things out - izzat ka maamla), I have officially switched to the new Blogger Beta. Switched - 'cause, ummm, beta could be exciting; officially - 'cause Blogger Help says you cannot opt out of the Beta!

So what does this beta has to offer over the old version? For one, the "privileged ones" now have a separate, red carpeted entrance at http://beta.blogger.com. Ordinary mortals should stick to their filthy swamps and keep using the lowly Blogger home page to log in.

The Blogger people have added support for tags - or "labels" as they call them. Der ayed durust ayed is the only thing that comes to mind.

And there is this supposedly cool Layout feature, that help you manage the "template" of your blog. Beware, the "template" word is hushed now, if you're cool, you'll have a layout.

So the layouts help users "drag and drop" widgets, or little snippets (previous posts, profile, description etc) on the page. Intuitive it is, but couldn't achieve its full potential until the "Edit HTML" option starts working. Gives us "power users" that creepy feeling of helplessness!

That means my little blog page has some AJAX elements in it. How I have been dying to have a little Ajax, that would keep my dishes clean... Who said God doesn't listen?!

Oh, and by the way, you'll have to comment by choosing the "Other" or "Anonymous" option on the comments page, your logged in nick wouldn't work here. Of course, what did you think? Its Beta!

Besides that, all the functionality is unchanged. They have tried to spruce up the Dashboard a little, with cramming the various blog-specific options, and the Blogger Buzz posts. Heck, they even forgot to fix the bug that occurs in the Rich Text Editor that it doesnt convert line breaks to hard line breaks :\ So it'd be better to stick to posting via e-mail!

Buss ooper say make-up kiya hai, under the hood its all the same!

Returning to the Craze Beta, I forgot to tell you: Flickr has gone a step ahead, its now Flickr Gamma!

And that gives an excuse for procrastinating office work too. Whenever somebody wants to take you to task, just claim that you've gone beta!

Wednesday, August 09, 2006

Sending mail with System.Web.Mail (.Net 1.1)

If you thought that it was a serious shortcoming that .Net framework 1.1 wasn't able to send email through SMTP servers that used authentication, you are in grave ignorance. On the surface of it, yes, you cannot send an email with the standard System.Web.Mail.MailMessage class; but you can of course play tricks on the Exchange server (yeah, that's what I get out of it that this things works only on an Exchange server) to make it authenticate you.

There is a namespace called http://schemas.microsoft.com/cdo/configuration that does those funny (and highly interesting) tricks. First we would check how to use a simple SMTP server (no authentication), and then we will use authentication to send a message.

//using System.Web;
//using System.Web.Mail;

//The simple SMTP Server
MailMessage message = new MailMessage();
message.From = "src@someone.com";
message.To = "dest@someother.com";
message.BodyFormat = MailFormat.Html;
message.Subject = "This is a spooky mail!";
message.Body = "Heheh, just kidding!";

SmtpMail.SmtpServer = "your.server.address"
SmtpMail.Send(message);

Now lets check out a server that uses authentication. Microsoft provides the CDOSYS object to achieve just that. You wouldn't think they were so dumb that they didnt incorporate some lousy authentication mechanism! Add the following lines before the SmtpMail lines.

message.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpserver"
] = "your.server.address";
message.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
message.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
message.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;

//Most of the times the @domain is necessary with the username
message.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "username@domain.com";
message.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "urpassword";

//If only the server uses SSL, in this case, the smtpserverport field would be different too
message.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = true;


And that would do just fine. There you go, I just saved your time and money!

[P.S. To those whom these lines look like Greek, I must say that this post appears as a record!]