Categories
perspective

Dynamically Nested Controls ASP.Net

The solution seemed simple enough and what’s more, it should have been a straightforward implementation. Should have been. After one or two false starts, we settled into an approach until we hit the ubiquitous viewstate issues. It’s a silly problem to be having really, given that every asp.net server control automatically manages its own state. True, there are constraints and conditions, nonetheless, the theories are not rocket science.

The page dynamically loads a “layout” usercontrol, depending on user context. This layout dynamically nests a “view” usercontrol, again depending on module within the application. This view then dynamically loads one of n “function” usercontrols on a postback. And therein lies the rub. This function itself posts back data from it’s children, one of which is typically a repeater or other custom usercontrols. Further, each repeater item may contain N server controls. After the postback, the page loads and all the viewstate across all the dynamically nested controls and their children load perfectly, viewstate intact. Simple.

The concepts: each server control maintains its own viewstate [good encapsulation]. The viewstate is heirarchically defined and processed at specific points [good definition]. This is a recursive situation, so if it works for one layer, it must work for N layers. The problems: confusing my requirements with another blog’s requirements, vague newsgroups and technical expressions, sometimes ambiguous documentation and a lot of CheeseFactor :).

After a fresh restart, simplifying the problem domain and applying recursive heuristics the solution is indeed simple. And as simple as they are, i often wonder why/how/where the connection points get missed? Methinks the language of function within the education process is not as sufficient as it could be, but that’s another discussion. So, in summary:

• Always load your dynamic controls, even on the postback. The (!IsPostBack) is not an decision you can use for deciding to load controls dynamically. Use that for binding data.
• Page dynamically loads control inside OnInit(). By the time you hit Page_Load, it’s too late for anything viewstate related, particularly when we’re looking at nested, nested controls.
• Give your dynamically created controls a unique ID. Better for debugging so instead of trying to figure out the tree through reading _ctl1, _ctl2, etc.. The tree now reads as Main, Layout, View, Function, etc… Write code for programmers, not for computers.
• Immediately add the dynamic control to the tree before setting any properties on it.
• With dynamically nested controls, follow similar principles as for page. Don’t dynamically load a nested control inside ControlLoad. Too late. CreateChildControls works much better.

Following these guidelines, your nested, nested controls maintain viewstate perfectly with no additional plumbing. Including all repeater items containing additional server controls and other custom usercontrols.

Tools, Ideas and References:
Google
Concrete Mathematics, A Foundation For Computer Science, Graham, Knuth & Patashnik
dotnet247.com
Authoring Custom Controls
Dynamic Web Controls, Postbacks, and View State By Scott Mitchell

Categories
perspective Technology

The Right Tool

It’s a theme which comes up quite regularly: “the right tool for the right job”. From DIY to software, this mantra manifested literally saves you money. Let alone a bundle of emotional energy which gets exhausted trying to fit round blocks into square holes. I can use a knife as a screwdriver, my cellphone as a delicate hammer and chewing gum as glue. As much as they work, they are not the right tools for the right job.

In software, we tend to think of tools as: inter-alia, compilers, languages, debuggers, IDE’s, SDK’s and drivers. Very rarely do we regard our processes, resources and skills as tools. We define these instead as attributes of a project, team or individual. But attributes are abstract things such as value, determination and enjoyment. Of course, we don’t want to offend any person by referring to them as a tool. But let’s rise above ourselves for a moment here, and ignore the connotations of “tool”. In doing so, we can take advantage of the definition to pursue success with greater enojyment.

The challenge: need to respond to aggressive shifts in the market and stay ahead of competition by releasing features rapidly. The tool: Agile.

The challenge: need to carefully plan out the next n months of development in a mature vertical market. The tool: Waterfall.

The challenge: need to research algorithms and implementations of those algorithms on different platforms. The tool: established computer scientists.

The challenge: need to mentor a team of young programmers within a business application product. The tool: pair-programming.

