Wednesday, May 30, 2007

Maintaining scroll position in .NET 2.0 ListBox on PostBack

Warning: this is only a partially working solution due to some Javascript issues described (and solved) here.

A requirement I had was to maintain the scroll position of ListBoxes on PostBack. The only solution I could find was to get the scroll through Javascript (the scrollTop property of the select) and restore it on page load, however, that would have meant a lot of custom controls, not to mention lots of work, to which I am usually against.

So, I used a ControlAdapter! The ControlAdapter is something new to the NET 2.0 framework. The Control in 2.0 looks for a ControlAdapter and delegates the usual methods (like OnLoad,OnInit,Render,etc) to the adapter. You tell the site to use an adapter for a specific type of control and possibly a specific browser type (by using a browser file), and it uses that adapter for all of the controls of the selected type and also the ones inherited from them. To disallow the "adaptation" of your control, override ResolveAdapter to always return null.

Ok, the code!
C# code
///<summary>
/// This class saves the vertical scroll of listboxes
/// Set Attributes["resetScroll"] to something when you want to reset the scroll
///</summary>
public class ListBoxScrollAdapter : ControlAdapter
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if ((Page != null) && (Control is WebControl))
        {
            WebControl ctrl = (WebControl) Control;
            string scrollTop = Page.Request.Form[Control.ClientID + "_scrollTop"];
            ScriptManagerHelper.RegisterHiddenField(Page, Control.ClientID + "_scrollTop", scrollTop);
            string script =
                string.Format(
                    "var hf=document.getElementById('{0}_scrollTop');var lb=document.getElementById('{0}');if(hf&&lb) hf.value=lb.scrollTop;",
                    Control.ClientID);
            ScriptManagerHelper.RegisterOnSubmitStatement(Page, Page.GetType(), Control.UniqueID + "_saveScroll",
                                                          script);
            if (string.IsNullOrEmpty(ctrl.Attributes["resetScroll"]))
            {
                script =
                    string.Format(
                        "var hf=document.getElementById('{0}_scrollTop');var lb=document.getElementById('{0}');if(hf&&lb) lb.scrollTop=hf.value;",
                        Control.ClientID);
                ScriptManagerHelper.RegisterStartupScript(Page, Page.GetType(), Control.ClientID + "_restoreScroll",
                                                          script, true);
            } else
            {
                ctrl.Attributes["resetScroll"] = null;
            }
        }
    }
}


Browser file content<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType ="System.Web.UI.WebControls.ListBox"
adapterType="Siderite.Web.WebAdapters.ListBoxScrollAdapter" />
</controlAdapters>
</browser>
</browsers>


Of course, you will ask me What is that ScriptManagerHelper? It's a little something that tries to get the ScriptManager class without having to reference the System.Web.Extensions library for Ajax. That means that if there is Ajax around, it will use ScriptManager.[method] and if it is not it will use ClientScript.[method]. To.Int(object) is obviously something that gets the integer value from a string.

There is another thing, at the beginning I've inherited this adapter from a WebControlAdapter, but it resulted in showing all the options in the select (all the items in the ListBox) with empty text. The value was set as well as the number of options. It might be because in WebControlAdapter the Render method looks like this:
protected internal override void Render(HtmlTextWriter writer)
{
  this.RenderBeginTag(writer);
  this.RenderContents(writer);
  this.RenderEndTag(writer);
}

instead of just calling the control Render method.

Crystal Reports - Custom tool error

While working on a Windows app that used Crystal Reports 9 with Visual Studio 2003 on .NET 1.1 I've stumbled upon a problem. For no apparent reason, the saving of a report took minutes rather than seconds, the .cs file associated with the report sometimes disappeared and randomly errors like the one below appeared:

Custom tool error: "Code generator 'ReportCodeGenerator' failed. Exception stack = System.IO.FileNotFoundException: File or assembly name CrystalDecisions.CrystalReports.Engine, or one of its dependencies, was not found.
File name: "CrystalDecisions.CrystalReports.Engine"
at CrystalDecisions.VSShell.CodeGen.ReportClassWriter..ctor(String filePath)
at CrystalDecisions.VSShell.CodeGen.ReportCodeGenerator.GenerateCode(String inputFileName, String inputFileContent)


I've searched the net and found a lot about wrong versions, deploying, etc. But I wasn't deploying anything, for crying out loud! First I thought it was about installing the Crystal Reports X runtime. I removed it, but that didn't solve anything. What was I to do?

Well, a temporary solution was to backup the .cs file somewhere, as it seemed not to change. Then I would just copy it back and add it to the project and it would work, but again, the time consumed by saving the report was huge! And there were caching problems. Sometimes I would see the report without the last modification in the application.

After a while I realised that actually I was deploying something. The project also had an installer, with the Crystal Reports .msm files. I remembered that I did install the application once, in order to test the installation process. Then, of course, I did remove it from the installed applications. That was it! All I had to do was to reinstall the application, thus repairing some Crystal Reports files or configuration that the uninstall process previously messed up.

