I am new to ASP .NET, I am trying to setup a website in Visual Studio with C#.
My background is in PHP. In that language, if I want a variable to be accessible by every page, simply put it in a include file.
Is there anything similar to C# and ASP .NET? There is an site.master page, but I am not sure how to access it's variables from page contents. Thanks in advance.
You have a few different options here:
Session Variables
Session variables are stored in the server's memory for each user, and can be read and written to as often as required. These are limited to a per-user basis, so if you want to hold a single variable for all users, then this isn't the way to go.
Usage:
Session["MyVariable"] = 5;
int myVariable = (int)Session["MyVariable"]; //Don't forget to check for null references!
You can to set a user's session variable in your global.asax file under the session_start event handler if required.
Application/Cache Variables
Application and Cache variables are accessible by any user, and can be get/set as required. The only difference between the two is that Cache variables can expire, which makes them useful for things such as database query results, which can be held for a while before they're out of date.
Usage:
Application["MyVariable"] = 5;
int myVariable = (int)Application["MyVariable"]; //Don't forget to check for null references!
You can set an application variable in your global.asax file in the application_start event handler if required.
Web.Config
This is probably the preferred way of storing constants in your application, since they are stored as "Application Settings" and changed in your web.config file as required without having to recompile your site. application settings are stored in the <appsettings> area of your file using this syntax:
<appSettings>
<add key="MyVariable" value="5" />
</appSettings>
Web.config values should be considered read-only in your code, and can simply be accessed using this code in your pages:
int myVariable = (int)System.Configuration.ConfigurationSettings.AppSettings["MyVariable"];
Static Variables
Alternatively, you could just create a class that contains a static property to hold your variable like this:
public class SiteVariables
{
private static _myVariable = 0;
public static int MyVariable
{
get { return _myVariable; }
set { _myVariable = value; }
}
}
And then access it like this:
int myVar = SiteVariables.MyVariable;
I actually use a combination of the latter two solutions in my code. I'll keep my settings in my web.config file, and then create a class called ApplicationSettings that reads the values from web.config when required using static properties.
Hope this helps
You could create a static class with a static member:
public static MyClass
{
public static MyVariable { get; set; }
}
Then from anywhere in the site you can call MyClass.MyVariable to get or set the value.
Keep in mind a significant difference between this and PHP. In PHP, you're running scripts and you include other scripts to make one big script. In ASP.NET, you're compiling code into assemblies. The patterns are different.
Indeed, just to have something like global php variable static classes could help you. But is it A Really what you whant? Because global variables are known to be harder mantainable, testable, etc...
Probably you want to "put" data somewhere and "take" it some where else.
There are A LOT out of the box ways to do it in .NET.
You can use SessionState to store something while session with a user lasts
http://msdn.microsoft.com/en-us/library/ms178581.aspx
You can use ViewState as a short term...
http://msdn.microsoft.com/en-us/library/ms972976.aspx
You can use settings to setup variables in web.config
http://msdn.microsoft.com/en-us/library/b5ysx397.aspx
You can use Profiles to store something related to user
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
You can use Application to store something more globally
http://msdn.microsoft.com/en-us/library/ms178594.aspx
And there are more...
Treat this post as "links" addition to Karl Nicoll's post.
You can access a property ( or field or method) on the master page by the Master property on your content page, which gives you a reference to the master page. You will need to cast it to a type that supports the property first, though:
((Site)Master).MyVariable
And MyVariable has to be visible to the content page, public or internal I think. And ideally you'd cast to a base type for the Master page, not directly as in the example above.
If it is a config option, use web.config file app settings section
If it is a session variable there is a session object
And you can also create an static class with some public members.
Related
I wanted to use some data from one page to another. General solution is to use Session (most of recommends). My boss don't like sessions and he suggested me to do same work by using C# Property in common class as below
public static long parentId { get; set; }
and set it one one page as
Common.parentId = "any value";
and use it on other page like
string anyVariable = Common.parentId
and it worked. We get rid of session expiration as well. But why most of people recommend session. Is property another state management thing?
If you are going to store some data using simple static property you must understand that it will be shared among all your users. Sessions are not for this. But I don't see any reasons not to use sessions if you want to store user data somewhere.
In my project it is very convenient, especially when we use SQL-server to store sessions - we can update our website without any losing users' sessions data.
You can check all possible ways to hanle sessions for example here http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx
I am building a web application. The authentication will be managed by the website, that is not my concern. What i need to store is the UserID in some place.
Once they open the application I will be able to get their UserID. I was previously using a Session variable to store this. Can I create a class say:
static string _UserID;
public static string UserDetails
{
get
{
return _UserID;
}
set
{
_globalValue = \\value from webpage;
}
}
and use UserDetails._UserID instead of assigning it to a session variable?!
The website's session server is not very reliable so I thought I could use this way.
Will this work?
I learnt from the answers that the variables will be overwritten for each user which is not what I want!!
Will it be the same scenario if i create an instance of this class in handler and assign the UserID to it??
are there any other way where I can make its scope limited only to one user i.e UserID with which I login should be same and if new user login to the application it must not be overwritten?? what is the disadvantage of using this method??
Is this method good if I use only one page and assign the object in the launch of the applciation ??
Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class.
The main problem is that static variables are shared across ALL USERS, and that is dangerous in your case that you pretend to store an UserID inside it. If you want to store
per user sessoin ID you should use Session
You can find more info here:
Lifetime of ASP.NET Static Variable
static filed will be shared between all users that means you would overwrite it for everyone. If you do not want to store it in Session you may store it in cookie (encrypted if security is important).
This is possibly very lame question and I lack knowledge about ASP.Net. In this case a link to an article explaining would be very welcome.
I'm working on web-site on ASP.NET with C# as codebehind. My current project involves developing few pages with very similar functionality and a many functions are the same. For example
private void PermissionCheck()
{
if (null == Session["UserID"] ||
null == Session["ProjectID"] ||
null == Session["AssetID"] ||
null == Session["ProjectName"])
{
Response.Redirect("~/Login.aspx");
}
}
Would be the same on 2 pages. Some other things are the same as well. I would like to put this into common base class. But there are other functions that don't really belong to pages at all:
private string GetAttachmentTempPath()
{
return Request.PhysicalApplicationPath + WebConfigurationManager.AppSettings.Get("AttachmentsTempFolder");
}
I would like to move this into Attachment class, but to get the physical path of the application, I need to pass in Request object into that method, which is not really nice, as it couples Attachment class with Page.Request object.
Is there any way to move these functions somewhere else without needing to pass Page.Request objects around??
p.s. The appliction is huge, and there is no scope to change the entire architecture.
For your permission thing you could make a base page class:
class BasePage : Page
{
...
protected override OnInit() {
// do check here
}
}
Now you can implement your page like this class MyOtherPage : BasePage { ... }
The OnInit gets executed everytime your MyOtherPage gets loaded.
You can see a complete page lifecycle here: Link
For your other problem: Consider to implement a global available static tool class
Update
A good approach for making things like web.config easier to access is a Singleton. In asp.net a singleton is only created once and lives until the asp worker process gets stopped . So this values are shared across the whole asp.net application. This is also good for storing data in a global context that you dont want to get out of your database or file anytime a user makes a page request (for example a version number or things like that)
Update 2
To access the request without passing it to every function, use this:
HttpContext.Current.Request
Base page is a good option for reusable code in Page level. Other than that for things like configuration values it's good to come up with utility classes specifically for those methods base don there type of operations.
If you need to avoid passing in Page object into these types of utility methods,
HttpContext
class would be handy because you can access many of the ASP.Net object through static members through this class. HttpConext # MSDN
If you have similar functions behind the page, you can use ASP.NET WEb User Control.
You can create the functions in the usercontrol and use the control in the pages where necessary.
Have look at this article about Web User Control in Asp.Net
How can I update and get values in a Windows Forms application while moving one form to other form (like cookies)?
I need to update the values to some variable and again I am going to refer stored values and need to do some calculations.
I have used cookies in ASP.NET but I am not able to find out the same concept in .NET Windows Forms (C#).
How can these issues be resolves?
You can use object references.
You can decalre a read/write Property for each variable you want to be available in another form and the use them for sharing your data.
One way to do this is to declare variables to be public, either in a global module or in any form.
public x as double
If it is declared in a module, you can access it with the variable name only. To access data declared in another form, use that form name with the variable: form1.x = 7
Another way is to declare a property in a form or other class.
A really simple way of getting cookie-like functionality would be to declare a static string dictionary in Program (Program.cs)
public static System.Collections.Specialized.StringDictionary SortOfLikeCookies = new System.Collections.Specialized.StringDictionary(); and read/write string values using Program.SortOfLikeCookies["Name"] = "Value";
What is the best way for classes to retrieve/store constants without getting them through web.config?
Store them as static in a class, something like this:
public static class DbConstants
{
public static const string CustomersTableName = "CUST";
public static const string ProductsTableName = "PROD";
...
}
Consider separating them in several classes to group them logically, e.g. one class for DB constants, one class for exception messages, etc.
You include a static class with all your constants in it.
public static class MyConstants
{
public const string MyString = "ConstString";
public const int TestInt = 100;
// etc...
}
That depends on how "constant" they are.
If they are really constant, that is something that would never ever change, then a static class with constants in it. E.g. the number PI, or perhaps a constant containg the name of a field in a table.
If they are more server specific, like connection strings, and you don't want to use the web.config, you might want to check out the option of including a new config file from web.config
<appSettings file="local.config">...</appSettings>
The local.config should then just contain an appSettings element. If the local.config file doesn't exist, it will be ignored. So no exceptions. Any setting that exists in both local.config and web.config, the local.config will be used. You can then share a web config file between many installations, and have local settings overridden in the local.config.
If the constants are more something that a superuser should be able to modify at runtime, then a table in a database is what I would choose. E.g. a if you would let a superuser modify a max password retry attempt count or something.
XML files and use Application Cache to improve performance or uou can use ASP.NET Configuration Files.