Saturday, December 30, 2006

Blogger Tag Cloud

One good thing about the blogger beta is that it supports Labels a.k.a. Categories/Tags (at last!), so one can categorize his posts. Blogger also allows showing the list of labels from your blogs and allows user to filter posts based on the labels. The problem is that the layout of labels is not customizable or is it? Actually, with some (not so elegant) lines of javascript and css, we can make these labels display as a tag-cloud pretty much what other blog platforms support. Here's what we need to do:
Preamble: Edit 2: Edit the template to give the ul tag (which displays the labels) an Id (for e.g. labelUl), this can be done by clicking on "Expand Widget Template" checkbox and scrolling to the code in template which has a div with ID: "Label1". The UL would be contained within this. Enclose the (<data:label.count/>) within a span and save the template.

1) Firstly we'll make the list appear horizontally instead of vertically, that way we can free up some screen real-estate. So we add the respective styles for the ul and li elements within the style tag under head:
#Label1 {display:none;word-wrap:break-word;}
#labelUL {list-style:none;margin:0px;padding:0px;}
#labelUL li{padding:0px 3px 0px 0px;margin:0px;display:inline;}
Add the noscript tag to display the label div, in case user has js turned off
<noscript>
<style type='text/css'>
#Label1 {display:block;}
</style&g;
</noscript>
So at least we've got the list to display horizontally instead of vertically.
2) Now we need to change the font sizes of the labels based on their weights (i.e. the larger the number of posts tagged to a label, the bigger the text size for that).
For that we hook our DOM walk-through javascript to window.load, this is what I've done:


<script type='text/javascript'>
window.onload = function(){
var labelDiv = document.getElementById("Label1");
var ul= document.getElementById("labelUL");

try{
if(ul.childNodes.length>=0)
{
var weights = new Array();
//should be a div
var li,text, re;
var textNode;

var lis = ul.getElementsByTagName("li");
for(var i=0;i<lis.length;i++)
{
li = lis[i];
textNode = li.getElementsByTagName('span')[0];
text = textNode.innerHTML;
re = new RegExp("[^0-9]", "g");
text = text.replace(re,"");
li.title = text + " posts";
weights.push(new category(text,li));
textNode.innerHTML = "";
}
weights.sort(sortNumber);
var mean = Math.floor((parseInt(weights[0].weight)+parseInt(weights[weights.length-1].weight))/2);
//lets go
var weightFactor = 1;
for(i=0;i<weights.length;i++)
{
weightFactor = parseInt(weights[i].weight)*100/mean;
if(weightFactor<80)
weightFactor = 80 + weightFactor*.1;
else if(weightFactor>250)
weightFactor = 250;

weights[i].li.style.fontSize = weightFactor + "%";
}
weights = null;
labelDiv.style.display = "block";
};
}
catch(e){
if(labelDiv!=null)
labelDiv.style.display = "block";
}
}

function category(weightParam,e)
{
this.li = e;
this.weight = weightParam;

}

function sortNumber(a,b)
{
return a.weight - b.weight;
}
<script>


I don't let any tag to be less than 80% of normal text size, you don't want any label to be illegible due to it's size. The js is simple enough to understand and as I said it isn't the most elegant piece of code that you'd come across but hey it works for me. I tested this out on IE 7 and Fx and I'd guess it should either work or downgrade silently on other browsers, worst case the Labels section would look a little whacko but I promise it wouldn't steal your credit card information or conduct any phishing attacks :-).

Edit:Just figured out that in the template if you click on "Expand Widgets.." checkbox, you can set the Id for the ul element and even perhaps write a javascript inline without having to resort to a onload function. I am too lazy to change the code on my page though (don't fix it if it ain't broke).

Tuesday, December 26, 2006

Zuned!

As I write this, the Zune Software installation is going on in the background and it has failed on me twice! Well, not really its fault, I got disconnected from my wireless connection on both occasions while it was downloading the firmware update (by the way, the error message was not at all handy, it said close all the applications and restart the system!). I don't think doing an update check the first thing during a new install is such a great idea, when people get new stuff they want to try it out as soon as they can and making them wait while a 30 MB something update is getting downloaded is definitely not on. By the way, the Circuit City guy told me that the Zune is selling quite well in these area and at times even outselling the iPod. Anyway, more on the OOBE and the Album-art fixer app that I wrote later.

Tuesday, December 05, 2006

The 6'O Clock Alarm

I generally hate waking up in the morning to an alarm, I believe that using alarms interrupt your sleep and if you're still sleeping during the hour when you should be "supposedly" up; it means that the body and mind needs more rest, as simple as that. I am not against using alarms as a one-off thing or using it to get up cause you have things planned for the day which you love doing, but getting up early in the morning just so that you can get to work early; please no unless you are in love with your job! I've used the alarms in the past quite often but I used it more or less to get things done which I loved doing. The last time I had to resort to alarm unwillingly was when I was in school, I had to get up like 5:30 in the morning to make it to the 7:30 assembly! I just don't understand how we expect from school children, does forcing them to get up so early make them any better? This gently reminds me of a British Airways ad from past which read something like:
It's same everywhere; children go to school (in the morning),
children run back home (after school)!
Unfortunately, these days I have to resort to alarms in the morning (not by choice) but one thing's for sure; the 6'O clock alarm would never ring...or would it?

Last.fm, Pandora or Musicmatch Jukebox Radio

Thanks to the social networking, even sharing music tastes online has these days become a fad; and all of a sudden there've been quite a few services online which provide you recommendations based on your tastes, the most popular of them being Pandora and last.fm. last.fm provides recommendations based on other listeners who share the "same" music taste as you, whereas Pandora uses some "fuzzy" logic to get it's recommendations. Before either of these services were on the scene, I would use MusicMatch Jukebox radio (due to its free CD quality streaming for one hour) and generally search for a particular artist and select "Play this and similar artists", and now after trying both Pandora and last.fm the same way, at least I've found that MusicMatch's recommendations were the best. The way I tried is quite simple; search for the same set of artists (mostly 80s bands like a-ha, Duran Duran, Cyndi Lauper, Belinda Carlisle etc.) on all the three services and see which one plays the songs you like the most and helps you in discovering new music. last.fm came with quite good recommendations but mostly songs that I'd listened to before, so not such great a thing if you're looking at finding new music matching your taste (though it did come with "Pictures of You - Cure", which I bought almost immediately!); Pandora's recommendations were beyond me but MusicMatch would per session at least play one song which I'd fall in love with: be it Afterglow by INXS, Moonlight Shadow by Mike Oldfield, The Sun Ain't Gonna Shine Anymore by Walker Brothers or numerous others. My word of advice: if you're into discovering new music give all three a spin and see which one works the best for you; I'd recommend the Jukebox the most though.
Happy listening!

Saturday, December 02, 2006

