DCSIMG
December 2007 - Posts - Sig-

Sig-

Code and stuff.

December 2007 - Posts

How do YOU use your datacontext ?

Well, this will be a very short post, and a very simple one, really.

I've just started working on my first _real_ app with linq (I know, a shame, isn't it...), and I was looking to manage my datacontext, so that I wouldn't have to create a new database connection for each query... so I came up with this :

public static class DataContextWrapper<T> where T : DataContext
   {
      public static T Instance
      {
         get
         {
            if (HttpContext.Current.Items["request"] == null)
            {
               string connString = ConfigurationManager.
                                 ConnectionStrings[0].
                                 ConnectionString;
               T dc = typeof(T).GetConstructor(
                                    new Type[] { typeof(string) }).
                                Invoke(new object[] { connString }) 
                                    as T;
               HttpContext.Current.Items["request"] = dc;
            }
            return HttpContext.Current.Items["request"] as T;
         }
      }
   }

And the usage would be something like this :

   MyDataContext dc = DataContextWrapper<MyDataContext>.Instance;

Your thoughts ? How do YOU use it ?
Posted: Dec 31 2007, 08:22 PM by silver83 | with no comments
תגים:

re : Developer Challenge

This is an answer (attempt) for Dror Engel's dev challenge (here - hebrew). I will translate his challenge according to popular demand :)

Well, Dror, assuming that in your DB table you only keep the sum of each transaction and it's date, and each account starts off from a balance of 0, then the following SQL query can give you the "starting value" to work with in each page (the balance at row "one after the last" relevant to the current page), given the current page number and the page size being used :

 
SELECT SUM(ActionSum) 
FROM 
    (SELECT 
        row_number() OVER (ORDER BY actionDate DESC) as RowId,
        ActionSum 
     FROM actions) as history
WHERE RowId > (@pagesize * @pagenum)

This syntax works on mssql 2005 and above,  but I believe there is similar syntax for oracle. You could do something similar in sql 2000 but that would require a temp table, whether it's a table variable or a real one.

I hope this helps in any way, and that I didn't misunderstand :)

I don't really like doing this kind of stuff per page (i.e. if your table gets REALLY big, this might get heavy... ), so I _would_ keep something extra in the database, even if it's the current balance, or an ugly calculated field for that matter.. but that's just me :P

** comment :  this could be optimized a bit for larger tables, using TOP + reversing the order by + precalculating the total amount of pages, but since you are talking about approx. 300 records, this should do.

Posted: Dec 21 2007, 10:43 PM by silver83 | with no comments
תגים:

Quote of the day...

From one of my favorite bloggers, Joel Spolsky :

"Managers exist to get furniture out of the way so the real talent can do brilliant work."

Well, it's a bit out-of-context, (see original post), but still :)

Just Moved In...

Well, I've just moved in to blogs.microsoft.co.il, and for now everything is all nice and fuzzy inside.

I've imported some posts from my previouse blog for comfort (hate the feeling of an empty blog)...

Wish me luck at my new home...

Academies in Israel - College vs. University

It's amazing how time can change your perspective.

Three years ago, approaching the end of my army duty, I was already certain that I want to start my academic studies as soon as I can.

Contrary to so many others, taking a long vacation after their army duty to "see the world" (i.e. thailand/ india) and "clean your head" (i.e. check how much weed the human body can endure) I was pretty certain I want to finish off with my studies first.

I was determined that a B.Sc. at one of the top universities is my goal. No matter the cost of comfort or effort. The word college was out of the question.

In a nutshell, it came down to packing up my stuff and moving down south, to study at Ben Gurion university.

Suddenly, it seemed to be a bit too much. Giving up the comfort of home, the proximity to Tel Aviv, the concept of being so far away from my great love from back then... so I started looking for alterntives. Just in case.

In the end - I enrolled at Afeka, the Academic College of Engineering in Tel Aviv. With a confused heart and mind, I gave up on the institute's prestige, for the comfort of home.

Today, I can only say one thing - Trust that all will be well, and things will fall into their proper place. When in college - you might be giving up on prestige, but it's so much easier to develop a serious career. If you're at a Uni., you have a better chance of getting a job compared to other applicants with no experience, but after a year or two, you're pretty sure to move up the ladder.

All of this, depends on one thing - Are you good enough. Not in an academic scale, but in a scale drawn by your employer and by your industry. Everything else simply doesn't matter, and only transposes your starting point by a year or two, in every direction.

I'm glad things worked out like they did. I'm also pretty certain I haven't finished my battles and I have a long road ahead. But I always try to remember one thing - trust yourself, and things will fall into place.

File dates and HTTP Error 500 Internal server error

Yesterday we deployed an ASP.Net web service to a new US server, which was meant to handle some very simple forwarding logic.

On my development environment, everything worked great, but after deploying the application and trying to invoke a web method from a smart client app, I receieved a wierd exception telling me something similar to "Requested registry access is not allowed".

The test page for the web service was viewable, but trying to invoke the web method through it resulted in an IIS generated error :
"HTTP Error 500 Internal server error"