Monday, May 28, 2007

TagBoard sucks!

I had this idea to put a chat on the blog, kind of like the old school Bulletin Board System I had once. The fun I had back then, talking nonsense to so many people I didn't know... [rolling eyes].

Anyway, I took the advice of Blogger and used the chat from TagBoard. The other recommended chat was marked as bad by SiteAdvisor. The first thing I noticed is that it was a very simple site as well as a very simple chat: your basic iframe and some text inputs. The second thing I noticed is that most of the features were restricted to payed accounts.

Well, who needs them? Auto-refresh? I can make my own! Ban IP? What for? Filter messages? Why? But soon enough I got a spam message. So I went to the TagBoard interface and deleted it. Next day I got two. I deleted those as well. Then 4 appeared. Deleted. Then 8! I was kindda worried that they would progress geometrically. And maybe they did, but TagBoard has a limit of messages it keeps in memory.

I have no real evidence for this, but I can only think of one reason this spam would occur a few days after I enabled the account, and that is that the spam is perpetrated by TagBoard itself to force you into buying an account. Afterwards you would probably notice that the spam comes from a single IP, you would block it, and be happy. Also, I noticed that the iframe that they served me occasionally tried to open a popup. It fits into the general profile I've associated with them.

Therefore, the chat is gone. I only had like two messages on it anyway. People seem more interested in commenting (yeah right).

Sunday, May 27, 2007

New series I've tried