Ambitious dream

I was talking with someone over the phone the other day about something that I was kind of reluctant to do, and he finally said to me: "Hey, that was always your dream", after I hung up I could understand why he was kind of annoyed/amazed but then I thought about the statement that he made; was it really my dream? It wasn't, it was an ambition. Well, how are the two things different? I define ambition as something tangible and materialistic, something which our outer self wants to achieve; whereas a dream can be anything from one night of peaceful sleep to being able to fly, and are what our inner self needs. This by no way means that dreams are something so abstract that they cannot be lived on in this material world, all the limits of the body are the limits of your own mind; let your mind go and your body will follow. Unfortunately we drown ourselves so much into our day to day chores and try to please so many people that we stop dreaming altogether. The moment we stop dreaming or stop believing in them is when we stop being in touch with ourselves, we are just reduced to a shadow of what we really are deep inside.

I would rather chase my dreams and give up my ambitions that come in the way than the other way round, this was just one of those cases; and I've no regrets about it.

Legend of a Band

There are singers who compose music that you like, and there are singers that compose songs which you admire and then there are singers that touch your heart and soul with their soulful music, The Moody Blues is one such band, a band whose music simple mesmerizes you. They have never failed me ever since I started listening to them way back in early 90s, their music always seemed to have that profound effect on me which always seemed to re-affirm my self-belief even during my most stressful times when I'd start doubting the sanity of very principles on which I have lived my life all these years. Maybe it's got to do with Justin's haunting voice or the theme of most of their songs (separation) or simply the lyrics; they take you on a journey to a completely different place, a place where you are so much more peace with yourself, where you are just being yourself every time you play one of their song. The place is not somewhere faraway (there's no such thing as far away, every place that you ever want to be at is right there inside your own self) but it's a journey inside your own self, a place where I've always felt safe and at peace with myself. I can still remember how I got hooked on to them, Sumit had borrowed a recorded cassette which had one song from The Moody Blues: I know You're Out There Somewhere; a song which you just can't stop falling in love with. I was too young to really appreciate the meaningful lyrics then (I didn't have to deal with pain of losing someone at age of 12) but still there was something about the song which affected me somewhere deep down inside, there was something about this band which made me feel as if there's beauty around us; we just have to close our eyes, take a deep breath and liberate our souls. Ever since I've listened to almost all of their numbers but somehow I always kind of associate myself with Justin's songs, there is so many things that he says through them and then there are so many things that are left unspoken that you want to immerse yourself in those songs. If you haven't listened to Moody Blues ever; you might want to run to your nearest music store and get their CDs, believe me you won't regret your decision ever.

Tuesday, November 21, 2006

AJAX and noscript

One of the evil of AJAX sites is that if the user has javascript turned off, the site stops functioning all together. Since I use NoScript extension all the time on Firefox, I really hate sites which don't even tell you that javascript needs to be turned on for the site's functionality to work and when it takes just a <noscript> tag to display a message to the user about js bit:
<noscript>
<div>This site requires javascript to be turned on...blah blah blah.</div>
</noscript>

You can get a bit more enterprising with the noscript tag, for instance what if you don't want the user to even access the page w.o. javascript turned on? Well, in that case you can put noscript tag in the head section and do a meta refresh:
<head>
...
<noscript>
<meta equiv="Refresh" content="0; URL=nojs.html"></noscript>
...
</head>


Ok, what if you don't want to redirect the user but hide all the elements on the page except the no js error message? You can achieve that too by using CSS:
Step 1) Add this div within the body where you want the error message to show up in case the js is turned off:
<div class="ns">
Ouch! No JS
</div>
Step 2) Hide the "ns" div by default:
.ns{display:none;}
Step 3) Hide all the elements on the page and display ns div if js is turned off:
<noscript>
<style type="text/css">
* {visibility:hidden;}
.ns {visibility:visible;margin:0px auto;width:60%;display:block}
</style>
</noscript>

Thursday, October 19, 2006

D or E, take your pick

At times we are confronted with choices, and we pick one of them based on which one is more aligned with where we want to go and our priorities. So, which one do you pick between D and E? What are D and E, first of all? They are two things which don't matter to us anyway, but we still have to make a choice, so it's like tossing a coin and taking a pick or coming up with crazy rationale and reasoning so that the choice that we make in the end makes some sense. I think, the most important factor in life is motivation, as long as we are motivated we would always want to grow, we would always want to explore the world around us, we would always want to learn something new, and unfortunately for past some time that's one thing that I've been lacking, maybe D or E were easy enough to choose between but since I just don't have any motivation left I don't care which one I pick.

Friday, October 06, 2006

cut, curl and A Brief History of Time...

Recently I stumbled upon an online version of "A brief History of Time" by Stephen Hawking, I read this book long time back, perhaps too soon for my age. So decided I'll give it another shot, the only issue is I prefer paper books over online versions and even if I have to read an ebook, I generally like reading them in MS Reader (it's got few nice features like annotating, bookmarking, and drawing among others). I know there's a plugin for MS Word which allows converting any word document to MS Reader format, so if only I could get these HTMLs to a doc file, I just have to run that converter. The easiest approach is to open all the htmls in a browser, select all text and paste in a word document but that doesn't appear to be any challenging, so I thought off automating the entire process....


A cursory look on the url naming for this book, showed that files are named from a-n (for some reason n is the first chapter, then every chapter is a-m). So the easiest way to do it w.o. any third party tool was to use curl to save these documents locally.



$curl http://www.physics.metu.edu.tr/~fizikt/html/hawking/[a-n].html -o "hawking_#1.html"

This would fetch all the documents named from a-n and save them locally as hawking_[a-n].html.

Step 1 was quite easy, now the chapters also have images embedded for which we need to extract the image sources and save them locally again. Another look at the source html showed that all images are declared as <img src="..." > so using grep I extracted all the img tags in the html pages:

grep -o '<img src="[a-z0-9A-Z\.]*' hawking_*.html >> img.txt

So I extracted all the img tags and saved them to an output file, different story that the grep command took me nearly 3 hrs! I kept on forgetting to add the -o switch, without which the grep would spit out the entire html content, making me think that my regex was perhaps wrong. Anyway, once we had the grep sorted out, the next issue was to extract just the image names from the img src tags grep found, well that quite easy using the cut command:

cut -d\" -f2 img.txt >>wget.txt

Once we have all the img src path, we just need to use a final wget to fetch them:

wget -i wget.txt -B http://www.physics.metu.edu.tr/~fizikt/html/hawking/

(-B specifies the base url)

So far so good, so we have saved a local copy of the book with the images (different story that perhaps doing it manually would have taken lesser time).

Now we need to merge these htmls and convert them to a word document, here's a slightly tweaked version of macro in OO that I used:

Sub MergeAndSave(baseUrl)
'urls are a-n
dim i
dim ch
dim cUrl
ch = chr(110)
dim cFile
dim docFile
docFile = "/home/sachin/Hawking/hawking.doc"
cFile = baseUrl + ch + ".html"
cUrl = ConvertToURL( cFile )
oDoc = StarDesktop.loadComponentFromURL( cURL, "_blank", 0, Array(MakePropertyValue("FilterName","HTML (StarWriter)") _
, MakePropertyValue("Hidden",False))

cURL = ConvertToURL( docFile )

oDoc.storeToURL( cURL, Array(_
MakePropertyValue( "FilterName", "MS WinWord 6.0" ),)
oDoc.close( True )

Dim oFinalDoc, oCursor,oText
oFinalDoc = StarDesktop.Loadcomponentfromurl(cURL, "_blank", 0, Array())
oText = oFinalDoc.getText
oCursor = oText.createTextCursor()
for i = 97 to 109
ch = chr(i)
cFile = baseUrl + ch + ".html"
cUrl = ConvertToURL( cFile )
oCursor.gotoEnd(false)
oCursor.BreakType = com.sun.star.style.BreakType.PAGE_BEFORE
oCursor.insertDocumentFromUrl(cUrl, Array())
next

'oFinalDoc.close(True)
End Sub



Unfortunately, I only have MS Word 2007 Beta installed on my Win Box, so I couldn't convert the doc to Reader format but I know it works as I'd converted a word doc earlier. Oh, by the way the same process could have been accomplished by ditching everything and passing the url of html directly to the oo macro or if you really really wanted to use some linux cmd then
wget allows you to fetch multiple pages by following links (though am not too sure whether that would work for img tags).
Moral of the story: at times we learn few things which we didn't need to learn then but maybe we'll find them to be useful sometime down the line.

Friday, September 29, 2006

Books of note

I've always been quite fond of reading and though it's been some time since I've read a book, a discussion with someone today got me talking about the books which have had some kind of influence on me, so here is the short list in no particular order:

  • Bridge Across Forever by Richard Bach
  • Illusions by Richard Bach
  • Jonathan Livingston Seagull by Richard Bach
  • A Diary Of A Young Girl by Anne Frank
  • Wuthering Heights by Emily Bronte
  • Vanity Fair by W.M. Thackeray
  • Gone With The Wind by Margaret Mitchell
  • Delhi Is Not Far (A Collection of Short Stories) By Ruskin Bond
  • Best of O' Henry by O' Henry
  • We, The Living by Ayn Rand
  • Tale Of Two Cities by Charles Dickens
I am currently reading Ivanhoe by Walter Scott (I've been trying to read that for past 2 months!), the to-read-next list contains Bhagvat Gita, Fountainhead among others. Any recommendations based on kind of stuff that I like reading (life philosophy, love stories et al)?

Oh, by the way I stumbled upon this quote on /. today, which I found to be quite funny:
The only person who got all his work done by Friday was Robinson Crusoe!

Thursday, September 21, 2006

Se A Vida É

How many times you come up with a situation where there's only one place in this entire world where you'd want to be at, one place which you would take anyday without even a thought, without even worrying about the other aspects and then one day you are asked to be at that place and you have to turn it down...because you just can't be there no matter how much you yearn for.
There are few things that are just way too painful but perhaps Se A Vida É (that's the way life is)...

Wednesday, September 20, 2006

Messageboxes

How many times have you come across a messagebox with some weird text and error number that you want to search for on the net? Well, till date I'd have to hand write the entire text, but not any longer cause now I've learnt that pressing CTRL-C while the Messagebox has the focus actually copies over the entire contents of the MessageBox to the clipboard! Guess, I am very slow learner.

Sunday, September 17, 2006

Never trust a stranger...

Just learnt it the hard way today!

Sunday, September 03, 2006

Sled Menu on Ubuntu Dapper and other stuff


I've been hearing a lot about SLED off-late and the fact that it's menu has been ported to Ubuntu, so I decided I'll give it a shot. The installation was quite easy, I followed the instructions from Angelic Penguins and got it up and running in a matter of 5 minutes. I won't say this is the best thing that could have happened to Linux after Linux but it sure looks a lot better than the original gnome menu. I had to manually tweak few things to get it fully working after the installation though, the tweaks were minor and required changes through Configuration Editor (gconf-editor). Firstly, the "Favorites Applications" section showed only 2 applications, you can add more applications by editing the /desktop/gnome/applications/main-menu/file-area/user_specified_apps key; finding the name of the .desktop file to add can be done by issuing "ls /usr/share/applications" command at the terminal. Secondly, the "Control Center" link was broken, this can be fixed by setting the ..../main-menu/system-area/control_center_item key to /desktop/gnome/applications/main-menu/system-area/control_center_item and the "Install Applications" link can be changed to Synaptic by changing "package_manager_item" to synaptic.desktop.
Taking Screenshot of a menu:
In the process of installing SLED menu and trying to take the screenshot, I learnt that taking a screenshot of a menu is not possible with PrintScreen and you have to resort to deferred screenshot i.e. after some time interval of the keypress, this can be achieved by issuing the following command: gnome-screenshot --delay n; where n is the seconds after which the screenshot would be taken.
Defining a keyboard shortcut:
I decided to map the "take deferred screenshot" to Shift-Print key, if you've been using Ubuntu you would have noticed that not all the applications can be mapped to keyboard shortucts using "Preferences-->Keyboard Shortcuts", so to map this keyboard shortcut to our app we need to again resort to gconf-editor, more details about the how to go about can be found over here. Also by tweaking the keyboard mapping (all you need to do is goto Preferences->Keyboard, select "Layout Options->Alt/Win key behaviour" and check "Hyper is mapped to Win keys"), you can map shortcuts like <win>e to nautilus (<mod4>e), <win>d to "show desktop" (<mod4>d) etc.

Wednesday, August 30, 2006

Separation Anxiety Disorder

When I was a kid I suffered from Separation Anxiety Disorder, not that I or my parents knew about it then but I think had most of the symptoms. I don't know how much it affects me now but it was a very emotionally stressfull experience, as a parent do make sure that your child is also not suffering from the same, remember it is always more painful for the child so do handle it with care.

A coincidence?

I won't say that I 100% believe in metaphysical sciences like Astrology, Numerology, Tarot etc. but I do think they hold some weight and like any other science, is based on certain assumptions. But something just made me think, ever since I've come to US I've shifted 3 houses and there is a unique thing about the house numbers. The house numbers are: 3905, 386 and now 125 and if you add up all the digits together and reduce them to a single number like in Numerology they all add up to 8! I didn't pick these houses based on the house numbers, infact I only found this out quite late...does a number pattern really mean something or is it just a coincidence?

Saturday, April 22, 2006

That's it for now

I've decided to take a break from blogging and I won't be updating this blog anytime in near future, I've been blogging for nearly 2 years now and it had mostly become a part of my life where I could write about my life, my thoughts and some technical things that I've learnt along the way. I know it's going to be a little difficult having to live without being able to share my thoughts but as they say all good things must come to an end.
Thanks to everyone who visited this blog and I hope that you left this blog feeling more enlightened than less.

Take care,
Sachin

Friday, April 14, 2006

Mutually exclusive RadioButton in INamingContainer redux

Some time back I'd posted about the bug with mutually excusive radiobuttons in repeater controls for VB.Net and hacking my way around the bug. Well, since some time I'd been thinking of posting how I actually did it for the benefit of others and today is the day! As they say, better late than never. Here's the CustomRadioButton.vb class:



Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Globalization
Imports System.Collections.Specialized

Public Class CustomRadioButtonControl
Inherits WebControl
Implements IPostBackDataHandler

Shared Sub New()
CustomRadioButtonControl.EventCheckedChanged = New Object
End Sub

Public Sub New()
MyBase.New(HtmlTextWriterTag.Input)
End Sub
#Region "Properties"

Public Event CheckedChanged As EventHandler
Private Shared ReadOnly EventCheckedChanged As Object

Private ReadOnly Property UniqueGroupName() As String
Get
Dim grpName As String = Me.GroupName
Dim unqId As String = Me.UniqueID
Dim num As Integer = unqId.LastIndexOf(":"c)
If (num >= 0) Then
grpName = (unqId.Substring(0, (num + 1)) & grpName)
End If
Return grpName
End Get
End Property


Public Overridable Property GroupName() As String
Get
Dim grpName As String = CType(Me.ViewState.Item("GroupName"), String)
If (Not grpName Is Nothing) Then
Return grpName
End If
Return String.Empty
End Get
Set(ByVal value As String)
Me.ViewState.Item("GroupName") = value
End Set
End Property

Public Overridable Property Checked() As Boolean
Get
Dim grpChecked As Object = Me.ViewState.Item("Checked")
If (Not grpChecked Is Nothing) Then
Return CType(grpChecked, Boolean)
End If
Return False
End Get
Set(ByVal value As Boolean)
Me.ViewState.Item("Checked") = value
End Set
End Property

Private ReadOnly Property SaveCheckedViewState() As Boolean
Get
If ((Not MyBase.Events.Item(Me.EventCheckedChanged) Is Nothing) OrElse Not Me.Enabled) Then
Return True
End If
Dim baseType As Type = MyBase.GetType
If ((Not baseType Is GetType(CheckBox)) AndAlso (Not baseType Is GetType(RadioButton))) Then
Return True
End If
Return False
End Get
End Property

Public Overridable Property AutoPostBack() As Boolean
Get
Dim doAutoPostBack As Object = Me.ViewState.Item("AutoPostBack")
If (Not doAutoPostBack Is Nothing) Then
Return CType(doAutoPostBack, Boolean)
End If
Return False
End Get
Set(ByVal value As Boolean)
Me.ViewState.Item("AutoPostBack") = value
End Set
End Property


Private ReadOnly Property Value() As String
Get
Dim val As String = Attributes("value")
If (val Is Nothing) Then
val = UniqueID
End If
Return val
End Get
End Property

Public Overridable Property [Text]() As String
Get
Dim grpText As String = CType(Me.ViewState.Item("Text"), String)
If (Not grpText Is Nothing) Then
Return grpText
End If
Return String.Empty
End Get
Set(ByVal value As String)
Me.ViewState.Item("Text") = value
End Set
End Property

Public Overridable Property TextAlign() As TextAlign
Get
Dim align As Object = Me.ViewState.Item("TextAlign")
If (Not align Is Nothing) Then
Return CType(align, TextAlign)
End If
Return TextAlign.Right
End Get
Set(ByVal value As TextAlign)
If ((value < TextAlign.Left) OrElse (value > TextAlign.Right)) Then
Throw New ArgumentOutOfRangeException("value")
End If
Me.ViewState.Item("TextAlign") = value
End Set
End Property

#End Region

Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
If (Not Me.Page Is Nothing) Then
Me.Page.VerifyRenderingInServerForm(Me)
End If
Dim doRender As Boolean = False

If Not Me.Enabled Then
writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled")
doRender = True
End If
Dim tip As String = Me.ToolTip
If (tip.Length > 0) Then
writer.AddAttribute(HtmlTextWriterAttribute.Title, tip)
doRender = True
End If
Dim _onClick As String = Nothing
Dim _attributes As AttributeCollection = MyBase.Attributes
Dim _value As String = _attributes.Item("value")
If (Not _value Is Nothing) Then
_attributes.Remove("value")
End If
_onClick = _attributes.Item("onclick")
If (Not _onClick Is Nothing) Then
_attributes.Remove("onclick")
End If
If (_attributes.Count <> 0) Then
_attributes.AddAttributes(writer)
doRender = True
End If
If (Not _value Is Nothing) Then
_attributes.Item("value") = _value
End If
If doRender Then
writer.RenderBeginTag(HtmlTextWriterTag.Span)
End If
Dim _text As String = Me.Text
Dim _clientId As String = Me.ClientID
If (_text.Length <> 0) Then
If (Me.TextAlign = TextAlign.Left) Then
Me.RenderLabel(writer, _text, _clientId)
Me.RenderInputTag(writer, _clientId, _onClick)
Else
Me.RenderInputTag(writer, _clientId, _onClick)
Me.RenderLabel(writer, _text, _clientId)
End If
Else
Me.RenderInputTag(writer, _clientId, _onClick)
End If
If doRender Then
writer.RenderEndTag()
End If

End Sub

Private Sub RenderLabel(ByVal writer As HtmlTextWriter, ByVal [text] As String, ByVal clientID As String)
writer.AddAttribute(HtmlTextWriterAttribute.For, clientID)
writer.RenderBeginTag(HtmlTextWriterTag.Label)
writer.Write(text)
writer.RenderEndTag()
End Sub


#Region "Rendering"

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
If ((Not Me.Page Is Nothing) AndAlso Me.Enabled) Then
Me.Page.RegisterRequiresPostBack(Me)
End If
If Not Me.SaveCheckedViewState Then
Me.ViewState.SetItemDirty("Checked", False)
End If

If (((Not Me.Page Is Nothing) AndAlso Not Me.Checked) AndAlso Me.Enabled) Then
Me.Page.RegisterRequiresPostBack(Me)
End If
If (Me.GroupName.Length = 0) Then
Me.GroupName = Me.UniqueID
End If
End Sub

Friend Sub RenderInputTag(ByVal writer As HtmlTextWriter, ByVal clientID As String, ByVal onClick As String)
writer.AddAttribute(HtmlTextWriterAttribute.Id, clientID)
writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio")
writer.AddAttribute(HtmlTextWriterAttribute.Name, Me.GroupName)
writer.AddAttribute(HtmlTextWriterAttribute.Value, Me.Value)
If Me.Checked Then
writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked")
End If
If Not Me.Enabled Then
writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled")
End If
If Me.AutoPostBack Then
If (Not onClick Is Nothing) Then
onClick = (onClick & Me.Page.GetPostBackClientEvent(Me, ""))
Else
onClick = Me.Page.GetPostBackClientEvent(Me, "")
End If
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick)
writer.AddAttribute("language", "javascript")
Else
If (Not onClick Is Nothing) Then
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick)
End If
End If
If (Me.AccessKey.Length > 0) Then
writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, Me.AccessKey)
End If
If (Me.TabIndex <> 0) Then
writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, Me.TabIndex.ToString(NumberFormatInfo.InvariantInfo))
End If
writer.RenderBeginTag(HtmlTextWriterTag.Input)
writer.RenderEndTag()
End Sub

