New to C# and trying to use a global variable - c#

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.

Related

How to place Async="true" on masterpage

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.

How to call a function from Masterpage into new form in c#

I've a Master Page which contains a DropDownList. I've a function for binding the list in the master and it works fine.
My problem is: How will I call that Master Page function from a form, which is not the child of the above master page
See article here.
Here is something nice that comes from the new compilation model in ASP.NET 2.0. Let’s say you add a custom property to a master page code-behind file like so:
partial class otcMaster : System.Web.UI.MasterPage
{
public string FooterText {
get { return Footer.Text; }
set { Footer.Text = value; }
}
}
You can get to the master page for a web form using the inherited Master property, which returns a MasterPage reference. To get to a property defined in otcMasterPage though, you might think you need to use a cast.
((otcMaster)Master).FooterText == "foo"
Casting to a derived type is just a part of life when using frameworks and statically typed languages, but there is a better way. Use the # MasterType directive in the ASPX.
<%# MasterType VirtualPath="~/otc.master" %>
Now when ASP.NET codegens the page, it puts the following inside a partial class definition. Notice the Shadows keyword (that would be the new keyword in semicolon land [yeah, I’m experimenting with alternative languages]).
public new otc Master {
get { return (otcMaster)base.Master; }
}
The result is a strongly typed Master Page. We don’t need a cast, we can go right to the Master.FooterText property. Another way to do this is to specify a TypeName in the #MasterType directive.
Provide a public method in your MasterPage, then you need to cast the ContentPage's Master property to the appropriate type:
public void DataBindDropDowns()
{
// ...
}
Then you can call it from your ContentPages in the following way(assuming your masterpage's type is called SiteMaster:
((SiteMaster)this.Page.Master).DataBindDropDowns();
Edit:
...which is not the child of the above master page
I assume that means it's no a ContentPage of that Master, am i right?
Then it's not possible to get a reference to the master except when:
The master's method is static, what is impossible in this use case since you want to bind controls on the master
You have a reference to a page which master is of that type, but again impossible since the current HTTP-Handler is another page which does not use this master
Note that the master page actually is a child of a ContentPage and will be merged with it. It's not possible to get a reference to an object that does not exist!
From MSDN:
Note that the master page becomes a part of the content page. In
effect, the master page acts in much the same way a user control acts
— as a child of the content page and as a container within that page.
You need to refer to MasterPage property, cast to your master page type and invoke your method.
((MyMasterPage)this.Master).MyBindingFunction();
Put this in your page code (where MyMasterPage is your master page object):
MyMasterPage masterPage = (MyMasterPage) this.Master;
masterPage.MyBindDropDownListFunction(); // Replace with your public function name
If you're making it very frequently, you can create a BasePage derived from System.Web.UI.Page, and use it as the bage page for your forms.
There you can add a property of the type of your master page, that will give you acces to all public members of the Master Page.
If you master page class is Site1, you could do something like this in your BasePage.
public class BasePage : System.Web.UI.Page
{
protected Site1 Site1Master
{
get { return Master as Site1; }
}
}
Then in the pages where you need to acces the methods of the master page replace:
public partial class DefaultPage : System.Web.UI.Page
with
public partial class DefaultPage : BasePage
Then you'll have the property Site1Master available in the pages, and you can use any of its public members like this:
Site1Master.MyBindingFunction(...);
You can also add any other desired functionality in your BasePage.
NOTE: If you want to make sure that the property isn't null in the pages, you can add a check to see if the page has the Site1 master, like this:
protected Site1 Site1Master
{
get
{
if (!(Master is Site1))
throw new Exception("This page doesn's have Site1 as master page");
return Master as Site1;
}
}
For accessing the members of a Master page there's a Master property exposed on Page Content.
First you've to specify the # MasterType directive :
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
Then in the Master Page create a Public function and in your content Page you simply call
Master.MethodNameInMaster()
For better design use EventAggregator pattern. Create your custom event and handle it in Master Page.

access function in aspx page to master page

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.

How to make a code run on all aspx pages?

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
}
}
}

asp.net - variable pass between ascx and page

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.

Categories

Resources