What's the official Microsoft way to track counts of dynamic controls to be reconstructed upon Postback? - asp.net

When creating dynamic controls based on a data source of arbitrary and changing size, what is the official way to track exactly how many controls need to be rebuilt into the page's control collection after a Postback operation (i.e. on the server side during the ASP.NET page event lifecycle) specifically the point at which dynamic controls are supposed to be rebuilt? Where is the arity stored for retrieval and reconstruction usage?
By "official" I mean the Microsoft way of doing it. There exist hacks like Session storage, etc but I want to know the bonafide or at least Microsoft-recommended way. I've been unable to find a documentation page stating this information. Usually code samples work with a set of dynamic controls of known numbers. It's as if doing otherwise would be tougher.
Update: I'm not inquiring about user controls or static expression of declarative controls, but instead about dynamically injecting controls completely from code-behind, whether they be mine, 3rd-party or built-in ASP.NET controls.

This greatly depends on the problem at hand, and the type of controls you're recreating. Are they all simple text boxes or various different complex custom user controls. the main thing here is: if you want your dynamic control to regain state after a post-back, you have to re-create it in the Init phase of a page life-cycle.
Anyway. There's nothing like a Microsoft way or Microsoft recommended way basically. When you're dynamically adding several simple controls of the same type a hidden field with a count would do the trick, but when you have several complex controls other ways would have to be used. You could still hidden fields and save control's full type strings in them (ie. System.Web.UI.WebControls.TextBox) and re-instantiate them. But think of an even more complex example of putting various controls on different parts in the page... And initializing them to a specific state. That would be a bit more challenging. Hence no Microsoft way... The recommended way is to recreate in Init phase. And that's it.
Everything can be solved, but sometimes one took a wrong direction in the UI and things could be done easier using a different approach.
Additional explanation
This state-full technique of ViewState that Asp.net uses is considered the worse culprit with web developers in general. That's why Asp.net MVC developers think the new framework is bliss since its much more suited to the state-less HTTP protocol. Me being one of them. :D

Related

ASP.Net Web Parts, personalization, and javascript

