Get All aspx-files using a specific Master-page - asp.net

I'm trying to get the path for all the .aspx-files that has a specific MasterPageFile value.
Lets say I have a aspx-file called "hi.aspx" with the MasterPageFile="hello.Master" in the page directive. I want to get the value from the MasterPageFile property through reflection, in a method like so:
GetAllASpxFilesUsingMasterFile("~/hello.Master");
> hi.aspx
The problem Im having using:
var type = BuildManager.GetCompiledType(path)
Activator.CreateInstance(type)
is that the MasterPageFile-property is null.. ideas?

You have just called the constructor and created a new instance that´s why MasterPageFileProperty is null. There is no page life cycle involved which is necessary for populating pages with controls and properties.
To get the actual page life cycle process going you should call ProcessRequest() method but this is not advised at all.
Type type = BuildManager.GetCompiledType("~/Default.aspx");
Page myPage = (Page)Activator.CreateInstance(type);
myPage.ProcessRequest(HttpContext.Current);

Related

Previous page title in asp.net

I am trying to get previous page title in my asp.net application.
My attempt :
string previousPageTitle = this.Page.PreviousPage.Title;
I am getting "NullReferenceException" as Object reference not set to an instance of an object.
I do not want to use session or query string to get previous page title.
See this SO question.
Is the reference to this.Page returning null? You could try accessing it through the HttpContext object:
((Page)HttpContext.Current.Handler).PreviousPage.Title
I believe you are going to the page directly, thus resulting in PreviousPage being null.
See Page.PreviousPage property
When you use the Transfer method or use cross-page posting to transfer
processing from one ASP.NET page to another, the originating page
contains request information that might be required for the
destination page. You can use the PreviousPage property to access that
information. If the current page is being rendered as a result of a
direct request (not a transfer or cross-post from another page), the
PreviousPage property contains null.

How do I get an ID after saving an ExtBase Model?

After creating a model and adding it to a repository I want to have the new ID for different purposes (creating a mail, updating other fields outside the Extbase world)
$page = t3lib_div::makeInstance('Tx_MyExt_Domain_Model_Page');
$page->setTitle('Hello World');
$this->pageRepository->add($page);
At this point $page hasn't got an ID yet, uid is null.
$page->getUid(); // returns null
When does it get it? And how can I retrieve in on runtime?
In ExtBase, objects are "managed". This means every persistence transaction (add/remove/update) is simply noted in the underlying logic, but not yet executed until the appropriate time (like the end of processing a request). So, just because you add an object to a repository doesn't mean that it's actually added yet. That actually happens once $persistenceManager->persistAll() is called, which isn't something you need to do manually, ever. The point is, your $page object won't have a UID until it's saved and that's why $page->getUid() returns null. Look here for a great explanation.
I suspect that you are trying to do something outside of the ExtBase object/MVC lifecycle. At least, last time I got null when I tried to get the UID of an object, it was because I wasn't operating within the framework appropriately.
However, if you post some more code and give us a bigger picture of what you're trying to achieve, maybe we can help you get to a point where that object actually has a UID. For instance, if you're in a Controller object, tell us which Action method you're in, or if you're in a Repository object, tell us what you're trying to get from the repository and where/how you plan on using the query results.
EDIT
Just guessing here, but I'm assuming you're executing this code in some action of a controller. Since after the controller is executed a view is rendered, you can just pass the page object to the view:
$this->view->assign('page', $page);
And then in your view you can use the page object in a link:
<f:link.action action="show" arguments="{page:page}">
See this page object
</f:link.action>
And then in the show action of your controller you can show the page:
public function showAction(Tx_MyExt_Domain_Model_Page $page) {
// Do whatever you need to show the page in the `Show.html` template
}
I really am just guessing here. If you can give us a larger picture of what you're trying to do, what your action methods are supposed to do and things like that, we can answer your question a little more confidently.
(I'm also assuming that your page object isn't a replacement for the regular TYPO3 pages and that they are something totally different. It's much easier to deal with those TYPO3 pages through the backend interface than at the php level.)
You can call persistence manager explicitly in Your controller like this
#TYPO3 4.x
$persistenceManager = $this->objectManager->create('Tx_Extbase_Persistence_Manager');
$persistenceManager->persistAll();
#TYPO3 6.x
$persistenceManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager');
$persistenceManager->persistAll();

pass a value into next page

I have login page, once logged in I create a session variable to store the UserName.
I've used this variable to retrieve info for this User from Account table with AccountID, name etc and I return the AccountID on the page using a label (lblAccountID).
I have a button to "Add Funds" to this account, which redirects to the AddFunds.aspx page
How can I pass the AccountID into the AddFunds.aspx page which will be used to insert details into Funds table which has the AccountID.
I don't want the AccountID to be visible on the AddFunds.aspx page.
there are multiple ways to achieve this. i can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request. QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters.More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″);
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: "How to: Pass Values Between ASP.NET Web Pages"
You need to store it in a session variable:
int AccountIdVar;
Session["AccountID"] = AccountIdVar;
then you can retrieve later by
int AccountIdVar = (int)Session["AccountID"];
You can either use the session variable you stored in the previous page as it should still be accessible or another way is to pass the id over via a querystring such as www.foofoofoo.com?Id=23456.
As the others said, you can use Session or Querystring values. You can also just POST to the new page
The How To Pass Values Between Pages page is worth looking at too.
The MSDN article about Pass Values Between ASP.NET Web Pages is the best place to look for.
For this we can also use Global variable, create a module class in that declare all variables with public data type, then assign the values. Once the value is assigned it can be accessed from anywhere.