After alot of digging around, the cause seemed practically embarresing - The file timestamps where dated to a future time.

Since the files were created on the dev environment, they were stamped with the local time, which remained the same when we moved them, and, as it appears, IIS doesn't really like that, to the extent of spewing out HTTP Error 500.

There is a few tools enabling a user to modify a file's timestamp, but one of the most efficient ones is a command line tool called touch, which can be found here :
http://www.helge.mynetcologne.de/touch/index.htm

 

NHibernate updating entities on Flush() without you having a clue as to why ?

As part of our effort to improve performance, we decided on a set of entities that should be cached. One of those was IPLAction.

Happy at my brand new shiny cache, things turned around to kick me in the *#!%$ when I found out that the cache is constantly invalidated.

Near the end of the request, a Flush() call will be sent to NH Session, the request will end and a minute after that – when asp cache polling mechanism polls the db - the cache is Re-loaded from db.

SQL Profiler will show a bunch of "UPDATE IPLActions.." requests just when flush() occurs.

To make a long story short (as possible) here is the final cause - After debugging _into_ NHibernate source code, I found out that if you map an Enum property like so :


<property name="EnumPropName" type="Int32"/>



There will be an UPDATE query on EACH AND EVERY OBJECT instantiated from that class, when the request ends (call to Session.Flush() or Session.Transaction.Commit() ).

Meaning, for example – a cache of 500 objects from that entity type, will cause 500 update calls on request end. (for application cache will happen once, for the first request. For NH 1st level cache, the common usage pattern, will be hit on each request)

Why is that ? – because NH is comparing initial object state (from db + mapping) to current object state when flushing (reflected) – and Enum != Int32, practically telling NH : “the object must be dirty – we need to update it”.

Conclusions –
1. NEVER map an Enum type to Int. (and punch the guy who did it in the first place...)
2. Check for weird “update” statements from time to time when profiling the application.
3. Mapping is _critical_ to fully understand
4. Never underestimate so called “simple” tasks
5. NHibernate source code is a nasty place to be in

 

Posted: Dec 20 2007, 05:28 PM by silver83 | with no comments
תגים:

Linq Expression - delegate parameters issue

Well, this might be a very small issue, but if this works :

 
        delegate TRes ExpDelegate<TArg, TRes>(TArg arg1);

        void LinqTest()
        {
            Expression<ExpDelegate<string, bool>> ex = (n => n.Length > 5);
        }


Why doesn't this work :

        delegate TRes ExpDelegate<TArg, TRes>(params TArg[] arg1);
 
        void LinqTest()
        {
            Expression<ExpDelegate<string, bool>> ex = ((n,k) => n.Length > k.Length);
        }
 


I know I can change the argument type (to be a collection or whatnot..)
but still - is there ambiguity here or was the params keyword just forgotten ?

Posted: Dec 20 2007, 05:27 PM by silver83 | with no comments
תגים:

Ayende Rahien

To anyone that have ever seen or heard enough of Ayende, the following post just clears away all speculation.

http://kyle.baley.org/DoAndroidsDreamOfElectricMonorailsWhileTheyreHibernating.aspx

Thanks, Kyle. Some of us were starting to develop an inferiority complex. :)

 

Posted: Dec 20 2007, 05:27 PM by silver83 | with no comments
תגים:

The love of the trade

Colleges in israel have a problem.

Well, it's more of a problem for us, students.

It's the marketialization of academics - buzzwordemics. and I'll be specific.

A new-comer to the world of a college's Comp.Science major will mainly hear about all the wonderfull programming languages and technologies he's about to learn : c, c++, c#, Java, asp/php, javascript, html, sql, and the list goes on...
Oh, and yes - in the midst are Unix/Linux classes, and even some Oracle (PL-SQL) classes.

This young lad, bombarded with all these buzzwords, is compelled to sign-up. This is surely a promising place for me - the computer-career enthusiast scholar-to-be.

But alas - how unfortunate this mirage is - most of us --

- Will NOT KNOW any of these technologies by the time we finish our scholastic duties.

- Will SUFFER from the ignorance of poorly trained, poorly educated mentors and professors.-

- Will NOT GAIN the tools we need to teach ourselves what the next dawn of technology will
bring forth.

And more importantly - we will not learn the LOVE OF THE TRADE.

I guess some of the reasons for my feelings are my college environment.
Everything around you is soiled by oders of money-grubbing, captilistic-minded geizers. They will all sell you the same dream. Money. But this dream is the wrong one.

 

Here's the right one.

Like Kawasakki (a VC capitalist with bundles of money) stated in one of his public appearances - "We are looking for people who think they will change the world..."

Teachers. Leaders. Influencers.
1. Give us Technology, not mythology. We don't need outdated methodologies and idioms - give
us TDD, IoC, Agile programming. We will appreciate being the few who know what they are
talking about on their first day at work.

2. We will learn the API by ourselves if you just blow us away with a cool DirectX example and
a push in the right way. Even if we won't build Quake7, we'll surely learn more than
listenning to you talk about the next excercise - "a basic banking application".