Folks,
I have some personalized properties on an ASP.Net Web Part that I would like to set via Ajax (for example, the size to which the user has expanded the WebPart using the jQuery Resizable plugin.)
I've read this question and answer, but I don't think it will work. Personalized properties are instance properties. (If they were static, they couldn't be user-scoped, could they?) A WebMethod, which must be static, can't access them.
You might be thinking that I could just use a hidden field and send my values back that way, but that assumes that a postback is done at least once after the values are set. In this case I can't guarantee that: the page in question displays a lot of data but doesn't take any user input other than for configuration.
I seem to recall that some Ajax techniques involve remotely instantiating a page on the server and going through at least part of the page life cycle, but the last time I messed with that was 2006 and I never could get it to work very well. I have the impression that modern Ajax techniques, even for ASP.Net, work in other ways.
So, does anybody have an idea of how this could be managed?
Thanks very much,
Ann L.
Webmethods only have to be static when they are page-based. Create a webservice in your project and stick non-static webmethods in there. You can even enable session state.

Dynamic User Controls in asp.net

Hello I am trying to lear how to create Dynamic User Controls in asp.net.
I just know that this type of controls are created or loaded at run time.
Someone knows a good tutorial about this topic?
thanks in advance,
The best thing you can learn about dynamic controls in ASP.Net webforms is how to avoid them. Dynamic controls in asp.net are filled with pitfalls. I almost always recommend one of the following alternatives:
Place a reasonable fixed number of controls on the page, and then only show the ones you need.
Figure out the source for the dynamic controls and abstract it out to a datasource (array, ienumerable, list, etc) that you can bind to a repeater, even if it's just a call to Enumerable.Range().
Build a user control that outputs the html you want, bypassing the entire "controls" metaphor for this content.
If you really must work with dynamic controls, it's important to keep the stateless nature of http in mind, along with the asp.net page life cycle. Each adds it's own wrinkle to making dynamic controls work: the former that you need to create or recreate the controls every time you do a postback, and the latter that you need to do this before hitting the page load event - usually in page init or pre-init.
Typically what people are talking about here is the dynamic instantiation and addition of a control to a placeholder.
For example
Control ControlInstance = LoadControl("MyControl.ascx");
myPlaceholder.Controls.Add(ControlInstance);
The above instantiates MyControl.ascx and places it inside of a placeholder with id of myPlaceholder.
I agree with #Joel by knowing the page lifecycle, the stateless nature in mind etc it is possible to avoid the pitfalls. The main things to watch out for, which I have had to do, are:
Page_Init – initialise the controls that are on the page here as they were the last time you rendered the page. This is important as ViewState runs after Init and requires the same controls initalised the same way as the way they were previously rendered. You can load the control using the code from #Mitchel i.e.
Control ControlInstance = LoadControl("MyControl.ascx");
myPlaceholder.Controls.Add(ControlInstance);
Page_Load – Load the content of the controls in here as you would with any control that isn’t dynamically loaded. If you have kept a reference to them in your page_init they will therefore be available here.
Keeping to this structure I haven’t had too much difficulty as this is appears to be the way that ASP.NET was designed to work, even if all the samples on MSDN don’t do it this way. The biggest thing that you then have to watch is tracking what state the page was in in regard to the controls that you have had rendered.
In my case it was take the section number of the multipage survey and reload the questions from the database, so all I had to do was track the currently rendered section number which wasn’t difficult.
Having said all that if you are using dynamic controls just to show and hide different views of the same screen then I suggest you don’t use them. In this case I would much rather use either user controls (with the inappropriate ones hidden), placeholders to mark areas that aren’t to be rendered yet, or separate pages/views etc. as that way you keep the pages to a single responsibility which makes it easier to debug and/or get useful information from the user about which page they were on.
The Microsoft article is very good, but the best article that I have been read is in the bellow link:
https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
If you are really interested in ASP.NET Web Forms dynamic controls, I recommend that you study the DotNetNuke CMS Portal. DotNetNuke is one of the best cases using dynamic controls as your core feature to build dynamic portals and pages using ASP.NET Portals. It is free for download in www.dotnetnuke.com.
I hope it helps

ASP.Net excessive use of User Controls

I'm investigating an asp.net web application that extensively uses User Controls on each page. Most pages contain around 10-20 user controls. The User controls seem to be the visual representation of the business objects (if that makes sense), although at a finer granularity such as each tab of a tab control having its contents in a user control. The project itself has over 200 user controls (ascx files).
The performance of the application is very poor (and the reason I'm investigating). Each event (such as a click or dropdown selection etc) requires about 5 seconds for the page to load (10 seconds whilst in visual studio). The application has no use of Ajax.
Tracing is painful as the aspx pages themselves have no code in the code-behind as the user controls look after all of this, so tracing a single page requires trace statements in all the user controls that are on that page.
I actually think that having each user control look after its business code and being re-usable is a smart idea, but is an excessive use of user controls going to incur a performance hit? Does this seem like the structure of an asp.net application that was written by someone with a strong WinForms background?
EDIT
thought I should add that i'm not questioning the use of user controls (or even the amount) but simply whether having so many on a page that all accomplish things (each user control connects to the database for example) will generally cause performance problems...For example, if just one user control postsback to do something, what about the processing of all the others, some are visible and some aren't...#David McEwing mentioned that he had 40 optimised user controls performing etc, but if the developer was WinForms based or "not familiar with asp.net", then how are they going to make sure each one is optimised...
EDIT2
After getting a sql statement trace, the same calls for data are being executed 5-6 times per page call for each event as the different user controls require data that is not stored commonly e.g. each user control in the tab (mentioned above) makes the same call to populate an object from the database...I'm really not here to accuse user controls of being the problem (should i delete the question?) as clearly the problem is NOT user controls but with the use of them in this particular case...which I believe is excessive!
10-20 (or even hundreds) User Controls alone is beyond trivial. The presence of the controls themselves, and the idea of encapsulation, is definitely not the source of your problems.
It's impossible to say precisely what the problem is without actually profiling the application of course, but based on my experience I can say this:
What is more likely is the specific implementation of the business logic inside each user control is poor. With postbacks taking as long as you describe, each control probably looks back to your DAL for its own data on each request. This can be mitigated by two things:
Make sure user controls cache all their data on first load and never re-load it unless explicitly instructed to (usually by an event from a lower-level service)
Ensure the controls all use a set of common services which can reuse data. E.g. if two controls need access to the customers list, and they are executing in the context of the same request session, that should only require one customer list lookup.
I'll put myself firmly in the camp of folks that suggest there is no hard limit to a number of user controls that should be used on a page. It sounds like application-wide tracing is in order here instead of page-level tracing. It may very well be that a handful of these controls is causing the problem. Heck, it could be a single control causing all the fuss. However, since it's impossible to make any assumption about the level of resource-usage that the "average" (if there is such a thing) user-control takes up, it's likewise impossible to suggest a limit. Otherwise, we'd be able to come up with similar limits to the number of members to a class or the number of stored procedures to a database.
Now, if we're talking about 20 complex user-controls that are each retrieving their own data with each refresh and each with a bunch of sub-controls using ViewState whether needed or not, then yeah, that's a problem. Still, it has more to do with overall design than with there being too many controls. If, on the other hand, they've created a common user control to act as nothing more than the composite of a label to the left of a textbox (or maybe even every combination of label + user-actionable control) and have sprinkled this control throughout the app, I can imagine that you'd get a bunch of these on a page and I can't see why that would necessarily hurt anything.
I take it that you are not familiar with applications which use so many user controls?
It sounds like you may be jumping to the conclusion that this unfamiliar aspect of the application is the cause of the unfamiliar bad performance. Instead of making assumptions, why not try one of the following profiling tools, and find out:
JetBrains' dotTrace
Red-Gate ANTS
Automated QA's AQTime
These can all do memory and CPU profiling of ASP.NET applications.
I believe that one of the key purposes of UserControls is code reuse. That is, if the same functionality occurs on multiple web pages, then it is better to create a UserControl for it. That not only saves the developer from writing (or copying and pasting) the same code to several web pages, but it also makes maintenance much easier. Any change made to the UserControl is implemented automatically everywhere the UserControl is used. The maintenance developer doesn't have to worry about finding all the different places that the code needs changing.
I'm not sure if a single-use UserControl is as effective. They do encapsulate and segreate the code, which is nice on a busy web page.
Can you ascertain whether your UserControls are reused, or are many of them only used once.
I agree with Saunders about doing some profiling to determine the impact certain things have.
Note that you can get some free stress-testing tools for IIS here: http://support.microsoft.com/kb/840671
I will say, though, that having too many controls is probably not a good thing, IMHO. Without knowing more, I'd tentatively say 20 is too many.

Serialize ASP.NET Control collection

I've been tasked with converting an existing ASP.NET site from using InProc session management to using the ASP.NET State Server.
Of course what this means is that anything stored in the Session must be serializable.
One of the most complicated pages in the app is currently storing an ASP.NET control collection to the Session. This is failing miserably because the controls cannot be serialized automatically.
Short of totally rewriting how the page works to prevent the need for storing the control collection in the Session, does anyone have a trick/solution for making the collection serializable?
Rewrite the page. You'll thank yourself later. There are sure to be other problems if the original "programmer" (and I use that term loosely here) thought it was a good idea to store a control hierarchy in session.
Don't store control collections in session state. Tess has a lot of articles about this, for example this one.
The first answer that comes to mind is to do a partial rewrite (I don't think there's going to be an easy answer to this). If it's a small number of control types, write your own controls that inherit from those controls and also implement ISerializable. Then, using search and replace, replace the page's controls with your versions. If you are using a large number of control types, you might spend more time extending the standard types than you would refactoring the page.
The work is going to be in the serialization and deserialization of the controls when you initialize them, to make sure you're capturing what you need (the TextBox values, the IsSelected, etc.).
This is obviously a hack, but if your priority really is not rewriting the functionality of that particuar page, this might work for you. Then, of course, you need to add this solution to the "technical debt" that your application is accruing, to make sure it's always on someone's radar to refactor at some point.

ASP.NET Custom Controls - Alternatives to PostBack?

On my journey into the depths of custom ASP.NET control development I am obviously getting my head around the ASP.NET PostBack model and how it affects control development.
I understand that controls have no "lifetime" in ASP.NET, and therefore must be re-initialized on each and every page load. We overcome this by persisting the objects values/parameters to the ViewState.
Many articles I read therefore suggest not using PostBack since this can add considerable overhead to the Page. I am not looking for how to disable it, I know that.
What I am looking for is:
What alternatives to we have to using the PostBack model to initialize controls?
I know we could use the QueryString, but that seems awfully messy, and obviously unreliable.
Ideally you could give me an overview of the architecture/design of a different approach and the pro's/con's of it..
Many thanks ^_^
Well, Session State is a server-side solution, with its own pile of cruft to deal with if you want to avoid ViewState altogether. Really though, using ViewState in a custom control is all fine and good - just be picky about what you store - only store deltas from the declared control state, don't store anything you're going to get on postback anyway (e.g. from a DB call), etc.
You have to store the values somewhere, so you are limited to the query string and hidden form fields. If you relate that to HTTP, basically it's either GET or POST parameters.
I suppose you could use cookies, but that would be really messy.
Store your object state in the session context: this will shift the burden of keeping state from the client to the server, which may be acceptable for small-scale intranet apps. For sites on the capital-I Internet, this won't work;
AJAX-enable your control: in this case, only state changes need to be posted back. Picking the right framework is key here; see http://www.asp.net/ajax/ajaxcontroltoolkit/samples/ for the official MS approach; many others are possible.
If you're truly looking for alternatives to the PostBack model altogether, then I would suggest researching the ASP.NET MVC Framework. I would love to kick WebForms to the curb and do all my stuff in MVC, but alas, legacy code is a tarbaby and rewriting is almost never the answer, so I plug onwards...
I think you still mis-understand controls somewhat. Controls only have the problem you describe when you add them to the page dynamically. If you declare your controls upfront in the aspx code then they build along with the page.

Resources