Protected Overridable Sub OnCheckedChanged(ByVal e As EventArgs)
Dim handler As EventHandler = CType(MyBase.Events.Item(CustomRadioButtonControl.EventCheckedChanged), EventHandler)
If (Not handler Is Nothing) Then
handler.Invoke(Me, e)
End If
End Sub

#End Region

#Region "IPostBackDataHandler Members"

Public Overridable Shadows Sub RaisePostDataChangedEvent() Implements IPostBackDataHandler.RaisePostDataChangedEvent
OnCheckedChanged(EventArgs.Empty)
End Sub

Private Function LoadPostData(ByVal postDataKey As String, ByVal postCollection As NameValueCollection) As Boolean Implements IPostBackDataHandler.LoadPostData
Dim grpName As String = postCollection.Item(Me.GroupName)
Dim flag As Boolean = False
If ((Not grpName Is Nothing) AndAlso grpName.Equals(Me.Value)) Then
If Not Me.Checked Then
Me.Checked = True
flag = True
End If
Return flag
End If
If Me.Checked Then
Me.Checked = False
End If
Return flag
End Function

#End Region
End Class

Embedding the control in your aspx page is simple, just register the tag prefix using:
<%@ Register TagPrefix="ucl" Namespace="XYZ.Website" Assembly="XYZ.Website"%>