3. If you can't teach something well, don't try. Some of us are smart. Really smart. Hell - some
of us already work professionaly in the field. We can tell when being preached on a matter
the preacher is illiterate about.

4. Doctors are good for us in scientific majors. They are not good for us in professional courses,
such as Quality Assurance classes. Bombarded with IEEE stardards we need to summerize
and analyse, and an exctremely subjective and narrow view of the software industry.

5. The term "Enterprise" just blows over our heads. We're not there. We won't even care for a
long time from now, and by then - we'll learn it all from scratch.

6. Design IS important. one course blowing over design patterns is not enough. Big UMLs,
architecture and performance considerations, are all things we need to be exposed to, as
soon as possible.

Well, I'm fresh out of more rants or ideas, it's 2:36am. Got another midterm tommorow :)

State problem with AjaxControlToolkit:TabContainer

The problem occured for me when I had 2 tabs, and on the second tab there was a listbox with AutoPostBack set to "true".

When a list item was clicked - the postback result would be that the TabContainer jumped back to the first tab panel (not maintaining "current active tab" state).

Well, small override if you don't want to delve into the source code :


<ajaxtoolkit:tabcontainer id="tc" runat="server" onclientactivetabchanged="SwitchTab">
...
</ajaxtoolkit:tabcontainer>

<asp:hiddenfield id="hdnTabIndex" runat="server"></asp:hiddenfield>

<script>
function SwitchTab(src, args){
__hdnTabIndex.value = src.get_activeTab()._tabIndex;
}
</script>


And in the codebehind :


protected void Page_Load(object sender, EventArgs e)
{
        //override tab state problem
      if (IsPostBack && !string.IsNullOrEmpty(hdnTabIndex.Value))
      {
          TabContainer1.ActiveTabIndex = Convert.ToInt32(hdnTabIndex.Value);
      }
}

 

Impossible local debugging, corrupt pages, mystery revealed.

For more than two months (shameful to admit), four programmers in my company were experiencing a freakish phenomena while trying to view locally served web content -

90% of all page views directed to http://localhost/ in any subdir or extension -
you would recieve corrupt content from your own IIS - html pages seemed screwed up, javascript errors all over the place, and sometimes even image content would seem, ahm, well, corrupt...

The corruption manifests itself in a completely inconsist manner - sometimes you would see everything fine, (after about 20 refresh attempts of the page), sometimes the entire page would seem like it waswritten by someone on LSD...

After many attempts to detect the source of the problem, we were totally lost.
Some of us even formatted their computers, and after a short while - the *** would hit the fan and the same experience would repeat itself.

Well, we (well, I - ) finally found the source of this evil - Citrix Netscaler VPN client !

Yes. It sounds wierd. It is wierd. Even when it is not running. Even when you remove it from the startup process list. Nothing helps but to uninstall it completely.

I have a suspicion, due to the inconsitent nature of the problem, that this is a dual core software incompatibility issue.

This is strengthened by the fact that the only programmer not to be affected by this issue was working on a single core machine.

I hope this helps some poor programming team out there using the Citrix VPN client and loosing their minds over impossible local debugging...

Posted: Dec 20 2007, 05:24 PM by silver83 | with no comments
תגים:

Why is this ThreadStatic member not null ?!?!

Well, I used to slap the “[ThreadStatic]” attribute on static members that I wanted to be Unique to the current request (null at the start of next one).

It seems that, logically enough – it doesn’t really work that way.
Since ASP.Net uses a threadPool, several consecutive requests may be served by the same thread, and all of your nice decorated members aren’t really unique at all.
(Makes sense, but I never really gave it any thought)

There is a solution – Here’s an article that explains the entire issue :

http://www.hanselman.com/blog/fromradio.ashx?external_referrer=&url=http://radio.weblogs.com/0106747/2003/05/23.html

 

Posted: Dec 20 2007, 05:21 PM by silver83 | with no comments
תגים:

ASP.Net Ajax : two common Gotcha's

1. GetPostBackEventReference of control inside UpdatePanel - performs full postback instead Partial postback :

This one can drive you nutters, since the __doPostBack call is almost the same for other elements which perform partial postback.

btn.Attributes["onclick"] = GetPostBackEventReference(this, string.Empty);
Although btn is inside the updatepanel - "this", the containing control, might not be - and that makes all the difference.

If the control's clientId is pre-registered during page load as a partial postback element - the postback will be partial. If not - it won't. So - if the parent (the IPostBackEventHandler) isn't held within an updatepanel - you're bound to eat *** until you find this post :)

2. RegisterClientScriptBlock() not working :

Well, this is one of the most annoying problems ever -
You setup a button inside an updatepanel, and call RegisterClientScriptBlock during it's event handler. Nothing happens.

Well - this is because the postbacker and the "this" object passed to the method call, aren't in the same updatepanel.

Either change "this" to the postbacker instance object, or put them both in the same updatepanel - vuila - it works.

Hope this helps, it sure would have helped me to have someone give me the solution for these two crappers...

 

Posted: Dec 20 2007, 05:01 PM by silver83 | with no comments
תגים: