ASP.NET reset thread culture after use? - asp.net

If I set Thread Culture and UICulture for one ASPX, after pass for that page, all my aspx that use the same thread(not same request) will have the same Culture?
Because I need to set Culture just for one ASMX

If the culture you set is not read from the browser settings (like it lives in a database) You need to set this on every request.
As described here:
http://msdn.microsoft.com/en-us/library/bz9tc508.aspx
Override the page's 'InitializeCulture' method on every page. A common base class for all your pages comes in really handy here.
I would suggest firing up .NET reflector and see what the default implementation does. It will help clarify what is going on by default.
As this is event is handled on the page level, and not in the Global.asax, I would expect this is re-set. also, as the article describes, this event is Called so early in the page life cycle that capturing User Input requires directly accessing 'Request.Form'.
EDIT: Please try this and See that this must be set in every request. Let me know if you see different results or if I misunderstand your question.
Default.aspx: prints '21.09.2010'
<%# Page Language="C#" %>
<%# Import Namespace="System.Threading" %>
<%# Import Namespace="System.Globalization" %>
<script runat="server">
protected override void InitializeCulture()
{
UICulture = "de-DE";
Culture = "de-DE";
//base.InitializeCulture();
}
</script>
<HTML>
<head>
</head>
<body>
<%= System.DateTime.Now.ToShortDateString()%>
</body>
</HTML>
Default2.aspx: prints '9/21/2010' (my default cluture is es-US)
<%# Page Language="C#" %>
<HTML>
<head>
</head>
<body>
<%= System.DateTime.Now.ToShortDateString()%>
</body>
</HTML>
The order in which you hit these pages does not matter. The results do not change.
One approach people is used is to store this info in a Session variable and use the Session Variables to set the culture ..so logic for this is centerlized.

I'm pretty sure that UICulture, once set, stays for the entire ASP session (which happens independently of whatever session you create for your own application).
Edit: looks like a straightforward summary here: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/localization/localization.aspx

Related

Invalid viewstate error when posting back to same page

I'm having some issues with an Invalid Viewstate error and I can understand why it's happening but I don't know how to fix it.
I have a page which is similar to this /story/?id=123 but I'm using a different page to Server.Transfer to this page.
So I've set up /info to Server.TransferRequest("/story/?id=123") and it works fine until the page does a postback to itself.
We have a login form on this page which simply reloads the page but when it does it seems to add /?id=123 onto the end of the URL so it ends up like this /info/?id=123 thus causing an Invalid Viewstate error.
I've already tried adding EnableViewStateMac="false" - this fixes the error but it doesn't log the user in as expected so it does not give the required result.
So my questions are:
Is there a better way to redirect to my page other than Server.TransferRequest but still keeping the nice URL? - I don't want to Response.Redirect if I can avoid it.
If not, is there an easy way to fix this error that doesn't require me adding EnableViewStateMac="false"?
http://support.microsoft.com/kb/316920
I believe that article will explain why you are having the problem and it gives a solution to fix it.
I know you don't want to use Response.Redirect, but I think that would also solve the problem.
PRB: "View State Is Invalid" Error Message When You Use Server.Transfer
This article was previously published under Q316920
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer
offers support. Therefore, this article is offered "as is" and will no
longer be updated.
SYMPTOMS
When you use HttpServerUtility.Transfer("page name", true), you
receive the following error message:
The View State is invalid for this page and might be corrupted
CAUSE
This problem occurs because the EnableViewStateMac attribute of the
<pages> element is set to true by default. When this attribute is
set to true, ASP.NET runs a message authentication check (MAC) on the
view state of the page when the page is posted back from the client.
This check determines if the view state of the page was modified on
the client. For security purposes, it is recommended that you keep
this attribute set to true.
When you call the Server.Transfer method and set the second
parameter to true, you preserve the QueryString and the Form
collections. One of the form fields is the hidden __VIEWSTATE form
field, which holds the view state for the page. The view state message
authentication check fails because the message authentication check
only checks each page. Therefore, the view state from the page that
calls Server.Transfer is not valid on the destination page.
View state is page scoped and is valid for that page only. View state
should not be transferred across pages.
RESOLUTION
To resolve this problem, use one of the following methods.
Resolution 1
Transfer values between pages to pass your server control values to
the other pages. For more information, refer to the following MSDN
documentation: Passing Server Control Values Between
Pages
This requires that you create public properties for each property of a
control that you want to access from the destination page.
If you have many controls, and if you want to access the properties of
these controls from another page, you can also declare those controls
as public variables. For example:
Page1.aspx
Public Class Page1
Public WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
'Insert your code here.
End Class
Page2.aspx
Dim sourcePage As Page1
sourcePage = CType(Context.Handler, WebForm1)
Response.Write(sourcePage.TextBox1.Text)
Resolution 2
Do not pass the second parameter (which is false by default) when
you call Server.Transfer. For example:
Server.Transfer("<page name>")
This code does not send the QueryString and the Form fields to the
page that is called. When no data is transferred, ASP.NET does not run
the message authentication check.
MORE INFORMATION
Steps to Reproduce the Behavior
Create an .aspx page named WebForm1.aspx that transfers execution to another page. Add the following code to WebForm1.aspx:
<%# Page language="vb" AutoEventWireup="true" %>
<html>
<body>
<form id="WebForm1" method="post" runat="server">
<asp:TextBox id="txtName" runat="server">Your Name</asp:TextBox><br>
<asp:Button id="Button1" runat="server" Text="Submit" OnClick="Button1_Click"></asp:Button>
</form>
</body>
</html>
<script runat=server>
Sub Button1_Click(sender As Object, e As System.EventArgs)
Server.Transfer("WebForm2.aspx",true)
End Sub
</script>
Create another .aspx page named WebForm2.aspx, and then add the following code:
<%# Page language="vb" AutoEventWireup="true" %>
<html>
<body>
<form id="WebForm2" method="post" runat="server">
<asp:Label id="lblName" runat="server" >Web Form 2</asp:Label>
</form>
</body>
</html>
<script runat=server>
Sub Page_Load(sender As Object, e As EventArgs)
Dim thisPage As System.Web.UI.Page
Dim nameTextBox As TextBox
thisPage = CType(Context.Handler, System.Web.UI.Page)
nameTextBox = CType(thisPage.FindControl("txtName"), System.Web.UI.Control)
lblName.Text = "Your name is '" & nameTextBox.Text & "'."
End Sub
</script>
Open WebForm1.aspx in your browser, and then click Submit.