PS: forget about how to showing the code snippet to embed it aspx page, blogger really sucks when you want to include html tags as is within your post. Basically you set the groupName property and the id property!

Saturday, April 08, 2006

Only yesterday

Recently, I received a mail from dialpad that my account would be cancelled as they are now part of Yahoo!. I used to use dialpad extensively 2 years back with an average of 2 hours per day coupled with like 1 hour on yahoo voice chat. I sure miss those days and it seems like as if it all happened only yesterday, either my life has stagnated since then or somethings are just impossible to forget about.

Thursday, April 06, 2006

Comment of the day

Today Harvinder Pal Singh (aka Kishi) from MS posted his first blog entry on Port25 (MS Linux lab), the post was nothing great but the comment#2 by "Santa Singh" made me laugh & remember the good ol' Santa & Banta jokes :)
"re: Welcome to Kishi's Korner
Thursday, April 06, 2006 8:48 AM by Santa Singh
Paaji,

Oye....welcome to the netta!"

Wednesday, April 05, 2006

Anonymous blogging in corporate world?

The title of the post might sound paradoxical & I just want to touch on the same topic, should you be anonymously blogging about your job/company? NO! don't even think about it, if your company encourages blogging then blog publicly i.e. let your PR dept. know, or don't blog anything specific related to your company (remember a blog is just another website waiting to be discovered). I, for instance blog anonymously, that is no where on my profile or on my blogs you would find any explicity reference to the company I work for, the reason being most of the times I blog about my personal life and how much it sucks with some technical posts thrown in between, and I don't want my private life being discussed at work! You would never find any post on my blog which says how much my work sucks or how I waste away my time in the office by pretending that I'm working (PR dept.: if by any chance you're reading this post then don't take it literally, I am the most sincerest employee you could have ever imagined to find..hee hee). Secondly, there're are very few close friends/family members who even know that I blog (different story if they stumbled on it) and if you're one of those "acquaintances" who just stumbled on it, I would very much appreciate if you keep it to yourself.

Tuesday, April 04, 2006

Latest iTunes additions

This weekend I downloaded few songs from iTunes, here they are with my ratings:
1) Glasses by Slizzy Bob (6/10)
2) Since I don't Have You by Guns n' Roses from the album The Spaghetti Incident (6/10)
3) La Luna by Belinda Carlisle from Runaway Horses (7/10)
4) Heartbeat by Wham! from Make it Big (6.5/10)
5) Skies the limit by Fleetwood Mac from Behind the Mask (7/10)
6) The World I know by Collective Soul from The Absolute Hits (7/10)
7) Afterglow by INXS from Switch (9/10)

All these songs I have listened to long before apart from the exception of Afterglow which just couple of days back I first listened on the MusicMatch Jukebox radio (I was playing Cyndi Lauper and "related artists").

Monday, April 03, 2006

Afterglow

I've absolutely fallen in love with "Afterglow" by INXS from their album Switch , the lyrics are really profound about dealing with a sense of loss in a postive way and remembering someone forever. I also love the background chanting that is there in the song, it just adds to the profoundness. And yes, I never even felt that it's not Michael Hutchence singing, which by itself speaks of their new found lead singer.
Update: Just finished watching the video on Yahoo! Launch (warning, works only in IE), the video isn't anything great but goes pretty well with the lyrics and the mood of the song.
Touch me and I will follow in your afterglow
Heal me from all this sorrow...

Saturday, April 01, 2006

bloglines down?

Is it just me who's experiencing issues with bloglines or is it universal? For most part of the day, bloglines hasn't shown me any new items at all, when I know for sure almost most have been updated. Oh, in case you're wondering what kinda feeds I subscribe to, you can view my blogroll here.

Moving on...

After a long and hard thought, I've decided to switch my job & I'll be joining KSC (Kuwait Oil Company) starting 15th of this month as a Technical Evangelist. I'll be moving to Ahmadi sometime end of this week subject to availability of tickets on Kuwait Airlines, what I really like about KSC is that they have a very open culture and they've got some real cool geeks working for them like Al Bashar Ul-Hussein, the father of CXA (Componentized Xml Architecture) and others. I got a mail from their HR on the 29th of Feb. and since then had 3 technical, 1 HR and 1 religious interview round (the religious round was more or less to ascertain whether you can survive in a Islamic country or not). My primary responisbility would be to help architecting & building the automation framework, which would automate the entire process of extracting oil from the wells to finally shipping them. Given that the TL on this project is Bashar himself, I am really excited to be part of such a team. Hopefully, my next post would be from Ahmadi itself....kuwait am coming!!