I will just summarise the series I've seen or came in contact with after the sad loss of Stargate :'(.

First of all: Ugly Betty (the US version). My wife watches it. It sucks ass! It's just like a gayified, pointless conveyor belt of clichees, mostly stolen from other clichee series of "romantic comedies". The only bit of originality comes from the original Colombian Ugly Betty. The premise: ugly girl with huge heart in the world of fashion. All possible violence or tension has been stripped off, though.

Next: Doctor Who. After having seen the wonderful reinventing of Battlestar Galactica, I kind of hoped that Dr. Who would be just as great. I haven't seen the original series, but this one is plain silly. I still watch it, but it's like watching Charmed. Lots of ridiculous comedy with a sci-fi twist. The premise is that an alien, last of his race, is travelling through time and space to ... watch history unfolding. He takes along Billie Piper, who is terribly cute, but that's about all that is good in the show.

Numb3rs! Now here is a show that is obviously planned from a recipe, but I like it. The premise of the show is that a brilliant mathematician is helping his FBI brother solve cases. And I swear my previous post about superhero mathematicians was written before I even heard of this show. The show has high quality values, both in police/military strategy, budget and human relationships. The math, though, is really basic, but it just had to be, obviously. I think of it as a science popularisation police show.

If anyone knows of a good sci fi show or at least a decent mainstream one, please let me know. I am in withdrawal already, torn between the loss of my fantasy world and the complete boredom of my real one. I don't even have time to fantasize! Boo-hoo!

Friday, May 25, 2007

Journey to the Centre of the Earth (2004) - Monty Halls

Monty Halls presents this two hour special about the Earth's structure. Again, it is not featured on IMdb.

The documentary follows the steps of Jules Verne and tries to analyse the same ideas with modern knowledge. In the process, explains how our planet is made, why it has an iron-nickel core, where does the magnetism come from, how deep humans have reached into the crust, etc. Interesting documentary, although a bit too "popular" for my taste. But it does explain a few things that I didn't know.

I would really like to see documentaries that are full of non repetitive data and that focus on information more than on special effects and deep voice presenters. But hey, in the same "session" somebody sent me a clip from a TV show where a guy was asked what orbits around the Earth, the Moon or the Sun. The guy asked the public and promptly said "the Sun". So, these docs are not completely useless. I just wish there was more.

Thursday, May 24, 2007

Basescu, really stupid or really smart?

You know, even about Bush people have said that he is in reality a very smart man and his obvious stupidity is an act. Could it be that Basescu is the same way? Oh, it seems I need a politics tag for this blog.

Well, Basescu is back in his presidential office, just like Ariel is back in school, and in his very first day as a not-ousted presidentthe very day of the referendum that decides to oust him or not he does this incredible stupid thing. Basically he first goes shopping in a mall (like a normal citizen, mind you) and then he gets annoyed with this reporter woman that kept filming him with her cell phone. So he takes her cell phone. He has no idea how to turn off the phone, so it continues to record, including a conversation between Basescu and his wife in which he calls the reporter an aggressive stinking Gypsy. Then the recording is being analysed by the president's SPP corps (kind of like Secret Service) and the bit about the stinking Gypsy is removed. Little did they know that a recording like that can be restored; and it was and now all this is public domain.

There was great protest against the obvious racist remark, also about the way the president of a country treats a reporter and nobody does anything about it. How stupid can you be to do something like that, right?

But let me bring you this conspiracy theory: Basescu did this on purpose! After the elections he faced a publicity void, one that he either had to fill with keeping his promises (a rather difficult feat for most politicians) or one that had to be replaced with a new stunt. It is already obvious that a lot of the people that voted against his ousting this time are zealots, loyal to Basescu personally, so a little incident like this would not decrease his popularity, maybe it would just show (again) how human and average and of the people our president is. And also shift the attention from the presidential duties to a more common, easy to understand, irrelevant topic. Yet the last thing, the recording that was supposedly deleted then restored, was a stroke of genius. He now got really close to the racist electorate. And, funny enough, the Romanian Press Group decided to boycott the president in the media, thus removing any need of him to do anything. I mean, if you are not on TV or in the press, why do anything? Meanwhile, the press devoted to Basescu would write only the good stuff. And the reporter herself, after receiving an apology note (Basescu is good with notes ) and some flowers, decided not to charge the president with anything.

Could this have a hint of truth in it? Who knows but Basescu and his inner circle, but there is this joke circulating in Bucharest about two Basescu supporters. One of them says "Oh, it would have been great for this thing to happen before the referendum". "Are you crazy?", the other one replies, " people might not have voted for him!". "Nah. He still would have been president, but now 75% of the population would get rid of the stinking Gypsies".

The incident can be easily found on YouTube, but I am not going to give you the link, as it is irrelevant.

Wednesday, May 23, 2007

Agrave bug?

One of my projects involves translation of pages and I have built a general framework that not only translates, but also tries to preserve the capitalization of text. For example, for English to Italian translations, MORNING would be translated into MATTINA and morning into mattina. But I've stumbled into an issue with ACTIVITY.

You see, the Italian for activity is attività, which would be translated into the UTF8 of html to attivit&#192; or attivit&agrave;. Well, then how would one translate ACTIVITY? Maybe ATTIVIT&AGRAVE;? No! Because, apparently, both IE and FireFox (and possibly any other browser) don't count &agrave; unless it is in lowercase, even if, as far as I know, HTML should be case insensitive.

So watch out! Use the numbering system, it is more compatible.

The boy with the Incredible Brain

This is a documentary about Daniel Tammet, a guy that is a savant, but without the loss of social skills. He can make incredible complex calculations in his mind, has a fantastic memory, learned Icelandic in seven days then conversed in it on live TV.

The most incredible stuff is when he does math, though. He "sees" numbers as colored shapes and the operations he does in his brain are plastic, rather than numeric. He just sees some shapes that then reveal digits. As a guy in the film said "he does math without even knowing".

As a film it is not terribly elaborated, but you don't need it to be. It just shows the facts and lets you be amazed. I am getting annoyed with IMdb for not having a lot of the documentary films I am watching these days, so I had to blog about them. Bottom line, this doesn't really help anyone do anything, but it does display a normal looking person seeing the world in a completely different way than most of us and being capable of "superhuman" feats. These guys are the real superheroes, even if in comic books they would have probably been the bad guys. You know, no muscles, not really handsome, lots of brain.

The best part of it is that you can watch it all, right here, on my blog, thanks to google videoYouTube. Isn't the Internet fab?

Tuesday, May 22, 2007

BBC Horizon - Fermat's Last Theorem

I usually comment on films on the IMdb site, but there was no mention of this program episode there. Watching it was much like reading "I am a Mathematician", immersed in a fascinating, yet inaccessible world, the one of professional mathematicians.

I often wonder where do they get the money to sit years on end at their desk to prove a theorem, without telling anyone they intend to. Anyway, the story is about this guy, Andrew Wiles, who had the dream of solving Fermat's last unsolved puzzle and one that Fermat himself wrote he had a beautiful solution to. You see, Fermat wrote some conjectures, some ideas he had, and did not write the solutions, thus failing to turn them into theorems.

A lot of mathematicians struggled to prove them and they succeeded, all but one, a problem so simple to define and yet very difficult to solve: show that there are no natural non zero values that satisfy the following equation for any N larger than 2 : x^N+y^N=z^N.

It is amazing the math that this guy has to explore to solve it. Of course, I understand nothing of it, and the show doesn't try to make anyone understand the math, but the feeling and effort are truly remarkable. A must see for anyone needing motivation to better himself.

You want to watch the film, here it is:

Sunday, May 20, 2007

Space Mowgli (The Kid) - Arkadi&Boris Strugatsky

Russian book cover Space Mowgli is a short novel that describes, much like Solaris, the first contact with an alien race. There is a twist, though, as the alien is a human kid, modified to survive on a planet by unknown beings with unimaginable power.

You can immediately separate Russian scifi from American scifi.
The Russian space exploration expeditions are mostly civilian, led by the smartest and more rational scientist around, acting as the brain of the expedition; the characters are unique and react unpredictably, led by their own feelings or beliefs; their biggest problems are bureaucratic or social and mostly internal in the group.
In contrast, American scifi usually deals with military expeditions led by a charismatic or at least authoritative figure, acting as the heart of the expedition; the characters usually act within a strict set of rules which, if they chose to bend, they do as a group rather than as individuals, their greatest issues being external or technical.
I personally prefer the Russian version.

This particular book explores the way humans understand their own humanity, rather than a true interaction with an alien race. The aliens are there, but they choose not to be characters in the story. Each human character has their own view of things and of how things should go on. Reading the book, one is forced to evaluate humanity together with the crew of the expedition and the ending becomes irrelevant. The inner exploration of the reader himself becomes the story.

Bottom line: nice and introverted. Easy to read and rather short. Lacking a conclusion because their is no need for one. The Strugatski brothers considered this story the closest to their hearts.

Saturday, May 19, 2007

AdSense for charity

People know me as the guy who won't put AdSense on his blog. I didn't do this before, because I don't believe in getting money for something that I would have done for free and I dislike the idea of people annoyed by ads.

However, it crossed my mind the other day that I could get some money and give it to charity. More than that, I could even use it in the charitable that I choose! Like teaching kids to use computer (or at least their brain).

So, I am asking you, dear readers, would you accept ads on my blog if you knew the money from your clicks go to a good cause? Please feel free to add a comment or use the chat to discuss it. Thank you!

Why I feel robbed!


BBC News released an article today, regarding the referendum in Romania about the decision to oust or not to oust the president, Traian Basescu. The picture in the article was very representative and it is the same in this post. That's why I feel robbed! I go vote and I see that this kind of people stole the vote from under me.

But I went to vote anyway. It is my first time (political deflowering?), and I knew it was for nothing just as well as I knew it the times I didn't go to vote, the idea being that even if I will be (again) in the minority that no one cares about, Basescu will look at the numbers and see me there! He will see that some of the people don't really like what he does and how he does it. Maybe this will stop him from going all Elvis on us.

Anyway, to people who are not employed in the budgetary system, this ousting of the president thing was like a good opportunity to watch something interesting on TV for a change. Nothing changed when he got suspended by the Parliament and nothing really changes today. Maybe that will make people see soon enough that we don't need a hero, just a good system.

However, I still fell pissed off because I always get ignored in the votes because of the "people" in the picture. Geez! Use head, don't bang!

Friday, May 18, 2007

Pandora is dead, long live Pandora!

For those of you who didn't hear about it until now, Pandora is a free online music service that tries to detect characteristics of songs and allows you to make your own "radio stations" that play the songs or artists you like and/or songs that are similar to those you like. You have a nice and simple voting system that allows you to say if you like the currently playing song or not.

But lately, some new legislation in the US, making licencing for the Internet a few times more expensive and adding more restrictions for access outside US made them restrict the site. Now you can't listen to music on Pandora unless you are American.

However, there is no way they can be restricted from showing the relations between songs, so you can search the songs for yourself. Here is a excerpt of an email I received from Pandora about allowing access to their song clustering system:
email from Pandora
You can essentially use our Backstage service (http://pandora.com/backstage) as a recommendation tool. If you search for an artist and click on their image, then you will see a list of Similar Artists. If you select an album, then you will see a list of Similar Albums. If you select a song from that album, you'll be presented with Similar Songs, along with 'Features of this Song'.

This is essentially the same information that the tuner was using to find new music for you. The big difference with Backstage is that you won't have any audio.

Sunday, May 13, 2007

BookCrossing Ep.2

I have been reading this very nice blog (in Romanian) called BookBlog, where people talk about and review books. They had a nice initiative of getting people together to swap books. I've decided to go and see how it is.

The result? Man, I'm old! And if so much opinionated and energetic youth, as were the people that came to the meeting, did somehow manage to infest me with their vitality, someone inevitably bumped a chair into me then excused themselves using the polite form of addressing your elders.

The meeting took place at Carturesti, a nice book shop/tea shop in Bucharest, one that has a very nice atmosphere, but lousy service. You see, the whole thing was organised with the approval of the people at Carturesti, but when we got there, no one knew we were coming and were very apprehensive about us moving tables around. Then they've decided to bring a big mug of fruit infusion (improperly called tea) to all of us, as it was too much the trouble of making individual tea pots for each request. I was bent on drinking mate tea and I hate boiled fruits, so it did upset me a lot.

But back to the meeting. The layout (a big makeshift table) did not encourage group discussion, but rather a group of small discussions. I've talked a little with the nice girl next to me, until a lot of her friends came and make it awkward. They all seemed to know each other, more or less, making me feel like an outsider. And I was outside everything you can imagine: size, age group, book interests.

Yes, the books everyone brought were mainly taken from the second hand book shops, not that mine was different, but I could find no single book that caught my eye. Eventually I bought a Strugatski book and left them my beloved "Fisherman's Hope". I do hope someone that knows how to appreciate it fished it home. Or I could have gotten A Mind of Its Own: A Cultural History of the Penis, by David M. Friedman, which was a huge success, although I doubt anyone took it home.

Eventually I got bored, talked a little to the organizer, a very nice guy from BookBlog. He has what it takes to make it in life... that particular energy that is found in both successful businessmen and sales people. Then I left.

At least I had the opportunity to read some more on the way back and at the Pizza Hut place, for now I return to my designated purpose for today, viewing as many movies as possible before the wife comes back. Muhahahahhaa!

Saturday, May 12, 2007

Messing with UpdatePanel to speed up and extend Ajax

I was looking for an answer to the problem of a grid inside an update panel. You see, since the rows and cells of a DataGrid or a GridView are special controls that can't be put inside panels, only in specific parent controls like tables and rows, there is no way to update only a row or a cell of a grid. If the grid is big, it takes a long time to render it entirely, it takes the CPU to 100%, it even blocks the animation of gifs. That results in ugly Ajax.

So, my first thought was: is there a way to update only what has changed? As I was saying in a previous post, a Page is rendered as its HTML string the first time it is loaded and then each Ajax postback makes it render like a list of tokens. The token format is this:

length|type|id|content|


For example 100|updatePanel|UpdatePanel1|<inner HTML of panel of 100 bytes>|

What if I would to insert my own tokens, then? Could I, let's say, change the innerHTML of a control outside of the UpdatePanel? And the answer is YES!

There are 20 token types:
  • updatePanel
  • hiddenField
  • arrayDeclaration
  • scriptBlock
  • expando
  • onSubmit
  • asyncPostBackControlIDs
  • postBackControlIDs
  • updatePanelIDs
  • asyncPostBackTimeout
  • childUpdatePanelIDs
  • panelsToRefreshIDs
  • formAction
  • dataItem
  • dataItemJson
  • scriptDispose
  • pageRedirect
  • error
  • pageTitle
  • focus


Most are not interesting, but 4 of them are!

type:updatePanel
If you add a token to the rendered page string that has the type updatePanel and the id is the UniqueID or ClientID of a control, the content will replace the innerHTML of that control, even if the control is not in an UpdatePanel.

type:hiddenField
If you add a token to the rendered page string that has the type hiddenField and the id is the UniqueID or ClientID of a control, the content will replace the value html property of that control. You can use it on hidden fields, but also on any type of input or html element that has a value. If the control does not exist, a hidden input will be created with that id and then the value will be set. You could read that value after a normal PostBack, let's say.

type:expando
If you add a token to the rendered page string that has the type expando a script will be executed in Javascript that looks like this:
id=content

Example: 5|expando|document.getElementById('TextBox1').style.backgroundColor|'red'|
This will result in the change of the background color of the control with id TextBox1 to red.

type:focus
If you add a token to the rendered page string that has the type focus and the content is a ClientID, then the focus will be set to that control provided that the focus.js script has been loaded. This script is loaded when you use Page.SetFocus. So, in order to set the focus to a control using this method, you must use SetFocus in PageLoad on any control you would like.

Why not use SetFocus, then, and be done with it? Well, because this, as all the methods above work on ANY control in the page, not just the ones in the update panel.

And now the code
using System;
using System.IO;
using System.Web.UI;
 
public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Use SetFocus so that focus.js is loaded
        SetFocus(TextBox1);
    }
 
    // get the token for a javascript property change
    private string TokenizeProperty(string value, string property)
    {
        return string.Format("{0}|expando|{1}|{2}|", value.Length, property, value);
    }
 
    // get the token for a javascript value change
    private string TokenizeValue(string content, string controlID)
    {
        return string.Format("{0}|hiddenField|{1}|{2}|", content.Length, controlID, content);
    }
 
    // get the token for setting focus to a control through javascript
    private string TokenizeFocus(string controlID)
    {
        return string.Format("{0}|focus||{1}|", controlID.Length, controlID);
    }
 
    // get the token to replace the innerHTML through javascript
    private string TokenizeInnerHtml(string content, string controlID)
    {
        return string.Format("{0}|updatePanel|{1}|{2}|", content.Length, controlID, content);
    }
 
    protected override void Render(HtmlTextWriter writer)
    {
        // we only do this in the case of an Async Postback
 
        ScriptManager sm = ScriptManager.GetCurrent(this);
        if ((sm == null) || !sm.IsInAsyncPostBack)
        {
            base.Render(writer);
            return;
        }
 
        // Get the rendered page string 
        // (which should be a list of Ajax tokens)
 
        HtmlTextWriter tw = new HtmlTextWriter(new StringWriter());
        base.Render(tw);
        string content = tw.InnerWriter.ToString();
 
        // Get some meaningless text that changes over time
        string insert = DateTime.Now.ToLongTimeString();
 
        //Change the inner html of Panel2 and some 
        // table cell with the id 'testTD' with the string
        content += TokenizeInnerHtml(insert, Panel2.UniqueID);
        content += TokenizeInnerHtml(insert, "testTD");
 
        // Set value of TextBox2 to the string
        content += TokenizeValue(insert, TextBox2.UniqueID);
 
        // change the background color of TextBox2 to red
        string property = string.Format(
            "document.getElementById('{0}').style.backgroundColor",
            TextBox2.ClientID);
        string value = "'red'";
        content += TokenizeProperty(value, property);
 
        // Set focus to TextBox2
        content += TokenizeFocus(TextBox2.ClientID);
 
        // write the content with the extra tokens
        writer.Write(content);
    }
     
}