How to pass an object from .cs to .aspx

I am a asp .net beginner. I want to use some objects created at Site.Master.cs in Site.Master. Is there an easy way to do it?
I know how to do it in MVC(by using view(the object)). But how can i do it in normal ASP .net web application?
I don't understand what exactly you want to do.
If you want to insert some string into tag's title you can insert the following thing in SiteMaster.master file:
<img src="<%= Page.ResolveUrl("~/") %>images/logo.png">
instead of:
<img src="images/logo.png">
In the first case there will be calculated the path from the root of your application. In the second case there will be relative link. This is because server will CALCULATE the value of Page.ResolveUrl("~") function and will WRITE it in src tag.
You can do the same thing with any other methods, classes if you defined them properly. But I wouldn't recommend you to implement complicated logic in .aspx files (or .master files). Because you can end up with many difficulties with testing and styling such application.
There are other server tags:
<% %> - an embedded code block is server code that executes during the page's render phase. The code in the block can execute programming statements and call functions in the current page class. Description and examples
<%= %> - most useful for displaying single pieces of information. Description and examples
<%# %> - data binding expression syntax. Description and examples
<%$ %> - ASP.NET Expression. Description and examples
<%# %> - Directive Syntax. Description and examples
<%-- --%> - Server-Side Comments. Description and examples
<%: %> like <%= %> - But HtmlEncodes the output (new with Asp.Net 4). Description and examples
Another way: you can use JSON to send some data to the client and then process it with javascript. Take a look at this project.
If the #Page directive in your .aspx file has Inherits="XYZ" where XYZ is the class declared in your .cs file, you can simply add a protected field to your class and assign a value to it. You'll be able to access it in the .aspx file just by using its name.
You can also use HttpContext.Items property to keep objects during a single request:
HttpContext.Current.Items["SavedItem"] = "hello world";
And use it in page:
<%= ((string)Context.Items["SavedItem"]) %>
Any public or protected property or method in Site.Master.cs will be accessible from Site.Master.
but how to invoke c# code in aspx ?
There are several ways, including the <%= %> construction, and databinding syntax.
It would help if you explained what you're trying to achieve.

ASP.Net <%# %> and <%= %> rules?