Instead of dogmatically insisting that the “attributes” of your project: Processes, Resources and SkillSet determine the course of your project, let the real attributes: success, enjoyment and value be a product of your project- but manage those just as pro-actively as any other aspect of the project. And while you course through your project, employ the right tools for the right job at the right time.

And just because a hammer worked really well driving that nail into the wall, it doesn’t mean it’ll do an equally fantastic job at attaching the mirror to the wall.

The irony for me though, is that we all instinctively know this and by some subconscious decision making process, we apply this principle quite well to a point. It’s when we don’t apply this principle though that we end up in a: “Houston, we have a problem”.

I think the art of getting this right, is like anything else: be conscious of what you do and decidely know what makes you successful. Like your code, when it unexpectedly stops working, it’s probably because you are not really sure why it was working to begin with…

It Depends

Which language is better: Java, C++, C# or VB.Net? Well, it depends.
Which is better: MS-SQL or Oracle? Again, it depends.
Which is the best implementation for a singleton? Mmm… let me think. Well… it depends. This ever popular and increasingly quoted phrase, “it depends” has nestled itself into our reactive vocabularly because well, “it depends” on a lot of factors.

From platforms to databases, frameworks to languages, compilers to GUIs, the variables in this game called software have multiplied radically. To think one solution can satisfy across all domains is declaring that you found the Holy Grail; the Silver Bullet; the Rabbit’s Foot- call it what you may. The problem with the Holy Grail is that no one [alive] has ever really seen it, so when you do present it, how do you argue beyond doubt that it is The Holy Grail? Hence you should not be surprised by the stares when you declare in a moment of technical triumph, rising from your cubicle in wondrous glee: “VB Rulz the World!” Well, yes and no. It depends…

Debates for and against, and within Agile come from different perspectives. Similarily, for and against, and within C++, the debatees hold different assumptions. An optimized implementation for one team, is not guaranteed to be the best solution for another. Team 2 might not even understand the code and hence not be capable of maintaining it. Or instead of optimization, throw a Gig or 2 of RAM, or a second processor at it [cheap at the price compared to a programmer] and watch how that routine suddenly improves in performance.
“That won’t always work, you know!” Yes, i know, it depends on the problem and the optimization.

And this is precisely the point, it does depend on a lot of variables. Even the very statement “it depends” is not applicable in every situation, because well… it depends on the circumstances 🙂

Communication Instinct

Many of the challenges facing software processes today are not new. From the social to the technical, these challenges are also not unique to the software world. Dissension amongst the ranks and disillusionment with management are common social problems within any company; and more, within any group of people who co-habit for a length of time. What and how to act [implement] are also sources of diverse technical opinion and impassioned debate between those in the know. Nonetheless, as common [and age-old] as our predicament is, it has it’s own distinct flavour spiced up through consistently bad communication.

Statistics aside, our collective experience testifies that business [“them”] and development [“us”] fail to understand each other as clearly as we would like. Starting with the requirements gathering phase, the problem definition is already corrupted. There is enough satire available to substantiate this undercurrent of truth [even without Dilbert] that there is something horribly wrong right from the beginning.

Agile, waterfall, functional specifications, UML; all these and others try desperately to accommodate vague definitions or legalistically bind definitions on opposite sides of the spectrum. Even the middle path fails sometimes. As hard as some try, they will fail with spectacular disillusion, regardless of how absolutely brilliant the idea is. Execution is key.

To execute, we need “a” plan. Once we have “a” plan, it needs to be communicated in a way that is understood with clarity by each member involved such that each is of the same mind and vision. And in successful execution, this communication tends toward the less verbose and more instinctive over time. Team members learn to read each other.