Of course, that doesn't solve my initial problem, of speeding up the Ajax rendering of large grids. That's because, even if I would solve the ViewState issues and the quirks that are bound to appear, I still can't change the innerHTML property of tables or table rows, as it is a readonly property.

So where am I to use this? It's easy: first of all, put a button (and only a button) inside an UpdatePanel. Any click on that button will trigger an Ajax postback, but will send a minimal amount of data. Then, put outside the UpdatePanel a Panel. Now you can override the Render of the page and on every Ajax postback, add whatever HTML you want to that panel. If you want to do it from javascript, put the button in a div with style="display:none" and then trigger the button click whenever you want to cause the postback. I am certain that for large readonly grids, that is a way faster method than the putting the grid inside the updatepanel.

To do this the traditional Atlas way you would have had to declare a web service, and then to set a javascript onclick event on the button, that would have executed a WebService method that returned a string, and manually change the innerHTML of the panel.

It happened again... Stargate is dying

My preferred method of watching SciFi is to download it from the Internet. I have these shows that I watch religiously, even if they are not all very good. But given the low quality and scarceness of scifi these days, that's all I've got. One of these shows is Stargate, a series that spun from a Kurt Russel movie and that managed to reach 13 seasons together with its offshoot, Atlantis.

Anyway, my method is to watch for the show air dates, then look for it on the Internet the next day. However, once I happened to find the entire Atlantis series for a few weeks way before the release date. Now it happened again. Stargate and Atlantis episodes till July are on the net. I am now watching them all. The quality is way down, the self-irony of the writers has gone way up, but they are there. What's going on?

