Friday, June 29, 2007

Creating ASP.Net Controls dynamically in Page_Load

I've spent two hours today trying to understand why my application works. I mean, I was glad it worked, but, based on my understanding of the ASP.Net cycle, it shouldn't have.

Long story short: in Page_Load I was instantiating and adding to the Page Controls collection some controls. To my astonishment, the postback worked! With events and everything. Even worse, even if the controls were being created every time (independent of IsPostBack) and the data was always added from the database, the postback data was overwriting it!

As far as I knew, the postback data is being loaded before the Page_Load event. And when you change something in the Page_Load, it stays changed. But things are different with dynamically generated controls. My guess is that the Page_Load method is being executed for the page, then recursively for the child controls. If a control has not yet retrieved it's postback data, it tries again.

Yet, if you try to do the same in a button event or in Page_LoadComplete, it doesn't work.

So, if you dynamically add the same controls in the Page_Load in between postbacks, the postback data will be saved and the events will fire.

Thursday, June 28, 2007

Bruce Campbell about indie and B movies

This video is hilarious just because it is so true. B movie legend Bruce Campbell is telling them as he sees them. Don't miss his upcoming movie "My Name is Bruce" in which he stars as himself battling demons! I can't find it anywhere for now, but I will keep searching.

Update: I found it, having been delayed for a year for redoing some scenes with extra budget, but it failed. :( I almost did not find it funny. Better luck next time.

Also, you might find useful the information that he played in all three Spiderman movies. And, as he says himself in another youtube clip, if he didn't name the hero in the first film, the entire franchise would have now been named "The Human Spider", while in the second, as the doorman of a cinema in which Spiderman did not enter, Bruce Campbell is the only person that ever defeated Spidey! :)

This man is just hilarious, watch this clip and all the Bruce Campbell Movies you can get your hands on.

Update: trust lawyers to screw with my blog. I had to replace the youtube video above with one from a live performance. Pretty much the same idea, only the interview was funnier and more complete.

Wednesday, June 27, 2007

Setting vertical scroll property in selects with Javascript

I've updated this page a few times, adding more optimizations, so get the last version.

I was asked to find a way to maintain the vertical scroll in a selection box (that is a select html element with a size bigger than 1). I checked to see what property was changing when I was scrolling the select and I noticed that scrollTop was the one. So I used

Well, this works fine in FireFox and apparently works fine in IE7, too. However, in Internet Explorer 7, if you click on the up/down arrows of the select scrollbar, the scroll resets to 0. Worst than that, in IE6 you can't even set the scrollTop property. You don't get an error, but it doesn't work.

One suggested solution for people that tried the same thing is to set the size attribute to the number of options, thus getting rid of the select scrollbar, and place the select in a div with fixed height and overflow auto. It will look like a select listbox, but the scroll will be from the div and easily changed. I didn't choose this solution, basically because I felt it was cheating.

So, I've applied another solution, one that changes the selected item so that the select element scrolls itself to a position as close to the desired vertical scroll position as possible. Then, I set the scrollTop property, so that it goes at that exact position in IE7 and FireFox. If one clicks the up/down scroll arrows in IE7, the scroll position resets to the one found by the selectedIndex, not 0. And it works in IE6, too.

Here is the code:
JS Code - vertical scroll a select element
function setSelectVerticalScroll(sel,y) {
if (!sel||(sel.options.length==0)) return;

// remember the selectedIndex (for single selection selects)
var selectedIndex=sel.selectedIndex;

// find the item that selected will yield
// the best match for the required scrollTop
var best=-1; var bestMatch=100000;

// try to guess the starting index based on select height
var optionHeight=parseInt(sel.size)
var startIndex=parseInt(y/optionHeight);
if (startIndex>=sel.options.length) startIndex=sel.options.length-1;
var c=startIndex;
while (c<sel.options.length) {
var selected=sel.options[c].selected;
if (Math.abs(parseInt(sel.scrollTop)-y)<bestMatch) {
// best match has been found, no point of going further
if (Math.abs(parseInt(sel.scrollTop)-y)>bestMatch) break;

// try to jump to the right index
var inc=parseInt((y-parseInt(sel.scrollTop))/optionHeight);

// select best match, to force scrolling
if (best>=0) {
var selected=sel.options[best].selected;

// set the selection back
if (sel.selectedIndex!=selectedIndex)

// now this should have been enough,
// but it doesn't work in IE6 and it's bugged in IE7

Warning! This will not work if the select is hidden by way of display=none or visibility=hidden. Also, for large selects, it will look funny scrolling through all the options. Optimizations can be applied, that try to find the correct selectedIndex or stop after the scroll position has been found (like in this example) or that search the best scrollTop match by dividing the options in two parts rather than taking them one by one, etc.

Star Wreck, a brilliant example of garage film making and a really funny comedy, too

I've accidentally stumbled upon Star Wreck, a Finnish film that parodies Star Trek and Babylon 5. The special effects are as good if not better than the original shows, the parody is cool and very funny and the fact that the film was made by some unknown guys in a makeshift studio gives it a lot of extra points. Not to mention that this is one film Danezia is very unlikely to comment on :D

What's even better is that the movie is freely downloadable from the net, so the major drive for the film was fun! When did you last see a movie made for fun, not money?

Update: Spoken too soon, apparently. After a while the film was released on DVD and removed as a download. But still, while it lasted it was cool.

All fans of Star Trek and B5 will love this.

You can also watch it here, but it's lower quality and maybe it will disappear after a while. Enjoy!

Monday, June 25, 2007

About life...

This is a video I've found randomly browsing the net. Previously I did search for it, but only on vague references.

What is it about? Steve Jobs gives a very cool speech at Stanford University, cool because it advocates following your heart and not settling on someone else's ideas of how your life should be. He basically goes in front of so many Stanford graduates and tells them that the things they learned there and stood by were nothing compared with the things they felt needed doing.

I really think that there must have been a lot of angry teachers after listening to Steve Jobs telling their students that he dropped out of college and that it was one of his best life decisions and that they should ignore all the brainwashing they had to go through to get to their graduation

Watch it. It is worth it.

Saturday, June 23, 2007

The downside of capitalism and the Americanization of Romania

I've just seen two movies: Sicko and Maxed Out, which describe, each in their own way, the issues arising from aggressive capitalism like the one in the USA. Some people are really quick to jump with the "oh no, it's socialist propaganda!" line and ignore the message, but, if you think about it, there is nothing wrong with some socialist propaganda now and then, since we are bombarded with capitalist propaganda every day in the form of ads and commercials and corrupt government propaganda.

I will make a (hopefully) short detour and talk about my perception of capitalism and democracy. I've always felt that there is something wrong with them, but could not exactly pinpoint it. Well, democracy is easy: the majority of people are idiots, therefore the rule of the people means you are lead by idiots. But capitalism? What is wrong with being competitive? Isn't that the only guarantee of performance? And then it struck me! Competition is not the problem, it's the performance! It's about one's definition of performance!

And now I return to the two movies, of which Sicko tells of insurance companies that pay doctors depending on how many people they refuse treatment to and Maxed Out shows how people are graded by the income they bring to the credit card companies, meaning that people with a high risk of being late on payments or even the ones that are not capable of paying are their main income sources, since they pay all those additional risk interest fees and late payment penalties.

Because this is grading performance. What it would be like for the police to try to catch mainly the people that will post bail and then run? What would it be like to have firemen being promoted on how little water they use? And since performance is now more and more defined exclusively in economic terms, who will inherit the world? The economic performers! banks, insurance companies, salesmen, marketeers, the ones that put everything into financial equations and care nothing about anything else.

The police and fire department, as brilliantly observed by Michael Moore in Sicko, are social services. In countries like the UK, Canada, France and even Cuba, getting professional medical help for your injuries for free (in other worlds universal health, health service socialization) is available. And doing great!

And now I look at Romania, I see the same thing that bothers be about America: everything is sold and bought. You need money to pay hospital bills, a lot of them not being covered by medical insurance, even if you have one; pharmacies payed by drug companies to sell their expensive products instead of for getting the right medicine to the right person; governments, no matter their political color, being bought and payed for by wealthy industrialists; banks and financial services effectively robbing you blind.

Oh yes, I agree, a socialist system does not work, but some services must be social. I would imagine welfare, health and education should be social services. The state should pay for them from taxes we all pay. No matter what company does the service, its income would originate from the state, rewarded by the real performance of their service: people not dying from poverty and disease, people cured from illness, people getting a high education and paying higher taxes because of it when their time comes.

But how can this happen in Romania? The government is so impotent and corrupt that it only does what large corporations, banks and political interests tell it to. And when people have had enough, here comes a superhero saviour, manufactured to look like the thing the people want by the very people that rob this country dry. I would hate to see Romania becoming a pale imitation of the US, a poor country with a cut-throat capitalism that benefits thieves only.

Friday, June 15, 2007

How to get rid of 'String or binary data would be truncated', divisions by zero or arithmetic overflows in T-SQL

In MS Sql when you try to insert or update a field value or parameter that is bigger than the defined size you get String or binary data would be truncated and the query fails. In order to get rid of this, you can use SET ANSI_WARNINGS OFF. But, warning (not ANSI :) ), there are some drawbacks that you have to be aware of before using SET ANSI_WARNINGS OFF :
  • putting SET ANSI_WARNINGS OFF in a stored procedure will force a procedure recompilation each time, so it is better to set it before the execution of the stored procedure
  • this setting will disable the indexes, so queries might run slower
  • no error will be generated when a division by zero appears and a null value is returned (this might not sound as a drawback, but think that you don't always want to return null in some cases and you want at least to be aware of them)

- disables the warning message from aggregated functions when finding null values
- returns null on divisions by zero and arithmetic overflows
- values are truncated when the length of the data is bigger than the defined size

If you want only part of the functionality above, also check SET ARITHABORT or SET ARITHIGNORE.

Also here is a list of how these options affect each other.

Wednesday, June 13, 2007

Il Nome della Rosa / Name of the Rose - Umberto Eco

I have finally finished reading this book. I've tried reading it in Italian together with English, but after a while I've only read the Italian version. My first impression was that publicists do more than just print books. There were several passages that were missing from the English translation, for example. I also felt that they were related in that they were more aggressive against the idea of the Church. Although I can't say for sure.

I also had difficulty reading the book after seeing the movie. I've heard a lot of people describing the movie as a pale imitation of the book. Bullshit! The movie was great: the adaptation, the casting, the music, the directing. The only thing lacking from the movie was the political dimension, the battle between religious factions and the description of the political situation of the time. Which is a lot, but is not really relevant to the idea of the book.

So, if you have seen the movie, you might find it difficult to read the book. If you haven't yet, I suggest you read the book and certainly watch the movie afterwards. There is a certain magic when Sean Connery's accent overlaps with Ennio Morricone's music :)

Anyway, the book describes not only the murders and the process of finding the killer, but also a world where books are copied by hand by people who can speak Latin and Greek, but not the vernacular, the language of the people, then they are hidden in great libraries with access restricted by religion. A time where the inquisition's main purpose is to get rid of troublesome Christian cults with their own interpretation of religion, gathering momentum and followers just like a political party would. A world where the Pope and the Emperor have great powers and fight each other using any means necessary. A period when the universities are slowly replacing the abbeys as places of learning.

All in all it is a good book. I don't think the Italian language brought a lot more to the book. I was quite satisfied with the English translation and there isn't much word play in the original text. There are some passages where the author seems unable to stop listing items, making them tedious, but overall the style is easy to follow and the logic good. The end moral is that the pursuit of knowledge is more important that the knowledge itself and that evil lurks even in the most holly of hearts.

Tuesday, June 12, 2007

Dark Messiah of Might and Magic

Dark Messiah of Might and Magic, a great game!

Oh, I am weak. I'd already decided not to download the game from various reasons. First of all I didn't have the greatest computer to play it on, then the fact that it would totally consume me and take me away from work or any intelligent activity; third of all, I didn't have the space. Well, the hell with it, I've taken the hard drive from another computer, deleted all the movies, downloaded the game and played it at lowest graphics. Luckily (or unluckily) I've finished it in about 5 days. Here is my experience.

I had huge expectancies regarding this game. Made by Arkane Studios, the brilliant makers of Ultima Underworld (AND NO! I DON'T MEAN ULTIMA, BLEAH!) and Arx Fatalis [blog entry], both greatly intelligent games, but in a Might&Magic universe (I've loved the might and magic series, even from Might&Magic 1 - AND NO! I DON'T MEAN HEROES OF MIGHT AND MAGIC, BLEAH!). Also I have seen the videos of gameplay and also noticed a multiplayer mode, something like Counter Strike, another sick obsession of mine. So Arx Fatalis + Might&Magic + Counter Strike = the greatest games of all times!

Wrong! Actually, the entire game is like Arx Fatalis II, a project that Arcane Studios have started but never finished. The Might&Magic name is completely misused, since the game is quest based, without open spaces or branched game play. The fighting is pretty cool, but on my NVidia FX5200 it showed white instead of water when swimming, a transparent checkers board on the screen when using magic items and a white rectangle when animations were played. Maybe that last one is from a glitch in the DVD image.

That doesn't mean it is a bad game. Au contraire! the 3D engine is great and the feeling and the story are almost identical to Arx Fatalis. The interactions with the environment and some of the innovations are extraordinary. However the complexity of the game greatly diminished, kind of like the decrease in complexity one sees from the 1-5 series of Might&Magic to the 3D version starting with 6. The quests are real no brainers and there aren't many creatures in the game. Somehow, the electric flying demon-octopus had made its way all the way from Ultima Underworld :) but other than that you only have: goblins, Orcs, soldiers, tough soldiers, necromancers, leeches, cyclops, pao-kai (corrupted dragons), undead zombies, undead cyclops and undead pao-kai, a huge spider and a lot of small and annoying other spiders and ghouls (which are the most scary and dangerous if you ask me) in 10 levels of fun.

I mean, where are the undead goblins? I've never seen them in any game!

Anyway, some innovations deserve a lot of credit:

The rope arrow (shoot an arrow and climb the rope) which would have been even better without the bug that made me fall through walls or get stuck there.

The fact that you can pretty much grab anything and throw it in your enemy.
The interaction with the environment (throw enemies off cliffs, into fires, into spikes, push coffins and statues and barrels on them, destroy wood supports or cut ropes to unleash hell on your enemies. This would have been great if you wouldn't have had to hit a ghoul several times with the coolest weapon you have to kill them, but you killed it instantly if you kicked it into spikes.

The way that the character evolves through your choices, making you an assassin, a wizard or a fighter depending on the usage of your points. Unfortunately you only win points when finishing quests, not when actually defeating enemies.

The head shot bonus.

The general dynamic of the game, which means smart monsters run when they are badly hurt, hide themselves behind obstacles if they can't reach you so you wouldn't just shoot them with a bow several times, etc.

Ok, spoilers follow! I will be telling the story of the game.

You are some magician's apprentice, before he sends you on a quest to carry a crystal to a friend, he implants you with a helper (a female voice) that gives you a lot of suggestions (too many if you ask me). She is also very sensual and making sexy remarks, so that means she has to be evil :-/ Anyway, you get to this city when the city is attacked by necromancers, they steal your crystal, you have to get the crystal back, find a skull, the necros take the skull, you have to get it back and the moral of the story is that... you are the son of the strongest demon of them all, imprisoned by the seventh dragon by using the very skull everyone has been after.

Now, you have options: purge yourself from the evil implantation in your head or not. Keep the good girl alive or not. Use the skull to imprison your father forever or to set him free. There are different endings for this, and the video below shows them all.

Very basic story, yes? A lot like the one in Arx Fatalis where you also were a pawn of ... everybody. And you also don't get any sex in this one. Plenty of violence though. The animations aren't very cool either. It seems as if Ubisoft bought the unfinished Arx Fatalis II and gave it a shine, then released it as fast as possible. Having morons like me playing the game without paying could also explain the lack of extra details.

My suggestion is to get the charm spell as soon as possible, as it gives you the opportunity to make enemies fight each other while you watch. :) Of course, assassin is cool, too, but I hadn't had the time to test it yet.

Bottom line: Not the greatest game ever, but still one to show everybody else how a game should be conceived and how important innovation is.

The different endings of DMOMM:

Friday, June 01, 2007

The long run

There is no clear formula for calculating the concept of success because success can only be defined from factors like goal and duration. For example, a guy might be considered successful in getting a girl, but a failure if the relationship does not work and they split up in terrible anger or grief. In the long run, it was not a good idea to get the girl.

The same theory can be applied to any problem. For example outsourcing. In the short run, the company wins, because they reduce the costs of employment. They might even win in the long run, but the money go outside the country, diminishing by a little the success of all companies in the same region. In this case, the long run might prove that making a united front is better than scattering the resources between competing factions. Or maybe not.

The other day I was thinking of oil. A friend of mine sent me this link to a site that talks about the coming of an age in which oil is no more. It is coming soon and it basically means a dramatic (and probably violent) scaling down of world energy output. In the same time, a Romanian minister declared that he intends to push for investments in the gas sector, like finding new natural gas reserves.

And something blinked. If the oil and natural gas are scarcer and the price is likely to go up very quickly and dramatically, wouldn't that mean that keeping the oil in the ground would be a far better deal? Why extract it now, when the US and OPEC are still managing to keep the prices to a decent level (through a lot of indecent actions)? Wouldn't it be better, in the long run, to wait until the price skyrockets and everybody else is left without? In the short run, oil companies and ministries make a lot of money from it, but in the long run, they could make a lot more. Yet the people that are in charge now probably won't get anything. So they greedily suck it up and sell it.

Now, since I've defined the problem, I should think of a solution. And I think the only solution here is this: people that have charge over the oil in the ground should be able to sell the rights to the oil once it has been extracted. That means that I could sell some guy the right to the oil underground, even if I am not extracting it. Maybe even a nice clause that if the oil is not extracted in time, the guy could get his money back with a considerable interest as penalty. I believe it could work, since the price of the underground oil is likely to increase in time.

Thus the oil in the ground is transformed into money, independently of the extraction process. The extractor will get a percentage of the price of oil, then pass it to the owner or find some other arrangement to sell it and split the profits with the owner of the oil. I think it's a great idea to make money from oil without burning it. The only drawback is that someone could invent a better and cheaper and cleaner energy source. Bummer! :)

DoubleSpeak and euphemisms

I've come upon this PDF file that explains what an euphemism is. I moved then to doublespeak, which is already a highly talked and blogged about term (679000 googles) because it is a form of euphemism used by politicians and press to change the emotional impact of information or even distort its sense. Stuff like "Collateral damage" to replace civilian death or "physical persuasion" used instead of torture.

Here are some useful links:
PDF file on euphemism
Doublespeak at Wikipedia
Also very interesting is the discussion on the article on doublespeak, which some call biased.
A funny rant about doublespeak and the US foreign policy when it comes to wars that are not wars