Why do newly formed sport teams get better with age [assuming players remain mostly the same]? Why does their game break down when the team is shuffled? Why is it so hard for new team players to break into a team? Why do they even need to break into a team? As a team gets better, their communication is reduced to a twinkle in the eye; a mono-syllabic reference to a previously successful play; the slightest change in posture. If they had to communicate from first principles each time, their progress would be slow. New team members need to absorb these nuances and shared histories in order to fit into and contribute to successful play.

The same can be said of a software development team [which, by the way includes both the “them” and the “us”- a one team mentality, but that’s another discussion altogether]. The team needs to progress to a point where business analysts only need say one thing in a particular way and immediately the technical team understands the play. Yes, this may take some time and work. More over, it takes courage and patience.

Changing teams all the time doesn’t help things much but maybe the teams change because there is no perceived progress. Another chicken/egg scenario [btw, the chicken came first]. That aside, a committed and successful team will endeavour to refine their communication and work hard at understanding each other.

Imagine business investment looking the technical team squarely in the eye during a round of requirements gathering…
BI: “Status Updates”
TT: “Done”
And the expectations of BI are exceeded upon delivery. Fantasy? For sure, but that doesn’t mean we can’t aim to achieve a measure of that.

Agile, waterfall, functional specifications, UML, et al, are all tools to aid communication, not replace it. And as with any tool, the job is easy if you use the right tool at the right time for the right job. They should not be ends within themselves but a means to achieve a greater understanding of each other. And in developing these communication tools, progressing in them for the sake of expertness without a greater awareness of their communicative double edge, restrains the more powerful instinctive and natural communication. It is this kind of communuication, when manifested, which is able to break all barriers of understanding and promote real value.

Quick And Dirty

Programmers write a lot of code. Some of it good, some bad, the rest just plain fugly. There’s code to provide functionality, code to prove a point, code to research a bug, code for fun; well, code for every occassion. So let’s examine the production occassion.

We’re employed to implement a feature and there’s a lot of code that needs to be written. But before we settle into implementation, we need to locate where it will belong. Like my cats kneading their sleeping spot, we refactor our bed of code to setup our work area. Then we settle into the business of production code. Red green refactor commit repeat.

Now when implementing “serious” code, we sometimes forget that QuickAndDirty code is just another tool in our box in order to get the job done. Faced with a lengthy workflow, there’s nothing wrong with plugging in un-cohesive, tightly coupled structs/procedures [ =:-o ] to get your thoughts down and documented. Of course, as with any tool, you need to use it correctly in order to get happy mileage out of it.

But just because you’re doing serious production code [and pair programming] don’t be too self conscious about the code you write. Be bold and get dirty. Write quick code to make it compile and flow. Just as red green refactor mantra is applied to tests; the same can be applied to production code.

The major advantage is that you don’t have to keep a hundred threads tied up in your head all at once while you journey through a workflow or a concept. Along each step of the way, there will be discoveries and unanswered questions about what [not] to do [particularly for UI based work]. These distractions can add up quickly and before you know it, you’re coding down a path that when you finish, it takes a while before you find that trail again.

Oh and by the way, don’t leave your tools lying around for others to trip on…


note: production code here is used to distinguish between purely test and deployed code, although i regard test code as production code in my environment.

Embracing Conflict

We all think differently, and this is a good thing. And there’s definitely value for particular paradigms at different points in software lifecycle. When we use the wrong paradigm at the wrong time, we end up in situations less desirable.

Researching the anti-patterns related to abstracting too early, it becomes obvious that implementing an abstraction ahead of its time results in bad design. Apart from the complexities and maintenance, there are hidden dangers about the assumptions subclasses make when they override methods, particularly over time and changing development teams. Couple these and you can end up with a time bomb.

This [abstracting too early] particular concept has resulted in endless [moot?] discussions within Agile teams debating inter-alia, upfront design, YAGNI and simplest thing. These “discussions” have divisive power and can hinder progress if the fruit of the discussions is not managed appropriately.