Update:
Oh, damn! Having just seen Stargate episode 20 of season 10, I've learned that there is not going to be a season 11 anymore. That being the reason why the show has been released online, probably. SciFi Channel cancelled the show. MGM, the owners of the Stargate francise, promised two Stargate movies, as you can see in this article.

Devastating as this is, considering the total lack of climax or seriousness of both season 3 of Atlantis and season 10 of SG1, ending Stargate to turn it into something better might not be a bad idea. I just lack the confidence that profit driven corporations have the right stuff to create something that should be art and brain driven.

Ah, that's that. Another decent scifi show bites the dust. I'll be watching Battlestar Galactica till it gets completely Lost (pun intended) in new "spiritual" developments.

For the melancholics, watch these videos released on YouTube as 200th Stargate special and this little video, which is a fun one, and I believe fits perfectly with the topic of this article:[another youtube deleted video, guh!]

Friday, May 11, 2007

The place where we are alone with our thoughts.

I had this English teacher in high school. She was very nice, and I also enjoyed her classes, mainly because I already knew English and because she did the unthinkable, she said she would pass anyone who didn't want to learn English, provided they didn't come to disturb the class. She was a good teacher.

Anyway, one day she started talking about the place where she is alone with her thoughts and she can feel calm. I, being even less tactful than I am today, replied "Oh, the toilet!". She felt offended, because she was talking about church. But the scene stuck with me. And sometimes, on the toilet, alone with my thoughts (and my cat - so not quite alone) I recall her reaction and my own. You see, I understood why she felt offended, it was because I compared a place she considered clean with a place she considered dirty, but I also thought about why a woman that believes in a deity that made us all considers dirty something like we do by design and clean something we do inside a building with trainers and specific rituals that are not by design.

