For my webpages, I decided to create a reusable, external (that is, the code is a separate class outside of the page's own classes), class to deal with managing cookies in a certain fashion.
So in my class constructor, I did something like this:
private property cookiepageas Page
Public Sub New(whatpage as Page)
cookiepage= whatpage
End Sub
This allows me to pass the page context to my external class.
This way, I can get intellisense to allow me to do this:
private property cookie as httpcookie
cookie = cookiepage.Request.Cookies.Get(cookiename) 'get the current cookie
That compiles. The problem is that when I run it in the browser, I get this error:
Request is not available in this context
How, then, can I request the cookie from my external class?
(you can post vb or c# - I like both)
Ah, instead of passing the Page, I did this:
cookie = HttpContext.Current.Request.Cookies.Get(cookiename)
Related
I am writing my very first asp.net application and am trying to use the PreviousPage property to access data between pages. Visual 2010 is giving me an error which I don't understand, so I need some help to understand what I am doing wrong.
I have an application where I will bounce between all the pages using Transfer. That way, from a user perspective there is only ever one url that he sees. This url will be the one that makes him log in to the application (a application controlled function for now) and connect to the database. I therefore have an sqlclient.sqlconnection object that I wish to hand off to the next page called _dbConnection this is a private variable in my page class declared ...
Partial Class Protocol
Inherits System.Web.UI.Page
Private _dbconnection As SqlClient.SqlConnection
Public ReadOnly Property dbConnection As SqlClient.SqlConnection
Get
Return _dbConnection
End Get
End Property
...
Later down the code, in reponse to a click event on a button
Server.Transfer("PSetup.aspx")
In PSetup.aspx I have the following
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="True" CodeFile="PSetup.aspx.vb" Inherits="PSetup" %>
<%# PreviousPageType VirtualPath="~/Protocol.aspx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
Which should declare the Protocol class as the previous page
However in PSetup's Page_Load Sub I attempt this
_dbConnection = PreviousPage.dbConnection
where in this use _dbConnection is a private variable in the new page class.
Visual Studio is giving me an error 'dbConnection' is not a member of 'System.Web.UI.Page'
I have read through the documentation about this several times and I just don't understand what I am doing wrong. Could someone help me please.
I guess the first thing you need to understand is that ASP.NET is stateless. That means that no data is "saved" between pages. What the PreviousPage property does is it allows the request information persist through the use of a Transfer method, and the request information will be the GET or POST variables.
IMHO, the best way to do what you desire, is to have a shared public class that is not related to either page, and have a public function for getting the SqlConnection. Remember though, it is stateless, so you will have to create the connection each time.
Another alternative would be to save the dbConnection in the session (which I don't recommend, since it is possible to view the session information).
Otherwise, you can't have a variable persist with information between pages. Thats what is means to be stateless.
ALSO, for PreviousPage, keep in mind that it is creating an instance of System.Web.UI.Page, not an instance of Protocol. That means public properties won't exist from Protocol, only native features of Page will be there.
edit
From msdn
Note
Properties on the source page that are created primarily to expose values for cross-page posting are usually read-only properties. Although the source page can contain public read/write properties, setting a source page property from the target page property generally has no purpose, because the value will not be persisted.
try to make the dbConnection variable as Shared
Partial Class Protocol
Inherits System.Web.UI.Page
Private Shared _dbconnection As SqlClient.SqlConnection
Public Shared ReadOnly Property dbConnection As SqlClient.SqlConnection
Get
Return _dbConnection
End Get
End Property
But I'm not sure if it is a good practice passing data between pages that way
I would like to be able to return the text generated from an httphandler and insert it into my web page during an onload event. There are examples that show how to return an image by setting the image source to the path of the handler. But how do you do this for just text as in the "hello world" basic template. I would like the text value of a label on my page to be set to "hello world", preferably withour using javascript.
You can try using the session variable in your HttpHandler. By default you won't have access to the Session object.
You have include the following library:
using System.Web.SessionState;
After that the class should inherit IRequiresSessionState.
public class NewHandler : IHttpHandler, IRequiresSessionState
Later you can access the value of this Session variable from your code behind.
IHttpHandler.ProcessRequest method takes a parameter of type HttpContext. This class has a property Items, which is a name value pair. You can add your string to this Items collection and later refer to it where ever HttpContext is available. Thing to keep in mind is that the Items collection is per request, and does not persist across request.
There are different ways to set the title for content pages from Master page
by findcontrol
by creating property in master page and setting the value in content page
As both method requires an object creation of master page which will be little heavy
myMasterPage myMaster = (myMasterPage)this.Master;
so I have tried it by creating a class and it worked -
public class clsmaster
{
public static clsmaster objmaster = new clsmaster();
public strtitle {get;set;}
}
Now I just need to access this static object and set the property in the content page and in the master page I just need the controls to take the value from this class (clsmaster).
I would like to know which one is the better approach and why with description please?
I generally advise creating a BasePage class of some sort that encapsulates the behavior you want through all of your pages, these objects are assumed to always have the same master page, if you need other setups then you can create other objects as necessary.
From there you can create some properties or methods to allow the BasePage objects to access the master page or its associated properties in a very easy to code way such as this.Title = "MyTitle"
You can get fancier and create some virtual methods on your BasePage class that you can then override on the physical pages as necessary, to set titles, etc, as needed, without ever grabbing the Master page object directly (which yes, is annoying and ugly). This might look something like this.Title = GetTitle(); (GetTitle is a virtual method on the BasePage that is overridden in the child pages as needed for those pages you want to set a title for).
This makes strong use of inheritance and lets you add functionality to all of your pages very easily, it may be overkill for what your doing but I've never found a situation that was too simplistic for this architecture, it just works really well. I personally find this design far better than constantly using FindControl(), which tends to be error-prone when control ID's change, etc.
FindControl() is bad because if the control ID's change, then you might forget to update them in the FindControl reference, and now it'll break the next time its executed, I stay well away from static stuff like this if at all possible for this very reason, it's a cheap, quick but error-prone solution.
Accessing the Master page directly isn't inherently bad, I just can't stand stuff like:
myMasterPage myMaster = (myMasterPage)this.Master
Gets old, is uglier than it needs to be, wrap it in an accessor property at the very least ;)
I like the following better:
Title = "My Title"; // Property
or
Title = GetTitle(); // Virtual method
In ASP.Net, is anyone aware of a way to bypass Forms Authentication if a specific query string parameter is passed in?
Such as:
mydomain.com/myprotectedpage.aspx
...I would like to be protected by Forms Authentication (and so, redirected to login page)
mydomain.com/myprotectedpage.aspx?myBypassParameter=me
...I would like the page to render as normal
Is this at all possible?
Not really any "official" way of doing it.
You could do what I do, is have a base page instead of system.web.ui.page like so:
Public MustInherit Class ProtectedPage
Inherits System.Web.UI.Page
Private Sub Page_InitComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.InitComplete
If User.Identity.IsAuthenticated = False Then
If String.IsNullOrEmpty(Request.QueryString("myBypassParameter")) Then
FormsAuthentication.RedirectToLoginPage()
End If
End If
End Sub
End Class
In your code behind, you could simply use Request.QueryString["myBypassParameter"] and check its value. If it's an invalid value, then use FormsAuthentication.RedirectToLoginPage or a custom redirect to put the user back at the log in page. However, this doesn't seem like a secure method of protecting a page. What if someone got hold of the specific parameter and managed to gain access to your protected page? Also, you want to make sure that the QueryString value is valid (maybe by a regular expression) to ensure the user hasn't passed malicious code which will then be read by your application.
You might be able to jam some quick code into the Application_AuthenticateRequest event. You could then test for the parameter and adjust the User.Identity as necessary to allow the page. You'd have to put in a page check as well to make sure it didn't allow this behavior on all restricted pages.
I wouldn't recommend this design as an approach though. If you need to have a protected area accessed in an anonymous fashion, it'd be better to put all of your functionality into a UserControl and then use a protected/unprotected version of a parent page. This would allow you to control what goes out and when.
Like in Windows Forms:
Dim myForm as New AForm(Constr-arg1, Constr-arg2)
myForm.Show
... is there a similar way to Load a Page in ASP.Net. I would like to overload the Page Constructor and instantiate the correct Page Contructor depending on the situation.
Can you just link to the page passing parameters in the QueryString (after the ? in the URL) and then use them in the constructor (more likely PageLoad)
I think the best approach here for ASP.NET is to write User Control (*.ascx file) that represents page content, and load different controls based on current situation using Page.LoadControl() method. This solution is flexible enough, because only reference to control is its name. And this approach is much more useful than page constructor overloading as soos as you're not related on strong types, only on controls' names.
This isn't really the "correct" way to redirect to a page in .Net web programming.
Instead, you should call either Request.Redirect("~/newpage.aspx") or Server.Transfer("~/newpage.aspx"). You should then handle the request in the new page's Page_Load handler.
You can pass state between the pages by adding to the query string of the redirected URL (i.e. ~/newpage.aspx?q1=test), or by assiging values to the Session store (i.e Session["q1"] = value).