Yet, there are definite advantages to thinking this way. Thinking in the abstract and seeing a bigger and more vague, yet determined way, can be useful in spotting potential problems down the line. Thinking in the abstract and visualising complex inheritance heirarchies and patterns upfront [so complicated its bound to impress the client :)] adds value to the discussions and directions by adding scope to thought.

It becomes a problem when one argument insists, dogmatically, that the ObviousImplementation is the only road to take and the psychic team insist, equally vehemently, that it is the only road to take. And don’t think that a public opinion poll is going to substitute for real thought.

Regardless of the judgements ultimately placed on any pattern, or anti-pattern, methodology or approach, a successful team can work productively within the apparent chaos and all it’s contradictions. Deciding when to use which paradigm is a critical decision. Deciding to dogmatically ban one undesirable paradigm, largely because it surfaces at the wrong time, is a shortcut to weaknening your team and disempowering your colleagues.

At each end of the contradiction is a powerful force that needs to be maintained in tension with it’s opposite. By harnessing this tension you can maintain a steady and powerful course, but be willing and prepared to use the opposing powers when the balance shifts unexpectedly. The degrees to which you need to harness are determined by the degree of imbalance. And if you don’t proactively manage these forces against one another, they will ultimately clash and spiral into destruction.

Passion, Commitment & Results

chicken or the egg? the question applies to just more than poultry, or breakfast, depending on which you think came first. which comes first, commitment or results?

in order to succeed at anything, we need to be committed, but often we first want some guarantee of result before we want to commit to anything. which we choose to come first, will depend on which area of our lives we’re talking about. but should it be that way?

starting a new job, for example. do we commit to the new job even if do not know what the future will hold for us there? trick is, if we don’t commit, the job will probably never work out anyway. at the first sign of trouble, the unsteady and doubting foundation which we set for ourselves on embarking the journey doesn’t offer any support. if anything, it will convince us even the more to abandon the cause. had we committed from the word go however, any sign of trouble will be percieved as opportunity to grow. results and success are inevitable.

it can be argued however, that signs of trouble do represent real trouble and we need to be cautious in not overcompensating by ignoring any “signs”. but this is not the topic at hand. i do concede that not everything is or should be an opportunity to grow. but the focus of this piece is the relationship between commitment and success.

extending the job commitment scenario, let’s look at relationships. do we commit to a relationship, not knowing what to fully expect? And thereby, because of our willingness to commit, the relationship succeeds and overcomes all challenges? Or do we wait for the relationship to show signs of promise on its own before deciding to commit? Question is: can a relationship show any sign of promise just on its own without any commitment by both parties to, at the very least, for example, commit to making each other a priority in their respective lives?

and then in spritual matters. does our religion have to offer us some sort of return-on-investment [time, money, emotion] and show good future prospects before we decide to fully commit to it? or is it possible to commit to it first, and in doing so, live and breathe the principles that, hopefully, lead us into a richer awareness of what it means to truly be alive?

so where does commitment come from? passion.

passion drives us to making a commitment. it won’t neccessarily sustain our commitment but can ignite from time to time [i’m referring to voluntary and not that fear-based or co-erced commitments]. that passion or desire [love?] in the moment of the commitment gives us the courage to make the commitment to things unknown, or rather, not yet known. but with the commitment in place, results and success are inevitable.

so where does passion come from? the heart? gut feeling? something needs to spark up and give rise to passion which will fuel the readiness to commit. and then there’s that other bit of trickery that goes on: that passionate feeling doesn’t last forever. the sparks fade relatively quickly, as sparks do. how do we make it linger through the range and bombardment of emotions and choices we face each day?

sustaining a particular emotion over an extended period of time requires a combination of physical, chemical and cognitive energy. how we manage to do that is each to our own little secret to living happy lives. and then there’s always this to consider: a passion that fades in the face of adversity- was that really a pure passion [versus fancy] or is it just passion under testing and how important is it to you [truthfully] to pursue?