Get List of Controls on each WebForm in an Assembly

Is it possible to get a plain text list of controls that are present on a webform using reflection? Basically a colleague is looking to get a list of controls to help define a validation strategy e.g. in general product numbers must be numeric but on certain screens they can be alphanumeric.
I thought it would be straightforward using reflection to generate a list of something like:
AddProduct.aspx
txtProductNumber
txtProductName
etc.
I can get the form names but so far not the controls contained within. The current code looks like this:
Assembly assembly = Assembly.LoadFrom(#"Filename.dll");
Type[] types = assembly.GetExportedTypes();
for (int i = 0; i < types.Length; i++)
{
Page page = (Page)assembly.CreateInstance(types[i].FullName);
ControlCollection controls = page.Controls;
// At this point controls.Count = 0 presumably because the controls are defined as protected.
}
Assembly.CreateInstance has a couple of overloads. For example if I change the page assignment line to
Page page = (Page)assembly.CreateInstance(types[i].FullName, true,
BindingFlags.NonPublic, null, null, null, null);
then I get an error about a missing constructor.
So have I gone completely down the wrong path or is what I'm attempting to do actually possible at all? Any help is much appreciated.
Edit: Apologies for the delayed response to this question. We got a bit further using Assembly.GetCallingAssembly() to generate a list but it still didn't quite meet our needs. We used a more long-winded Find in Entire solution approach in the end.
Since you are just creating an instance of each page and not actually serving up the pages, I don't believe your approach will work since it will not have the pages go through their normal page request lifecycle that is responsible for creating the page and its child controls.
If this is a single website that uses the asp.net framework controls, you may be better off just doing a "Find in Files" for the tag prefix "
It seems to me that you are looking for controls that are created at runtime. If you want to find these controls at runtime, you can, both with reflection and (depending on the container) with other means. You should do so in the Page_Unload event, which is where most controls will have been loaded and still available.
But if you are trying to find these controls without processing your pages through the page-request life cycle, it can be daunting. Just creating a page with CreateInstance (or "new") for that matter won't run Page_Load, Page_Init or any of the other events. It wil only run the code in the constructor (which, as you found out, is protected, which doesn't mean you cannot instantiate it, but going through that trouble will give you little).

Can't get Session variable the way I want to

Partial Class Preferences_MyPreferences
Inherits System.Web.UI.Page
Dim userID As String = Session("UserID")
This is just a page in asp.net. I want to be able to grab the Session("UserID") but every time I try, I get this error:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
If I put that Dim userID inside say the Page_Load Event, then it works fine. Why does it have to be inside an event? I want to dim it once, and use it throughout the page.
Consider wrapping your call to the Session in a property in your code behind?
Public ReadOnly Property UserID() As String
Get
Return Session("UserID")
End Get
End Property
If you declare it as you have there, the variable is initialized and the session variable is expected to be ready for usage, but it is too early in the page life cycle to allow that. The preferred method would be as #p.campbell has suggested and wrap it in a Property or similar method. To answer the question though, the exception is generated because you are attempting to use session before it is available.
You need to read up on ASP.NET Page Lifecycles. The Session object doesn't become available until a certain point in the page lifecycle; if you want to grab the UserID once, you need to do it after the session becomes available.
The reason it doesn't work in your example is that the constructor for your Preferences_MyPreferences page is executed before the request object is available to the page. You should instead load it during the Page_Init or Page_Load event.

Resources