And that got me thinking (hmm, is my blog the best thing since toilets?) about the general situation where we put so much value on an external thing, while the value itself is internal. And I am not talking here only about religion (which by now you know I consider stupid) but also about everything else. Fashion, for example. It's the human equivalent of monkey see monkey do. It's putting value on a thing, person or trend simply because you feel like it. So it's something that has internal value, you gave it importance, but you attached it to something external.

Take another example: the things we get attached to, apparently by brain design. A child is being told that his favourite toy has been cloned into a perfect copy. And he is given "the clone", which is actually the same object. And the kid wants his toy back, not the copy. And the examples are infinite.

I think it's because in our brains, things are not things, but intersections of meanings. A red pill is the intersection between "pill" and "red", themselves intersections of other concepts. The church is nothing but a silly building, but it has meaning, for it gives peace and solitude for a while. So does a bathroom. So does this blog. But there comes a time when we realise that the intersections don't add up. It's called thinking, and it's the equivalent of Bonzai trimming of one's thoughts. We start cutting away the lines that don't make sense or that hurt us, while we strenghten the ones that give us sense and pleasure. We start with a thin scaffolding of chaotic wires and we bring it to a sturdy iron bar cage where our thoughts are stable and protected. That is the real place where we are alone with our thoughts, and we are alone because we don't allow anybody or anything in.