maybe why we give up so easily on tasks, paths or journeys we set for themselves is because we’re choosing the ones that aren’t dripping with passion. and because there’s no passion, we don’t want to, we can’t, commit. and because we’re not committed, we fail when we hit a rough spot.

conversely, if we choose journeys of passion, we will commit to them 100% and through that commitment, we’ll reach the levels of success possible within that path. be it job, relationship, spritual or communal…

Truth Is Relative

big problem is that this statement is itself a very absolute statement. so if you hold to the “absolute” truth that “truth is relative”, you’re in a bit of a predicament and you got some explaining to do. maybe your persepctive of the truth is relative, but that doesn’t change the truth itself.

if truth is absolute, well then there’s no problem then, is there. what is the truth, is the truth for everyone concerned. deciding of course, what exactly is the absolute truth is, is another question altogether.

i’m going to stop there before my head explodes.

Categories
Technology

DataBinding on ASP.Net

After consideration from a previous post, i decided to boldly test my new class designs by making those private instance variables public. Beyond struggling against my own niggles, i discovered that ASP.Net doesn’t like breaking PrivateInstanceVariableMandate either. Consider the DataBinder for example.

In your mark-up code, a “typical” repeater section might look like


The DataBinder.Eval however only evaluates properties of that object. Public fields [class variables] are not properties and so breaking with traditions and trying to make things simpler, proved to be more complicated down the line [on this framework].

With a little co-ercion, it’s easy enuff to write a FieldBinder


to allow code such as above. All of a sudden i can access fields and it’s all good. Now the pro’s and con’s of introducing FieldBinder into the system can be debated at length, but the beauty of this insight led me to an even more interesting possibility.


There are times when real-time data associated with an object needs to be retrieved. Making the function a property, in a no-argument case, again, is a design preference but can lead to problems since the property EmailCount conveys a different sentiment to the method GetEmailCount(). The method, for me in my current project, implies that more work is done to retrieve the value than simply looking at one of the already present values. So i really want to keep it a function but can’t bind to it using DataBinder.

Extending this idea further, you can overload FunctionBinder to accept specific parameter types or arrays of objects for the function arguments. How you do that, well, that’s your decision…

SourceCode

Mixing It Up

For the past 2 days, i’ve *finally* had the opportunity to work in both C# and Visual Basic simultaneously! It might seem like quite a lame goal, and yes, it probably is. But it was interesting none the less, to dynamically compare the two languages, and bonus- getting paid to do it- ie not doing it at home after hours as part of research or interest.

The functional library was written in VB [WebChart by blong] which didn’t quite have all the functionality we needed. But it did provide a good fit. On the negative side, it didn’t come with a set of test suite *shock.horror* The rest of our web application is almost entirely C#.

The day arrived on Monday when WebChart needed to mature and we needed to do the moral thing. Add tests. The test code itself was written in C# and this was the perfect platform to code simultaneously without “looking” for an excuse, erm, opportunity to truly compare the two languages.

After a few days of implementing in VB.Net and then directly using the implementation from C#, i still prefer C# but definitely have less of an aversion to VB.Net. I’m glad to see VB and array indexing has come of age. Yes, but not just reading about it- actually using it. There’s something about us programmers ‘cos we don’t trust documentation; no thanks to years of bad SDK’s. We only believe once we see something in action, and that, in production on our system.

The { } are by way FarMoreEfficient than the End … statements. More readable and when you’re looking at nested loops, the


For Each ...
For Each ...
Next
Next

was not as easy to find as


foreach(...)
{
foreach(....)
{
}
}

And using [] for arrays/lists is nicer than () which usually refers to a method, i mean Sub

Etc.. etc.. And many before me have waxed lyrically about the two languages, but i’ll stop here.

If anything, it provided a good mental workout jumping between the two so dynamically. But there were [lost] times when i stared at the screen wondering why the *&%#! the following


Private Function GetLegend() As SortedList
int index = 0;
End Function

would just NOT compile 🙂