Setting CurrentCulture from DropnDown in MasterPage - asp.net

What is the best practice to set the CurrentThread.CurrentUICulture from a DrownDownList in a MasterPage?
I don't want to override InitializeCulture() in every page.
Could it be stored in a Session variable and set in a HttpModule or HttpHandler?
An additional problem i ran into is that if there are databound language-dependant controls on the page they will need to be databound after the language has changed.
Thanks.

I have most often chosen to create a pase page class and override InitializeCulture() there. All pages inherit from the base page so all logic is encapsulated in the base page. This works for me because I use the querystring to pass language preference changes.
InitializeCulture() has logic to check for querystring argument, existing session value, cookie preference, defaulting to the browser's current culture.
I suppose you could do a redirect in the masterpage dropdown change event.

I store the culture in a cookie and then set it in the Application_BeginRequest of the global.asax. When you first set it though you have to Server.Transfer(Request.Url.LocalPath) because the selectedindex changed event fires too late in the lifecycle to take affect. Not sure if its the best but it works for me.

Related

Destroy Session in an application

I have several pages in my application. I have used a session variable called "Session["Variable"]" that is set in page1 and page2. That means The scope should be in page1 and page2. If you go out any of these page will clear the above session variable. Is there any solution to clear the particular session varible in the application level. i.e i don't want to write the code for each and every pages...
Session key once created is accessbile in all pages of the asp.net application and not just within the once where it was added or modified.
use Session.Remove() if you need to explicitly remove a variable/key from session.
Session.Remove("Variable");
Additionally,
Session.RemoveAll(); //Removes all keys from current session.
Session.Abandon(); //Abandon the current session.
If you used MasterPages or derive your pages from a base class, you can use a switch case and determine whether or not the current page is Page1, Page2 or something else. If it is "something else", remove the key from the session.
IE: Switch case in the Page_load of the masterpage
Once you set the session in an asp.net application, the scope of this session is available in everywhere. So, in your case, u can just write one common function for checking the page1 and page2.

How do I set a custom culture before the page is rendered?

I have created a custom culture for client-specific language, i.e. I have resx files for that culture.
The issue I have is that I can't seem to set the culture early enough in the page cycle. By the time I call Thread.CurrentThread.CurrentUICulture = culture and Thread.CurrentThread.CurrentCulture = culture the page seems to already have picked the language from the base resx file :(
So I'm having to set the culture and then redirect back to the same page?
I've tried setting it in the Page_PreInit and its still not early enough? Is there an earlier event I can hook into?
You need to override the page's InitializeCulture() method, look here for details.

ViewState is taking 20% of my pages even though it's disabled!