Sake and Sushi time

Today was my first attempt at Sake and Sushi and well I feel both of them are passable! I tried a hot kurosawa and a cold Mu with Salmon sushi on the sides, the Mu for sure reminded me of some sweet coconut water that I used to have once in a while when I was a kid. I'll have a Pinot Grigio over these anytime. Aside, if you haven't tried Ethiopian cuisine and are in vicinty of Washington D.C., you should give Zed's a shot, it's simply worth it.

Tuesday, March 28, 2006

ExecuteXmlReader woes

These days I get problems which by no means are "funny" (I brand a problem as funny which is quite challenging and still fun to work on). So the problem is this: given a one-to-many relationship between two tables in Sql Server, generate a one-time report in excel which linearizes (I don't know whether it's the correct term) the entire data in one row for a given main entity. Confused? so was I when I got this requirement, let me try to explain the problem (often times knowing the problem itself means you're half way there!) by giving an e.g. consider two tables Orders and OrderLines, Order table contains the data about the order (let's say the customer name, date entered etc.) and the OrderDetails contains data about the line items in a single order (let's say the product information abt the data that was ordered etc.). Here's a snippet of a highly denormalized (it works for the e.g. that I'm abt to give) design of these two tables in db:
Order:
OrderId int pk,
CustomerName varchar(100)

OrderLines:
OrderId int not null fk_refers_to_Order
ProductName varchar(100).
Here's a sample set of data:
Order Table:

OrderIdCustomerName
1Tada
2Wada

Order Details Table:


OrderIdProductName
1Prod1
1Prod2
2Prod1
2Prod3

The generated report should have output in this format:


OrderIdProduct 1Product 2
1Prod1Prod2
2Prod1Prod3

So how do you solve it, well here's what I did...loaded the data using for xml explicit so that the OrderLines data is rolled up and added to Order node as children. Wrote an Xsl to iterate through the nodes and print them in a csv format and loaded the csv in xls. Different story that I faced quite a few issues with this approach! Firstly, for xml explicity returns the resultset as a fragment (i.e. there is no root node), during ASP/VB days I could add a dummy root node quite easily in the xml template but I couldn't any easy way of achieving it in ADO.Net! The only approach that I found was on serverside.net which added the dummy root node in the for xml query itself. Once I got the XmlTextReader, I loaded it into a dataset with XmlReadMode.InferSchema and used dataset.WriteXml to write the entire xml to a file (I had to follow this approach just to get the entire xml from "for xml" query, the query analyzer always truncates the results if it exceeds certain characters). With the xml file in hand I wrote some quick n dirty (this operation was one time only and hence there was no need to automate the entire process) xsl in cooktop which would save the generate a csv output.
The relevant snippets of code and xsl are below:

XmlTextReader r = (XmlTextReader)cmd.ExecuteXmlReader();
myDataSet1.ReadXml(r,XmlReadMode.InferSchema);
myDataSet1.WriteXml("data1.xml");

Update: Had to remove the xsl listing as it was randomly blewing up my feed! Will put it back on once I figure it out.

Friday, March 24, 2006

Google maps prototype live again

Some time back my free hosted website was auto-deleted by somee.com due to "cpu overuse", now given that I don't have many high-end background procceses running on my site; it was quite a surprise but as they say you get what you pay for! Nevertheless, I've got the site back up and running and reuploading the entire chunk took me some time to figure out as I would get real bizarre configuration errors on the live site.
The Fx page transition e.g. is also back where it originally was and so is the Google Maps prototype, by the way I'd updated the prototype long time back to integrate it with MapPoint, Flickr and Fotolia...and yes, please don't use way too much bandwidth while checking them out :)

Wednesday, March 22, 2006

My tryst with Linux


It's been nearly 6 months that I installed Linux on my laptop, and since off-late I've started booting into it more regularly I think it's a time to post my experiences around Linux (primarily Ubuntu; that's what I've installed).
  • Prep: I used PartitionMagic to create partitions as I've had bad experience with using Linux based partition apps, even though those were the days when Linux had just started way back in 1999 it's always better to be careful: as they say; once bitten twice shy. I resized my ntfs partition & created a physical Ex3 partition and that's where I sc***ed up! I didn't make any FAT partition making it impossible to create a local read/write share between the two OSes (XP and Linux). Moral of the story: Measure twice, cut err partition once!
  • Installation: Went like a charm, almost everything was auto-detected including my WIFI card, as a Windows user you might think what's the big deal, but believe me getting all of the piece of hardware detected and auto-configured is really a big deal in Linux (ask my friends who still are having problems with their wireless card being detected by Fedora and Red Hat). Another thing that I did was to install Grub (a boot loader) onto MBR.
  • First Impression: Ubuntu is gnome based rather than KDE based like it's sibling Kubuntu, hence I didn't get that Windows kinda looks but I've to admit that apart from gnome-panels which look very very dated, I like the look-n-feel of gnome.
  • Applications: Ubuntu comes pre-installed with most of the stuff that you would need on day to day basis like Firefox as web browser, OpenOffice as office suite, Gaim (IM client), xpdf for pdf viewing, gimp for image manipulation etc. so you are almost set once you log in.
  • eXtras: The main reason to install Linux distro was to try out Mono, so I installed Mono and MonoDevelop (IDE for mono) and created a small ASP.Net web page in MonoDevelop. Mono comes with a lightweight web browser (much like Cassini) called xsp and voila the web page ran without any hitches, the only thing is MonoDevelop is still under development (well, so is mono) so you don't get support for code-behind pages yet.



monodevelop

HelloWorld in MonoDevelop


xsp and mono

Xsp and helloworld.aspx


  • Verdict: All in all a cool "geeky" OS but still not user-friendly enough for Average Joe to really give a scare to Windows.

Saturday, March 18, 2006

Url Checker with HttpWebRequest

Recently one of my colleagues came with a problem, where he wanted to check the validity of a url submitted by the user for some reporting tool that he was writing. Since I've had some experience with HttpWebRequest, I asked him to use it to get the response and then check the StatusCode returned, everything was hunky-dory till people started entering Urls for huge pdfs and doc files et al, since the UrlChecker would make a Http-Get call to the Url, it meant getting the entire document from the Url which was putting some unnecessary load on our server. Well, if you just need to check for the validity of a url (i.e. if it's alive or not) you can use Http-Head method to only return the header information. This is how I did it:


    private bool IsValid(string url)

    {

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

        wr.Method = "HEAD";

        HttpWebResponse ws = null;

        try

        {

            ws = (HttpWebResponse)wr.GetResponse();

            switch (ws.StatusCode)

            {

                case HttpStatusCode.OK:

                case HttpStatusCode.Accepted:

                    return true;

                    break;

            }

        }

        catch (HttpException e)

        {

            if (ws != null)

            {

                switch (ws.StatusCode)

                {

                    case HttpStatusCode.Forbidden:

                    case HttpStatusCode.NotFound:

                        return false;

                }

            }

        }

        finally

        {

            if (ws != null)

                ws.Close();

        }

        //dummy return

        return false;

    }

Friday, March 10, 2006

Cooking is not for men

Today while chopping onions for the dinner I chopped my thumb along with it, this is the second time in this week when I have tested the sharpness of knife on my fingers and hence I have come to the conclusion that cooking is indeed not for men, atleast not for me. But given the fact that I don't have anyone else to cook food for me, guess I'll have to keep on trying the knife on my fingers for more time to come in the future.

Wednesday, March 08, 2006

Unstrung words

There are things in life that happen by themselves and then there are things in life that make us strive hard, bend and at times look like a fool. In my experience the things that don't matter to us are the things that happen by themselves but the things that we care about make us go out and achieve them, why is that so? It's because the fears, the doubts and the negative feelings that come along with the things that we care for, because they matter to us we desparately want them to happen: the more you care, the more you fall. And then there are people who appear from nowhere when you're down: good friends, people who are always there to give you free advices, people whom you care about and who care about you....so do you follow your own instincts even if all and sundry think otherwise or do you listen to them and do what they say? well, it's your life and not theirs..you have to know what you want/need and think/act accordingly...I don't need somebody else to screw my life (by following their advices), no thanks..I can pretty much do it myself and be better at it too!
And yes today is the "Women's Day" (not that I care) so wishes to all the women born today and more so to the woman who for me, defines the real meaning of being a woman..happy birthday!

Saturday, March 04, 2006

Google, Yahoo and MSN Search

If you're using Firefox and have HTML Validator extension installed have you noticed that the MSN search results page renders without any error or warnings, whereas Yahoo! is rendered with Warnings (were like 126 for the query that I tried) and Google's got errors as well as warnings? Not that it matters much cause the pages are rendered without any glitches but I feel MSN Search team deserves a pat on their back for generating an error and warning free results page (which as a techie myself, I know is not the easiest to achieve).

bad times are good times...

"bad times are good times to prepare for the better times!"
One of my IM contacts had this one liner as her status message, I absolutely fell in love with it...well off-late, I've been having way too much prep time to my comfort!

Wednesday, March 01, 2006

Web 2.0 Paradigm

Almost every one is jumping on the a.k.a. "The Return of the .coms" bandwangon, basically web 2.0 is all about social networking and thick web clients using some or the other Ajaxian techniques. Given the previous trackrecords of .coms (2000ish, when it went bust), one really has to think the business model behind this all, I was recently reading pretty insightful Russel Beatties' post around the same (aptly titled WTF 2.0) where he raises the same questions which I've been having since long...what's the business model of all these web 2.0 .coms which have mushroomed out of nowhere all of a sudden?

First things first, let's see how web 2.0 differs from web 1.0 (portals was the buzzword then) sites, I see two major differences:
  1. The internet penetration: the majority of people now have faster internet connections like cable or dsl (think abt dialups then), so an Average Joe spends more of his time online.
  2. Social networking: almost all the portals had very little or close to nothing end-user involvement, all the end-user was able to do was read through myriad of information and hence the end-user retention rate used to be pretty low and it wasn't attractive enough for the new user to create an account. Think web 2.0, be it del.icio.us or digg it's the end-user(s) that control the content: I like a news and want others to read, I digg it, liked a website? bookmark it at del.icio.us. Now it's all about sharing your(i.e. the end-user) knowledge, interests etc with the world, the current web apps just aid in orchestrating the information.
  3. Mindset shift: Another differentiating factor is that the Average Joe is more comfortable now in managing a good chunk of his life and time online, for e.g. earlier a lotsa people used to be sceptical abt buying anything online but that number has come down drastically (think iTunes etc.).


Now to the main point, yes web 2.0 have a better user-retention model than web 1.0 portals but where's the cash inflow? Given that the domains and shared hosting is dirt cheap nowadays almost anyone from a college going kid to a homely mother of 5 can start a web 2.0 out of his/her pocket, no problems here, the problem comes when you get popular as Russell points out in his post. You've more requests & users than your shared host can handle, so now either you shut your shop or you invest some chunk of your money into getting a better infrastructure for site. So now we do have a pretty high TCO (good cash outflow without any inflow), so let's try to think of the ways of generating revenue, I can only think of 3 ways that you can generate revenue online and be profitable (not taking into a/c conning a VC to invest), listed below in order of profitability:
  1. An Ad-Free and really free website: See point 4. Examples: 43things, technorati, del.icio.us etc.
  2. Contextual Ads: Sign up for Google Ads or Yahoo! Ads or whatever and hope Average Joe's gonna be enticed enough to click on the ads enough number of times for you to make some good moolah (this might work if you're still on a shared hosting and the investment that you've made is pretty low). Examples: Digg uses this model by the way, this can't be their only revenue model, given that Alexa rates it among the top 500 websites they gotta have more than 1000....(fill in the remaining 0s) users which can't be supported on a shared hosting.
  3. Sell something: Needn't be a physical product like amazon or ebay sells, could be some advanced features or goodies of your website. Example(s): flickr.
  4. Wait for a bigger fish to swallow you: Given that some bigger fishes like Yahoo! are buying almost everything under the .com sun, build something niche (actually needn't be that niche either), get a good user base to boast off and start approaching bigger fishes whom you think might be interested in your thingie. There are few caveats with this though: first define the exit criteria pretty clearly, what if no fish takes the bait? then either be prepared to wait and shell out more from your pocket or shut your shop quietly (online users generally have a short memory span, they'd forget you and move on). Generally, the bigger fish would be more interested in buying "a company" which can exist on it's own than buying just the idea (ie your website & perhaps you), so point 4. is indeed your exit strategy then you might indeed have to look at conning VCs ;-). Think off the bigger fishes which might be interested in your kinda app upfront and define the technology platform based on that for e.g. it would be tough to sell a Java/Apache/PHP/Linux based web 2.0 app to Microsoft and equally tough to sell ASP/.Net/SQL Server based website to Yahoo! or Google. Examples: flickr, webjay, upcoming.org, orkut etc etc etc.

The straw that broke the camel's back...

