I need to create a code that reads the QueryString and set a value on the Session and on the end of the page I need to clear the Session.
How can I make a code like this to run on all .aspx pages?
Two possibilities are:
Create a class that inherits from System.Web.UI.Page. Insert your code there and all your pages inherit from that class instead of System.Web.UI.Page.
Create a HttpModule
well as i see it you got 2 solutions
Use a master page and do it there
Inherit Page and use that as base class on all your pages
One question why must it be stored in a session? this will give your problems if the same user executes 2 pages at the same time (the first to finish will clear the sesson for the other page)
if you only need the data while the page runs you can just save it in a normal variable, else use the viewState!
Or just use Global.asax: http://en.wikipedia.org/wiki/Global.asax
Create a class that inherit from Page that you will use instead of Page.
Alternatively, you can use a MasterPage if your application design allows that.
By putting the code in a basepage and letting all your .aspx pages inherit from the basepage.
An easy way to include code that is part of all pages is to subclass Windows.Web.UI.Page, and have all your pages inherit from this new class, instead of Windows.Web.UI.Page. The new class can register for page events, independently from each individual page.
Another option, if you don't want it to be part of each page, and you want to ensure that it runs even if a developer doesn't inherit your new page subclass, is to write an HTTPModule. This hooks into the ASP.NET processing pipeline, and you can trigger off pipeline events, such as authentication or displaying pages. You can write an HTTPHandler and run it out of the pipeline as well. (All pages implement IHTTPHandler, somewhere up the chain.)
I used the method of writing a class to inherit from System.Web.UI.Page. However, I did not find the implementation of this method to be obvious. Here is the code that I eventually wrote:
public class BasePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Code here will be run when any page loads that inherits from BasePage
}
}
}
Related
In my master page I will load some data from the database. I have place it into an asynchronous method. For normal pages I place Async="true" on the top but if I do it on the master page, I have the following error:
myproject.master does not contain a definition for AsyncMode and blablabla...
I've also search on the internet but nothing found for an asynchronous master page. Language I use on background is C#.
Can anyone help me?
The sample uses the new async and await keywords (available in .NET 4.5 and Visual Studio 2012) to let the compiler be responsible for maintaining the complicated transformations necessary for asynchronous programming. The compiler lets you write code using the C#'s synchronous control flow constructs and the compiler automatically applies the transformations necessary to use callbacks in order to avoid blocking threads.
ASP.NET asynchronous pages must include the Page directive with the Async attribute set to "true".
Master File contain master directive.
Master Page inherit MasterPage class of System.Web.UI which does not contain AsyncMode property..So you can't use it at master page.
Normal Page inherit Page class of System.Web.UI which contain AsyncMode.
You can set it in the master page like this. Found solution here:
public abstract class MyBasePage : System.Web.UI.Page
{
public MyBasePage()
{
this.AsyncMode = true;
}
}
Then change the inheritance in the aspx.cs file to something like this:
public partial class WebForm1 : MyBasePage
It can break the system when you set the AsyncMode property in anything else then the constructor.
I'm still new to MVC, so bear with me :-)
I've got a community site I'm working on, and I'd like to show how many users are online on all my pages after the user's been logged in.
I've got a shared view which is used as layout for all pages after login (UserLayout.cshtml)
Can I somehow add the logic to show online count to my shared layout ?
If it were WebForms I'd just have some code-behind for my masterpage, but this is obviously not an option here.
The information about users online is fetched from a cache. It's not available as a property on any of my View Models.
You can write an action which renders the information (using a very small view)
You can then call Html.Action to render it from the layout page.
You can create a 'UserLayoutModel' class and have all other view models derive from it. You can also use 'RenderAction' to have a part of the UI rendered separately (make sure you mark this action with ChildActionOnly attribute).
What I did was create a BaseController.cs that all controllers inherit from, and in the base controller you can override OnActionExecuting and any viewdata values you set here will be available to your master page.
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
base.OnActionExecuting(filterContext);
}
You can create a Global Action Filter.
Normally you add an Action Filter as an attribute to a method or class ([HttpPost]). Using a global Action Filter you can add code to every Action, without the need to inherit from a specific class. It is like you added an attribute to each and every Action method.
This article explains a lot.
I have a.master and b.aspx .
i have some functions in my aspx page.
how to access that functions in a.master page.
thank you
Let's say, you want to call Foo from b.aspx from a.master. So first thing is that you have make the method internal (or public) and then you can use code such as below in master page is call that method.
var page = (b)this.Page;
page.Foo();
Note that b will be the code behind class name in b.aspx. Note that above code will fail if you use another page c.aspx and use the same master a with it. Generally, I will say that invoking page specific functions from master does not make sense unless functions are present in some base page class and in such case you should be casting to that base page class.
Edit: More elaborate example as requested by Asif:
Consider your content page b.aspx such as
<%# Page Language="C#" MasterPageFile="a.Master" Title="Page B" AutoEventWireup="true"
CodeBehind="b.aspx.cs" Inherits="YourProject.b" %>
And in code behind file (b.aspx.cs), you have a method Foo such as
namespace YourProject
{
public partial class b : System.Web.UI.Page
{
void Foo(string someParameter)
{
Label1.Text = someParameter
}
...
}
}
Now in code behind (a.master.cs) of a.master page
namespace YourProject
{
public partial class a : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
b contentPage = (b)this.Page;
contentPage.Foo("Hello");
}
....
}
}
Of course you can make the method in b.aspx be public to call it in a.master. However I suggest you consider your design carefully. Because it's really weird just like that you call a method of a child class from its parent class (even though it's theoretically possible). Before your modification, ask yourself:
Is it necessary to call this method in the master page? If yes, do I have a better place to put the method?
As others have said, it's possible to do this. However, it's an odd way of doing things. You are probably going to be better off doing whatever you want to do in a different way. The whole idea of a master page is that it "wraps" many kinds of content pages. What if you content page doesn't have the function you want to call?
You could make sure all your content pages have the function, but then why not just put it in the master page?
Perhaps if you descired what you wanted to do a little better, we could advies you on a better way to handle things.
To access, either:
Make that method a static method.
Move your code in App_Code folder.
Move your code out of your web project, into some generic assembly and use that as a reference.
Is it possible to use global variables in C#? I'm coming from mainly a PHP background so variables are either accessible everywhere or just a global definition away.
My main issue is I have a User class that I built myself to wrap around the current users table on my company's database. I am defining it in the MasterPage but can't seem to access it from the actual pages (I don't know if there's a better word to describe them but they are the pages that inherit the styles and format from the MasterPage)
Any general tips or implementation practices for me?
EDIT: here's some code snippets of what I'm trying to do:
Site.master.cs
public partial class SiteMaster : System.Web.UI.MasterPage
{
public User user = new User();
}
logout.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="logout.aspx.cs" Inherits="logout" %>
<%# MasterType virtualPath="~/Site.master"%>
logout.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
User user = Master.user;
}
}
No, it is impossible. It is possible to create singletons or public static classes, but this is bad practice.
C# was designed for object oriented programming. If you haven't written programs using object oriented paradigm before it can be a bit hard to switch to it in the beginning. OOP (http://en.wikipedia.org/wiki/Object-oriented_programming) is built on three main concepts: inheritance, polymorphism and encapsulation.
You can defined classed apart of the pages/masterpages, it is good practice to define them in the App_Code folder.
Have a public static class and declare public static member variables.
That's what I do when I need some globals, though I try to avoid using them when I can.
If Page is inheriting from MasterPage, then make User property protected in MasterPage and it will be visible to Page.
The Master page class can be accessible to the pages that use it by setting the MasterPageClass in your .aspx page like so:
<%# MasterType TypeName="MyTypeName" VirtualPath="~/MasterPageName.master" %>
It sounds to me like you may just need to put your code in a slightly different place. A typical User class would be accessible to your project through a stand-alone class, and not bundled into a master page or a master type.
I might suggest that you add your User class into a new classfile in the /AppCode directory of your project instead, (User.cs). That would let you have access to it from your pages without having to muck with the MasterType.
See my answer to this question. Non-static class-level variables do no persist once the response is sent to the browser. This is because each Page object is going to be a new instance of the class, not the same one from your last request.
Use the "Session" property instead as I show in the link.
Is your problem, from your page, get to data stored in the masterpage (assuming we're talking about the ASP.Net MasterPage mechanism here)?
If so, you should look at strongly-typed access to masterpages. Basically, what you do is create a public property in your MasterPage class. Then, in your Page, declare the MasterPageFile and MasterType, like this:
public partial class MasterPage
{
public User CurrentUser{...}
}
In your page aspx, declare to use the masterpage and which master type to use.
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
You will then be able to access the property from within your page class like this:
var user = Master.CurrentUser;
Then, for the question on where to initialize the CurrentUser object, look at the list of page lifecycle events. As you can see, MasterPage.Init fires before Page.Init and MasterPage.Load fires before Page.Load. You can use either MP.Init or MP.Load to make sure the data is ready for when the page events fire, though Init is preferred.
There are at least a couple different ways to achieve what you want:
Use the Application object - It can be used to store things globally and is part of ASP.Net.
Use static classes - This is another option for creating a singleton.
Have any ways to keep a variables (object) in a page scope? I need pass some object from master page to all ascx files. Normally, i passing by using a method or structure with parameters. But now im asking another way to do this. Store it in session is a bad idea because my object should exists in a page scope only.
One way is to set up properties in your user controls. You have access to read and set these from all pages that implement them.
Another alternative is to store the shared object(s) in the HttpContext.Items collection.
You could expose your variables a public properties of the master page:
public string MyVariable { get; set; }
then access them from the user controls by referencing the master page, and casting to its specific type:
((MyMasterPageType)Page.Master).MyVariable
So you have masterpage, user controls and the page itself.
The page is the container for the masterpage and the user controls, hence it's the only one that 'knows' the 2 parties. So I'll suggest (if you haven't) you have the page instance to facilitate the object/variable passing amongst them.
If your variable's value is going to be changed on per page basis then i would recommend you to write that code in base page (or user control) and inherit all the page (or usercontrol),if the values are going to be similar for all pages(or user control) you can use cache object as well.
In a more better approach if you feel you can even create one helper class and call it from your base page (or user control), so you can separate variable assignment code from your page.