Can someone explain to me the rules around what can and cannot be evaluated/inserted into markup using the <%# %> and <%= %> tags in asp.net?
When I first discovered I could inject code-behind variables into mark-up using <%= I thought 'great'. Then I discovered that if such tags are present you can then not add to the controls collection of the page (that's a whole different question!). But <%# tags are ok.
Is there a way I can inject a code-behind variable or function evaluation into the page using <%# ? Thanks.
<%%> are code blocks. You can put any server side code in them. This is a shortcut for <script runat="server"></script>.
<%=%> is for outputting strings. This is a shortcut for <script runat="server">Response.Write()</script>.
See here for more detail about <%%> and <%=%>.
<%#%> are used for data binding expressions.
See the index page for asp.net Page syntax.
The <%# inline tag is used for data binding, so if you want to use a code-behind variable inside it, you will have to bind the page or control the variable resides in:
Page.DataBind();
You can include this statement in the Page_Load or Page_PreRender event.
See this article for more information about the use of inline tags in ASP.Net, and this article for more about server-side databinding.

Include Content in .aspx masterpage

In my current project we have 5 different masterpages, there are some common elements in each and its really annoying making the change in all 5, it kind of defeats the point of masterpages.
I have tried having parent and child master pages but that caused other problems for a different day.
Is there a way to include dynamic content in a masterpage?
I'm looking for something similar to the php and coldfusion include().
You can put user controls (.ASCX) in your master pages. Is this what you were attempting to accomplish?
Like so...
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="WebForms.master.cs"
Inherits="Tunafish.Web.Views.Shared.WebForms" %>
<%# Register Src="~/Content/Controls/SiteNavigation.ascx" TagName="Nav"
TagPrefix="sc" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
<body>
<sc:Nav runat="server" />
Have you looked into User Controls? .ascx
Custom web controls are the way to go:
http://weblogs.asp.net/scottgu/archive/2006/11/26/tip-trick-how-to-register-user-controls-and-custom-controls-in-web-config.aspx
As mxmissile and JMP suggested, user controls are the way to go, but you might want to be thorough in your usage of them. When you include the master page, make sure you add the following markup along with the page declaration:
<%# MasterType
virtualpath="~/myMasterPages/Master.master"
%>
This will allow you to call functions/objects in your master pages so you can make changes to controls or have access from the page itself to various other objects. I have a property in my base usercontrol class called "ParentForm" that is a reference to the page it sits in. For user controls in the master page, I ended up having the same property and in the setter of that property I translate it down to the user controls.
You could set the masterpages to inherit from a class that dynamically inserts content or script to the page OnPreRender in code. It may seem out there but I have had to use this method.

Strongly-typed ASCX in WebForms 3.5?

I'm looking to get rid of the code-behind for a control in my WebForms 3.5 application. Again bitten by the bug of how it's done in MVC, I'd like to get a step closer to this methodology by doing:
<%# Control Language="C#" Inherits="Core.DataTemplate<Models.NewsArticle>" %>
This gives me the parser error you'd expect, so I remembered back to when this was an issue awaiting a fix in the MVC Preview, and changed it to:
<%# Control Language="C#" Inherits="Core.DataTemplate`1[[Models.NewsArticle]]" %>
But this doesn't work either! How is it that the MVC team were able to harness this ability? Was it something special about the MVC project type rather than the latest VS2008 Service Pack?
Short of giving up and requiring future templates to have code-behind files, what are my best options to get this as close to the generic user control method as possible?
Well, it appears like I've managed to do it. After looking at the PageParserFilter implemented by the MVC team for ViewUserControl<T>, I was able to construct something similar for my own DataTemplate<T> purposes. Sweet. I can now use the line:
<%# Control Language="C#" Inherits="Core.DataTemplate<Models.NewsArticle>" %>
And, without any code behind file, it parses! I'll report back if I find that I've broken something else in the process!
With WebForms you lose pretty much everything that makes them useful without a code behind page, because then VS can't auto generate the designer file that holds the actual definitions for all your runat="server" controls.
What you can do is have a common base page class, and make that generic:
public class DataTemplate<T> : Page {
public T Model {get;set;}
}
public partial class MyCodeBehindClass :
DataTemplate<Models.NewsArticle> {
...
}
This would allow all the drag-drop component stuff that WebForms does to work unhindered, while also allowing you to access a strongly typed model on the page:
<%# Control Language="C#" Inherits="MyCodeBehindClass" %>
<% foreach( var item in Model ) { %>
<!-- do stuff -->
<% } %>

Resources