Ever since 2002 or so I've been having some pain or the other in my back, earlier it used to affect my lower back but since past one year it has happily shifted to my upper back (I don't how that works but the lower back is pretty much alright these days but the pain in the upper back has increased multi-folds to a point where sometimes it's just way too much to handle). I think the pain can be attributed to wrong (and long) sitting postures, esp. now that I work primarily on a laptop which means your head is not in line with the screen and you have to bend down to view the screen properly...that's why I feel it's imperative that you should use an external monitor and/or keyboard with the laptop to make sure the alignment of the head & the screen is pretty much in the same straight line and hence avoiding the bending down business all together. Recently, a friend of mine underwent a keyhole surgery on his back for perhaps the same issue which has got me to think seriously about visiting a doctor too. Given how much I "love" visiting doctors and taking pills, it's quite obvious why I had been avoiding it for so long, I am hoping that just like the pain shifted from lower to upper portion, one fine day it would just shift further up to a point which doesn't affect my body any longer.

Friday, February 24, 2006

Estranged

The first time when I heard Guns n' Roses' Estranged, the following piece of lyrics caught my mind:
old at heart but I'm only 28,
& much too young to love break my heart.
young at heart but it's getting much too late,
to find ourselves so far apart.

I was in my early 20s when I first heard this song & for some reasons I always remembered these lines. Now that I'm 28 (brand new year, same old life!), I wonder if there was any reason why I remembered them for so long...and it seems to be quite obvious.

Saturday, February 04, 2006

the art of communication

Communication is a very funny thing and it can make or break almost anything, be it a sales pitch, a job interview or a relationship. It's not just about what you say but also how you say it and most of the times it really doesn't matter what you infact implied but how the "other person" understood it. Think about this statement: I want you to atleast meet me once before you go. What do you get from this statement? when I wrote it I meant that of all the things that I expect you to do before you go, meeting me once is one of them. Now let's rephrase the statement a little bit by playing around with the placement of the word "atleast", here's the reordered statement: I want you to meet me before you go atleast once. Whoa! the entire meaning of the statement changes dramatically, now it's like I want to meet you atleast once (or more) before you go : atleast that's what I meant before I wrote those statements.
Given that talking over the phone is one of the most prevalent forms of communication, where all you are spoken words to put your point across, it gives even more chance for the other person to read between the lines and make a completely other judgment. Perhaps this hazard is not so much in chat, e-mail where you have time to think twice and mostly words don't have to be im-promptu and also not so much of an issue when you are talking face to face where the other person & even you have the luxury of reading each other's facial expression. I feel it's imperative that while talking we don't hold back our doubts and try to get them cleared up by asking upright honest questions if we feel there is any scope for misunderstanding...most of the talks fall out more due to misunderstandings than all other reasons combined together.
I still remember what my brother used to told me long time back: communication is not what you say, it's what the other person makes out of it.

Friday, January 27, 2006

Implementing page transitions in Firefox using AJAX and CSS

Page is a feature in IE which allows you to add visual effects on your site using filters when a user enters or exits a page, the problem is that filters are IE-only. What if you want to add same transitions on your site for users who are visiting on Fx? You can emulate some filters of IE by using and CSS on to achieve the same results, here is a simple way to achieve fade-in transition in Fx for page exit:
Instead of redirecting user to second page directly (using links or JS:location.href), retrieve the second page contents using XmlHttpRequest, once the httpRequest has retrieved the contents of page 2, add a timeout function where in you reduce the opacity of the page by steps. Once the opacity falls below a certain value, do a document.write of page 2's response text. Here is the piece of JS code:

var xmlhttp;
var timerId = 0;
var op = 1;
function getPageFx()
{
url = "/transpage2.html";
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest()
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("GET",url,true)
xmlhttp.send(null)
}
else
getPageIE();
}

function xmlhttpChange()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
{
// if "OK"
if (xmlhttp.status==200)
{
if(timerId!=0)
window.clearTimeout(timerId);
timerId = window.setTimeout("trans();",100);
}
else
{
alert(xmlhttp.status)
}
}
}

function trans(){
op -= .1;
document.body.style.opacity = op;
if(op<.4){ window.clearTimeout(timerId); timerId = 0; document.body.style.opacity = 1; document.open(); document.write(xmlhttp.responseText); document.close(); return; } timerId = window.setTimeout("trans();",100); } function getPageIE(){ window.location.href = "transpage2.html"; }

You can see this code in action here.

Monday, January 23, 2006

Code sample: success algorithm

a c# snippet:
//initialize the variables, experience effect is generally the same
int const experience = 1;
int success = int.MinValue();

while(success!=100){
//the chance factor is best left unhandled, also includes the time
int chance = Random.Next(1,100);
try{
effort = 99 - chance; //reduce the effort effect based on the chance factor
//experience can at times help you, at times go against you and times doesn't help at all!
success = effort + chance + Random.Next(1,-1)*experience;
}
catch{
//oops we blew up somewhere..try again
}
}
//we are done yippie, time to introspect...
wasItWorthIt();


so basically either you finally hit the wasItWorthIt stage or you hit a stack overflow exception, good luck :-)

Saturday, January 14, 2006

few things about firefox you didn't know

I really like , apart from it being a really memory hungry beast it's almost perfect with everything that it does...but the documentation of Fx is something which I would say is far from being comprehensive so mostly you have to find stuff on your own. few things that I've found are:
a) Many a times you want to search using the search box without leaving the current page, well go to search box (ctrl-k), type in your query and hit Alt-Enter & viola the results open in a new tab. You can also pick the search engine by using the keyboard (press Ctrl-Down/Up Arrow key). There are tons of search engines to choose from in case you are not satisfied, try http://mycroft.mozdev.org.
b) How do you open a Url on a page if it is not hyperlinked for e.g. the mycroft link above, you don't have to copy the Url, open a new tab & paste the link, just select the link with the mouse and drag it to the tab-bar or to one of the opened tab.
c) File-Exit, is different from Alt-F4 or Close Window. It exits Firefox completely including all open Fx windows (download manager, other Fx open windows included).
d) How many times you would wish that Fx would automatically authenticate you against a given server much like the way IE does? Don't fret there is way for that too, in the location bar type in about:config , in the filters type ntlm and dbl click network.automatic-ntlm-auth.trusted-uris, type in the name of servers for which you want to be automatically authenticated separated by comma and you're done.
e) [01/17] With Fx 1.5 the javascript console started showing CSS errors as well, though this is a great debugging feature at times I would find it cluttering my console when I wanted to see what js is blowing up my code well any one else who always felt the need to be able to filter the console errors/messages by type (like JS, Css, Xml etc) there is this real nice extension, try it out:
https://addons.mozilla.org/extensions/moreinfo.php?id=1815&application=firefox

later...

Sunday, January 01, 2006

2006

another new year...building new hopes, new dreams and making older dreams come to life...by the way there is no such thing as false hope/dream....hope and dreams are good things infact they are the best things & good things in life never die...a beautiful Richard Bach line comes to the mind from his book Illusions: "You are never given a wish without also being given the powers to make it to come true"...you might have to work for it though.
Anywez wishing you all a happy new year, hope 2006 gets you one more step closer to your destination.