I disabled viewstate in the web.config file (and there's no EnableViewState = true anywhere on the pages), but despite this, the pages are rendered with a quite large view state (8k for a 40k page). I checked the viewstate contents with a viewstate decoder and discovered that the multiview controls I'm using on my pages are the guilty ones. Is there anyway to make the multiview controls stop using the viewstate?
I'm thinking about creating a control class that inherits from MultiView and override the LoadViewState and SaveViewState methods but I'm leaving this as a last resort, any suggestions?
Thanks
here is a wonderful way to just get rid of viewstate from being sent over wire for each post-back. basically, it stores the complete viewstate as a session variable on the server and only transfers the identifier in the viewstate field.
compression will save you little bit in terms of bandwidth whereas putting getting viewstate out of the page will have quite dramatic performance improvement
the following articles explains several techniques with performance measurement metrics as well eggheadcafe
Since ASP.NET 2.0 the internal content of the ViewState hidden field is made up of the "old" ViewState (the ViewState state bag / dictionary) AND the ControlState. The Control State unlike the ViewState cannot be disabled and it is intended for the minimal information that a Control needs to function properly.
You cannot disable the ControlState and you either live with it either use a different (kind) of control on your page.
You could override the render for your page (or base page) scan for the viewstate hidden input and remove it from the writer.
steps:
do the base.render
output the htmlwriter contents to a string
remove input with __viewstate
write the new string to the HTMLWriter.
To answer my own question, I managed to get rid of the viewstate by removing the form runat="server" I had in my master page, now I only enclose the controls that really need postback in a form tag with runat=server. It seems to be discarding the control state as well (which is what I want, the page doesn't post back), will still have to investigate more though.
The only problem that's left is that when I add a form runat=server tag anywhere on the page, the Multiview finds my form tag and add its trash in the hidden viewstate field, I was thinking this would happen only if the multiview is enclosed in a form runat="server" tag but it's smart enough (or dumb enough in this regard) to find the form tag anyway.
The System.Web.UI.Page class has a property called PageStatePersister that you can override in your pages. Here you can return a PageStatePersister type object that overrides the default persistence mode for the pages viewstate.
As Vikram suggested you can use a SessionPageStatePersister to store viewstate in session instead of a hidden field. But you can also implement your own PageStatePersister that stores the viewstate in the Cache or a database or a file. Whatever you need really.
The thing you shouldn't do is to use the PageStatePersister to discard viewstate, for the viewstate is needed by some of your controls.

Best way to implement languages menu in an ASP.NET application

I trying to implement a typical languages menu where users can select the language they want to view the site in through a menu that appears throughout all pages in the site.
The menu will appear on multiple master pages (currently one for pages where users are logged in and one for pages where users are not).
My current implementation is having a single master page base class (let's call it MasterBase). MasterBase has an event
public event LanguageChangedEventHandler LanguageChanged;
where LanguagedChangedEventHandler is simply defined as
public delegate void LanguageChangedEventHandler(string NewCulture);
MasterBase also has an overridable method
protected virtual void OnLanguageChanged(string NewCulture)
which just basically fires the event.
Each master page that inherits MasterBase overrides OnLanguageChanged and does the usual stuff like set the Thread's CurrentUICulture and the language cookie then does a
Server.Transfer(this.Page.AppRelativeVirtualPath, true);
to get the page to reload with localized values for the new culture. On the master page for logged in users it also updates the user's language pref in the db.
Each language option is currently a LinkButton on a master page that inherits from MasterBase. When the link is clicked it calls the base OnLanguagedChanged method passing in the correct culture info. E.g.
protected void btnEnglish_Click(object sender, EventArgs e) {
this.OnLanguageChanged("en-US");
}
Each page that needs to handle a language change then has some code in the page load that looks like...
((MasterBase)this.Master).LanguageChanged += this.Page_OnLanguageChanged;
// Where Page_OnLanguageChanged has the signature of LanguageChangedEventHandler
// and has stuff like reloading options in a drop down using the new language.
Quite a convoluted 'framework' =)
Firstly it's hard for new developers to know they have to hook up a method to the MasterBase's LanguageChanged event to handle language changes. Yes, we do document it. But still it's not something straightforward and obvious.
Secondly, all language changes are post backs. This is problematic especially when you want to navigate back with the browser Back button.
I'm looking for a more elegant solution. One that doesn't have both the problems above and also handles my current requirements.
Greatly appreciate any suggestions. Thanks.
It seems to me that it would be better to implement this in a control that sets an application variable that all pages could use. That way you could just implement the code in one place and have it always available on each page that displays the control (could be in your master's so all pages that inherit get it automatically). I think in the control you would have a handler that sets the global language setting and then reloads the page. Each page would check the language setting during page_load or prerender and load the proper localized strings accordingly.
I would just use the PreInit event on base page to set the current ui culture. I am not clear on why you would need each page to know when language is changed.

Dynamically added controls in Asp.Net

I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)
My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page_init as it is dependent on values from at previous PostBack.
A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").
Am I going down the wrong path here?
I agree with the other points made here "If you can get out of creating controls dynamically, then do so..." (by #Jesper Blad Jenson aka) but here is a trick I worked out with dynamically created controls in the past.
The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values just before the rest of the tree is populated. That is by overriding LoadViewState(...) and SaveViewState(...).
In SaveViewState store the control you wish to create:
protected override object SaveViewState()
{
object[] myState = new object[2];
myState[0] = base.SaveViewState();
myState[1] = controlPickerDropDown.SelectedValue;
return myState
}
When the framework calls your "LoadViewState" override you'll get back the exact object you returned from "SaveViewState":
protected override void LoadViewState(object savedState)
{
object[] myState = (object[])savedState;
// Here is the trick, use the value you saved here to create your control tree.
CreateControlBasedOnDropDownValue(myState[1]);
// Call the base method to ensure everything works correctly.
base.LoadViewState(myState[0]);
}
I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single "Save" operation.
You must add your control inside OnInit event and viewstate will be preserved. Don't use if(ispostback), because controls must be added every time, event in postback!
(De)Serialization of viewstate happens after OnInit and before OnLoad, so your viewstate persistence provider will see dynamically added controls if they are added in OnInit.
But in scenario you're describing, probably multiview or simple hide/show (visible property) will be better solution.
It's because in OnInit event, when you must read dropdown and add new controls, viewstate isn't read (deserialized) yet and you don't know what did user choose! (you can do request.form(), but that feels kinda wrong)
After having wrestled with this problem for at while I have come up with these groundrules which seems to work, but YMMV.
Use declarative controls whenever possible
Use databinding where possible
Understand how ViewState works
The Visibilty property can go a long way
If you must use add controls in an event handler use Aydsman's tip and recreate the controls in an overridden LoadViewState.
TRULY Understanding ViewState is a must-read.
Understanding Dynamic Controls By Example shows some techniques on how to use databinding instead of dynamic controls.
TRULY Understanding Dynamic Controls also clarifies techniques which can be used to avoid dynamic controls.
Hope this helps others with same problems.
If you truly need to use dynamic controls, the following should work:
In OnInit, recreate the exact same control hierarchy that was on the page when the previous request was fulfilled. (If this isn't the initial request, of course)
After OnInit, the framework will load the viewstate from the previous request and all your controls should be in a stable state now.
In OnLoad, remove the controls that are not required and add the necessary ones. You will also have to somehow save the current control tree at this point, to be used in the first step during the following request. You could use a session variable that dictates how the dynamic control tree was created. I even stored the whole Controls collection in the session once (put aside your pitchforks, it was just for a demo).
Re-adding the "stale" controls that you will not need and will be removed at OnLoad anyway seems a bit quirky, but Asp.Net was not really designed with dynamic control creation in mind. If the exact same control hierarchy is not preserved during viewstate loading, all kinds of hard-to find bugs begin lurking in the page, because states of older controls are loaded into newly added ones.
Read up on Asp.Net page life cycle and especially on how the viewstate works and it will become clear.
Edit: This is a very good article about how viewstate behaves and what you should consider while dealing with dynamic controls: <Link>
Well. If you can get out of creating controls dynamicly, then do so - otherwise, what i whould do is to use Page_Load instead of Page_Init, but instead of placing stuff inside the If Not IsPostBack, then set i just directly in the method.
Ah, that's the problem with the leaky abstraction of ASP.NET web forms.
Maybe you'll be interested to look at ASP.NET MVC, which was used for the creation of this stackoverflow.com web site? That should be an easier fit for you, coming from a PHP (thus, pedal-to-the-metal when it comes to HTML and Javascript) background.
I think the answer here is in the MultiView control, so that for example the dropdown switches between different views in the multi-view.
You can probably even data-bind the current view property of the multiview to the value of the dropdown!
The only correct answer was given by Aydsman. LoadViewState is the only place to add dynamic controls where their viewstate values will be restored when recreated and you can access the viewstate in order to determine which controls to add.
I ran across this in the book "Pro ASP.NET 3.5 in C# 2008" under the section Dynamic Control Creation:
If you need to re-create a control multiple times, you should perform the control creation in the Page.Load event handler. This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the Page.Load event, ASP.NET will apply any view state information that it has after the Page.Load event handler ends. This process is automatic.
I have not tested this, but you might look into it.

Resources