So trim carefully, some thin wires are good while some iron bars are bad.

Thursday, May 10, 2007

C# indexed properties - inheriting from VB

VB has a feature that it missing in C#, that is indexed properties. There are various methods to emulate this behaviour in C# and here is a small article about it:
Three C# Tips: Indexed properties, property delegates, and read-only subproperties.

However, a problem arises. What happens if you have a library written in VB and having indexed properties and you try to use it in a C# project? Well, it works, and the generated code is something like:
 public override bool get_PropertyName(string index)
{
}
public override bool set_PropertyName(string index)
{
}


Somehow, this compiles :) Anyway, the problem now is that you can't use the VB code that used to use the VB library if you convert it to C# like this. I haven't found any way to do this:
VBLib(with indexed properties)+VBApplication(inheriting or overriding indexed properties) -> C#Lib(translated)+VBApplication(unchanged).

How idiocy leads to death.

I was too tired to work this morning, so I got on Digg to read what people were reading.

And I've seen some interesting articles, like for instance one about Starbucks. They started this campaign in which people write stuff and the company writes it on coffee cups. One man dared to question praying in God, based on the assumption that people are rational beings with a strong will. Obviously that assumption was wrong, as some chick got 'offended' and started bitching about the text. It got me thinking, you know, of why nobody cares if I am offended by all the God crap I hear everywhere. Some guy said on TV a few days ago that in Romania 99.8% of the population are believers. Yeah, right! Like, they are not full time declarative atheists. How easy it is to spin things.

Anyway, back to interesting topics. There was one about how lawyers are behind the times. They write these 'cease and desist' letters, with a threatening language that no one can ever sympathize with, but nowadays these documents get on the Internet, for everyone to read. And hate. So they cause public relation troubles for the companies they were trying to protect. I don't really see a problem, though, as there are a lot more lawyers ready to sue these lawyers so there you go.

But even religious and legal idiocy fades compared to the total mind numbing dumbness of these two Vegan parents. Apparently, they've decided to make their 6 week old infant a Vegan from birth. They fed it soy milk and apple juice. The baby died.

How gullible are we?! How can we believe in all these stupid things and advertise them as indie revolt against 'the system' or 'healthy' lifestyle against the food corporations and so on? Is it so hard to mind your own business and let other people think and decide for themselves?

Tuesday, May 08, 2007

There is a fly on my blog!

Apparently, the summer has brought all kind of nasty insects. A fly has gotten loose on my blog! It's a bfly! Until it finds something useful to do (like allowing people to search stuff or going to the interesting bits or acting as a friendly button) and until it will find friends to join it, it will just annoy us. Alas! It is an unswatabble fly.

Cross browser inner width and height of html documents

I wanted to create this Javascript fly that would... well... fly on the screen. So the first thing I did is create an empty html, put a script tag in it, add some init function to the body and then write the code.
First problem: how to get maximum height and width of the page in both IE and Mozilla. I found a way, then I added a more complex html code, like a DOCTYPE. Well, amazingly (duh!) it didn't work. Finally, after trying several options, I found this code to be working in both browsers and in both doctypes (or lack of). Please report any issues with it, so I can fix it. Thank you.

function maxHeight() {
var h=0;
if (window.document.innerHeight>h)
h=window.document.innerHeight;
if (window.document.documentElement.clientHeight>h)
h=window.document.documentElement.clientHeight;
if (window.document.body.clientHeight>h)
h=window.document.body.clientHeight;
return h;
}
function maxWidth() {
var w=0;
if (window.document.innerWidth>w)
w=window.document.innerWidth;
if (window.document.documentElement.clientWidth>w)
w=window.document.documentElement.clientWidth;
if (window.document.body.clientWidth>w)
w=window.document.body.clientWidth;
return w;
}

Saturday, May 05, 2007

Crystal Reports "Query Engine Error"

You want to create a report with Crystal Reports and you create that weird ADO.Net DataSet, then you add a Crystal Report, you select the tables you want from the created DataSet, then you drag the Id references to create the table links, you go through all that weird Report Expert, you add a Crystal ReportViewer to a Windows Form and you press F5! And you get "Query Engine Error".

Well, two main reasons for this are explained in this nice article: "Query Engine Error" With Crystal Reports .NET, but you just created the report, there is no way you changed the XSD or the name of the tables.

I tried a lot of things until I found out what was going on. You see, I had this tables that had an "Id" column and a many-to-many table that had "UserId" and "MenuId" columns. In order to link them, I did what I also did in the XSD, I dragged the Id (primary key of each table) to the UserId and MenuId columns. That was the problem! You have to do it the other way around, drag the Foreign Key columns to the Primary Key columns.

Hopefully, you would have read this article before wasting hours to find out what the hell is that error and where it comes from... It happened to me with Crystal Reports 9.0 and Visual Studio 2003.

Oh! And don't bother to link the tables in the DataSet XSD, since Crystal Reports seems oblivious to that.

Crystal Reports - Insert Field is disabled

I am working on this windows app that uses Crystal Reports. I've never used it before and I thought "Hey! I could learn something new". So I opened this .rpt file in Visual Studio 2003 and I got the most incomprehensible interface ever. I mean, I will have to invest some hours just to understand what the report interface is all about.

But anyway, I thought I would take an existing report and then just change something, like adding a new field. I went with the mouse on an empty space, right click, context menu, Insert... I could insert text. I could insert Special Fields (report data like number of the page, creation date and so on). I could insert Fields. Only that option was disabled! I've tried every option in the context menu, no avail.

Finally I've decided I am to dumb to figure it out, I went to man's best friend: Google! The answer found in an obscure forum was:
- Go to View (in Visual Studio 2003)
- click Other Windows
- click Document Outline

Now a Field Explorer window is open and I can see all fields and drag them to the report. That was it! :-/

Escaping Regex replace patterns

When one wants to replace a text, say, case insensitive, one uses the .NET Regex class. In order to make sure the text to be replaced is not interpreted as a Regex pattern, the Regex.Escape method is used. But what about the replacement string? What if you want to replace the text with "${0}", which in Regexian means "the entire matched string" ? You need to somehow escape the replace pattern.

I have no idea where to find this information on MSDN, although I am sure it is hidden somewhere in all that Regex labyrinth. Here is the link on MSDN: Substitutions

So here is the info: You only need escaping the dollar sign, so the code would look like this:

Regex reg=new Regex("Text to replace",RegexOptions.CaseInsensitive);

string s="here is the text to replace";

s=Regex.Replace(s,"$${0}");

Now the value of s is "here is the ${0}".

Mitsubishi Colt is our final (hopefully?) choice!

Yes, we went to the Mitsubishi dealership. It was nice to actually have someone talk to us and give us all the details, thing that did NOT happen to us at any showroom except the Seat part of the Skoda showroom.

As a side note, I tried entering the Pajero, the Mitsubishi SUV and... I couldn't fit. Not even a tortured position. The front seat moves electrically (yes, some people are so lazy that moving their own seat takes too much. My foot was turned at 90 degrees, my leg could not find a proper position and it wouldn't pass past the steering. It was horrible. But then it dawned on me: tall people don't buy SUVs! The usual suspects when we're talking SUV drivers are fancy women and small, fat people. You don't buy an SUV because you need it, but because it compensates for some shortcomings (pun intended).

Now, back to the car we preordered!! The Mitsubishi Colt is a normal droplet shaped hatchback. But I could fit in! A little effort was required on the driver's seat, but it was ok. More than that, I am sure the rails of the seat can be lengthened or at least moved a little back. The back seats also move back! You can also collapse them or even remove them entirely, giving a huge space in the back if there are only one or two people in the car. It also has automatic gear shifter, which is terribly difficult to find in small cars (or any cars for that matter) in Romania; yet, unfortunately, only the gasoline car models. No matter. I was looking for a gasoline car anyway. The color choice was rather poor, I had to choose between white, black, gray and red nuances.
carmine Mitsubishi Colt
So, we preordered the car! A carmine Mitsubishi Colt Hatchback, 1.3 Gasoline, Automatic/manual gearbox (that means you can switch between them whenever you like).

Now, all we have to do is get the money (from a bank!) and pay a lot of money every month for 5 years. Wish us luck!

Thursday, May 03, 2007

Tuesday, May 01, 2007

Ban water! It's eeeeevil!

No, I am not talking about Dark Water, either. I am talking about water. Penn and Teller went to a rally of some sort and asked people to ban dihydrogen monoxide; water, that is...



So, if you are reading this, dear environmentalists and conspiracy theorists... don't listen to everything that sounds good, because most of it is not, even if it seems to enter the same agenda as yours...

The holograms are here!

A while ago I wrote this entry about an innovation in sound technology that will probably change the way we think of sound.

Today I am presenting a video technology I witnessed at the mall! Yes, the mall, that dreaded place of overpriced junk and overdressed bimbos. Overpriced, too! :) Anyway, I was watching this Pepsi commercial on a big TV like device, where a can of Pepsi was rotating showing its full cylindrical glory. Only that it felt out of focus. My eyes were kind of sore watching it. Immediately the image changed to a ball that came towards the screen and then... went through the screen!

It worked from almost every angle, without being a holographic thing in the middle of the air, but more of an optical illusion. Thinking of the faithful thousands of people reading this blog every day, I remembered the little link on the side of the device: www.x3d.com, with their device called MultiView.

The image is not as clear as one would want. It's like continuously vibrating or something like that, but the optical illusion is great! I saw people passing by the device and trying to put their hand through the "flying" objects.

Here are a few links from Wikipedia about the subject:
Volumetric Display
Autostereoscopic