Moving data from one web form to another ASP.NET C# - c#

I am trying to move the content of a textbox on the from StudentRegistration to the form MyProfile by following a tutorial on YouTube. However when I try to reference the StudentRegitration Page in my code, I get the error that the type or namespace cannot be found.
In the tutorial I can see that in their code they have a namespace, however my website does not. Could anyone tell me what to do in order to be able to reference StudentRegistration without getting an error?
I should have stated that I have a website not a web app. I have found that websites do not have a default namespace. How would I go about accessing the StudentRegistration without referencing a namespace?
public partial class MyProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
lblEmail.Text = StudentRegistration.STextBoxEm;
}
}
}

Rather than answer your question directly, I'd like to point out another issue with your code that will probably prevent it from working. You should refer to the documentation on the PreviousPage property at: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage%28v=vs.110%29.aspx
It does NOT work like this:
user visits /StudentRegistration.aspx
user does stuff
user submits the form on /StudentRegistration.aspx
server redirects the user to /MyProfile.aspx
MyProfile class knows that PreviousPage = the class from /StudentRegistration.aspx
Instead, the description from the msdn reference page linked above stipulates that the PreviousPage property only works on this scenario:
user visits /StudentRegistration.aspx
user does some stuff
user submits form on /StudentRegistration.aspx
server transfers request to the MyProfile class
this does not mean that the url has changed to /MyProfile.aspx for the user, this means that the server is going to treat the current request to /StudentRegistration.aspx as if it were actually a request to /MyProfile.aspx
the user ends up seeing the result of what would normally be /MyProfile.aspx on /StudentRegistration.aspx
Now, your code may actually want that, but the fact that you have:
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
// this should be
// StudentRegistration LastPage = (StudentRegistration)PreviousPage;
}
makes me think that you have misinterpreted the somewhat misleadingly named PreviousPage property. For a sample of how to persist state across multiple page loads in .NET, I would recommend reading up on SessionState. It has a somewhat complicated name, but does more of what you would want in this scenario:
http://msdn.microsoft.com/en-us/library/ms178581%28v=vs.100%29.aspx
An added bonus is that you do not need to reference one class from another, so you fix your current bug later on. Additionally, even if you did resolve your potential namespace error, the issue that I outlined earlier will cause the value of the text field to be blank if your code is working as I suspect.

You are sending data from a source to a target - e.g. StudentRegistration -> MyProfile
You have options because at the end of the day, it is HTTP. Aside from "persistence" (Session), and the tutorial you are following, a "simpler" way is to use ButtonPostBackUrl.
All it means is that you are POSTing data to the target page. The target page (MyProfile) will have to validate and parse the posted data (Request.Form). This way you don't have to manage things like Session state.

Related

Restrict URL to specific database username ASP.NET

I am making a website tool isch with ASP.NET Framework, that lets a user/customer preview their website.
I have a simple database that gathers a SESSION["username"] and creates a with the source to the customer project file.
But if I have multiple users how am I supposed to prevent users from accessing each other's files using the URL? like if the directory for the customer projects is ? "~/Customer/SESSION["username"]/Default.aspx and user1 enters user2 in the directory instead. I will post some content of the page here to make it easier to understand.
Directory of my project
In the Default.aspx page I direct everyone that is not the user "admin". And inside the Default.aspx i have an IFrame that looks like this <iframe id="contentPanel1" runat="server" /> and it gets its src attribute from my Default.aspx.cs that looks like this:
using System;
using System.Web.UI;
namespace MyFeedbackWebsite
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Redirect("~/login");
}
if ((string)Session["username"] == "admin")
{
Response.Redirect("~/admin");
}
this.contentPanel1.Attributes["src"] = "https://localhost:44350/Customer/" + Session["username"].ToString();
}
}
}
In my Admin.aspx.cs I check if the username = admin and if the user is logged in:
using System;
namespace MyFeedbackWebsite
{
public partial class admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((string)Session["username"] == null)
{
Response.Redirect("~/Login");
}
if ((string)Session["username"] != "admin")
{
Response.Redirect("~/Default");
}
}
}
}
And in the /Customer/ Directory I want the customers project to be located. But as I mentioned, if the directory is /Customer/user1/Default.aspxI want the user1 value to match the current session. Thanks beforehand!
Best regards Max
A few observations
Now, I don't know the background of this project you're working on, but it seems you are relatively new to some of the concepts, so I'll just list a few things for you to think about:
If this is a new project I would highly recommend you to stop and instead look at ASP.NET Core or similar. .NET Framework is slowly being replaced by .NET Core, so a new project based on .NET Framework (such as ASP.NET Web Forms) will quickly become outdated (if it isn't already from the start).
If this is just a spare time/personal little project, all good (except for above point) - playing around with it is a good way to learn. If it's a commercial or otherwise serious project, however, I would recommend you to read up on security best practices in web applications. Restricting access to a page using a construct like Session["username"] != "admin" is bad business and very error prone. Take a look here for an example of configuring which users or roles can access which pages.
The problem in question
It's still a little unclear to me what part of your code handles/is run when accessing /Customer/user1/Default.aspx. But I would recommend you, that instead of having the username be part of the URL, you are getting the username from the session in the backend instead, and then serving the proper page matching that username:
User accesses the URL /Customer/Default.aspx
Backend verifies that user is logged in. If not, user is redirected to login page
Backend gets the username from the session and returns the page <username>/Default.aspx (note: this is not a URL, but a file path or something similar that points to the page you are serving - the user never sees this)
Now, the user will not be able to see another user's page because /Customer/user1/Default.aspx is not a valid URL - /Customer/Default.aspx is.

Is it possible to have a single URL that points to two different pages?

I have one url (/settings) that needs to point to two different pages depending on the users security on login. One page is the existing webforms page the other is a new MVC page. Is this even possible?
Additional Info:
When the user is on either page the url needs to say website.com/settings
Solution:
Convinced the PM to change the requirements.
The short answer, yes. You can do this several ways.
Javascript
Model View Controller (Controller)
ASP.NET Web-Forms (Method)
It is often poor practice to do such an event, as it can expose data. It is indeed possible:
Javascript:
$(document).ready(function () {
if($("#Account").val() != '') {
$(".Url").attr('href', 'http://www.google.com');
}
});
Pretend #Account is a hidden field that is populated from your database. If the field is not null then modify the .Url element to navigate to link. That approach for Web-Forms is the most simple.
Web-Forms:
protected void btnAccount_Click(object sender, EventArgs e)
{
if(User.IsInRole("Account"))
Response.Redirect("~/Admin.aspx");
else
Response.Redirect("~/User.aspx");
}
That would use the default Windows Authentication for the domain, you could bend and contort to use the database to pull data. An example, the Model View Controller would be similar as the Controller will simply handle that capability.
Hope this points in right direction.
This is a redirects based approach. Create a web page mapped to /settings, and have this code run on page load.
if(User.IsAdministrator()) //I take it you have some way of determining who is an Admin, so this is just example code
{
Response.Redirect("~/AdminSettings.aspx");
}
else
{
Response.Redirect("~/UserSettings.aspx");
}
Note that you'll need security on the Admin page to make sure a regular user can't just navigate directly there.

Inject JavaScript code from asp.net page into html page in another domain

How can I inject a JavaScript code from asp.net page into html page in another domain e.g http://www.codeproject.com/ . how to inject a JavaScript into this html page from my application
I am currently working on making a plugin just like Pinterest when the html page opens from my application it shows a bookmarklet just like Pinterest automatically on the page.
Below is the code I am using to inject JavaScript
public partial class ViewPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string script = "javascript:(function(){var jsdom = document.createElement('script');jsdom.src = 'http://localhost:15064/Script/delete.js';document.body.appendChild(jsdom);})();";
Response.Redirect(Server.UrlEncode(script));
}
}
Below is the Error I get After the execution of above code
Same Original Policy will not allow you to run scripts in someone else's domain.If this did not exist anyone could run scripts in any domain which would be a major security risk.
There are a couple *legal exceptions to this rule which you can read below
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
The only other way to accomplish outside of an agreement with both sides would be a violation of Same Origin and probably illegal.
Xss attacks are pretty common and do what you are describing.
The closest you will probably be able to get is a bookmarklet:
http://www.mattcutts.com/blog/javascript-bookmarklet-basics/
which is basically a shortcut to inline javascript.
An example in the wild is the X-Ray Goggles bookmarklet. You can add it by creating a new bookmark and pasting the location as:
javascript:(function(){var script=document.createElement('script');script.src='https://goggles.webmaker.org/en-US/webxray.js';script.className='webxray';script.setAttribute('data-lang','en-US');script.setAttribute('data-baseuri','https://goggles.webmaker.org/en-US');document.body.appendChild(script);})();
This won't let you inject from your application but it is a way of injecting into a doc from your browser.

How to use Skin.AddPageMessage() method?

I am developing a DNN module and I want to display an info message at the top of my ContentPane, not above the actual module. I have found that DotNetNuke.UI.Skins.Skin.AddPageMessage() should just do the thing. I am not getting the behavior I want though, the message just won't display at all.
There are few overloads of this method, one group accepting a Page object, the other one taking a Skin object.
public static void AddPageMessage(Page page, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType)
public static void AddPageMessage(Skin skin, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType)
I did take a look into the DNN source and found out that in the end they're actually using the same private static AddPageMessage(...) method, which just looks for a ContentPane within the provided control and adds a new ModuleMessage to the collection of its controls.
What should I pass as a Page or Skin parameter to get this correclty working?
Thanks ...
The private AddPageMessage method takes a fairly ambiguous "Control" as the first parameter. I believe that needs to be the current Skin, as it does a FindControl for ContentPane.
Doing something like this should get you a reference to the current skin:
var skin = Skin.GetSkin((PageBase)this.Page);
Skin.AddPageMessage(skin, "Header", "Message", ModuleMessageType.GreenSuccess);
the reason why the messages are not showing up is that you turned on "enable partial rendering" in the controlssetting of the modulecontrols.
If you are using AJAX (this is happening if you set the partial rendering to true) the DNN modulemessages are turned off from DNN itselfe.
Its enough if you have turned the partial rendering on just 1 control (dont have to be your control where you are acting from) on your page. DNN will wrap the whole page into ajax script manager and messages are not working anymore.
*EDIT 26.04.2012 10:45:
You can get the current ScriptManager by executing the following Code for example in you Page_Load(). If the manager is null, you dont have ajax enabled and the modulemessages should work. If bIsAjaxEnabled is true the modulemessages are disabled.
ScriptManager manager = AJAX.GetScriptManager(Page);
if (manager != null)
{
bool bIsAjaxEnabled = manager.SupportsPartialRendering;
}

CryptographicException: Padding is invalid and cannot be removed and Validation of viewstate MAC failed

Monitoring my global exception logs this error seems to be impossible to remove no matter what I do, I thought I finally got rid of it but it's back again. You can see a strack trace of the error on a similar post here.
Notes about the environment:
IIS 6.0, .NET 3.5 SP1 single server ASP.NET application
Steps already taken:
<system.web>
<machineKey validationKey="big encryption key"
decryptionKey="big decryption key"
validation="SHA1" decryption="AES" />
In my Page Base for all of my pages
protected override void OnInit(EventArgs e)
{
const string viewStateKey = "big key value";
Page.ViewStateUserKey = viewStateKey;
}
Also in the source of the page I can see that all of the ASP.NET generated hidden fields are correctly at the top of the page.
First of all lets start from the fact, that this error of view state happens on PostBack.
Also I must say that I have done all the things that every one suggest to do to avoid this problem. And I have single machine, but 2 pools that run the same Pages.
So someone do an action, ether a man, ether some other search machine by 'clicking' on your pages, or some hacker try to check your system for problems...
I have similar problems (rare but existing ones), and I finally found that people try to hack-test my pages. (from the same IP I have and dos attacks)
I modify the function LoadPageStateFromPersistenceMedium() that translate the viewstate, and see by logging what exactly was the input, and from what IPs... then I started monitor these results and see that the view state was changed by hand - or was totally empty.
On error I just redirect him to the same page...
Here is what I did...
public abstract class BasePage : System.Web.UI.Page
{
protected override object LoadPageStateFromPersistenceMedium()
{
try
{
.. return the base, or make here your decompress, or what ever...
return base.LoadPageStateFromPersistenceMedium();
}
catch (Exception x)
{
string vsString = Request.Form[__VIEWSTATE];
string cThePage = Request.RawUrl;
...log the x.ToString() error...
...log the vsString...
...log the ip coming from...
...log the cThePage...
// check by your self for local errors
Debug.Fail("Fail to load view state ! Reason:" + x.ToString());
}
// if reach here, then have fail, so I reload the page - maybe here you
// can place somthing like ?rnd=RandomNumber&ErrorId=1 and show a message
Responce.Redirect(Request.RawUrl, true);
// the return is not used after the redirect
return string.Empty;
}
}
Second Reason
Now there is one more reason why this can happen, and the reason is because some one click on your page before the __EVENTVALIDATION is loaded.
This eventValidation is placed on the last button-even that asp.net found, and if you have some of them on many place on the page, or near the button, then this go to the end of the page.
So even if you see the viewstate on the top of the page, where is the Validation ??? maybe this never loaded - page corrupt ?, too fast user click on page ?
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" ... >
To avoid this kind of problem I made a simple javascript that I do not let it press the button unless this input have been loaded !!!.
One more comment, the __EVENTVALIDATION is not always presents ! so is maybe safer not to search for this field if you make a general solution, but to make a javascript trick to just check if the full page is loaded, or something else that you think.
Here is my final solution with jQuery: (note that I check on PageLoad if eventvalidation exist !). I have this placed on my MasterPages.
<script language="javascript" type="text/javascript">
function AllowFormToRun()
{
var MyEventValidation = $("#__EVENTVALIDATION");
if(MyEventValidation.length == 0 || MyEventValidation.val() == ""){
alert("Please wait for the page to fully loaded.");
return false;
}
return true;
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
// I do not know if Page can be null - just in case I place it.
if (Page != null && Page.EnableEventValidation)
{
Form.Attributes["onsubmit"] = "return AllowFormToRun();";
}
}
You can test by placing near the button of your page a delay.
<% System.Threading.Thread.Sleep(5000); %>
Update
Today I see in log this message again for WebResource and what I discover is that a bot getting the pages and make all the character on the links in lower case, including the parameters, so this was one more reason to not getting the correct encoded string, and throw a message like Padding is invalid and cannot be removed.
Hope this help you more.
A survey of the web pages found with several of the keywords from the error message indicate that this type of error is relatively common, usually random (at least in appearance) and unfortunately rarely inclusive of an explicit work-around or explanation...
The existence of many similar-yet-different situations is probably tied to the very many different architectures and underlying configurations which can somehow lead to the inability of the crypto layer to assert the authenticity of the MAC (Message Authentication Codes) in the request pages:
Server farm setup
Cross domain / syndicated pages
third party widget libraries and such
Actual ASP program logic (of course)
One relatively frequent "marker" around these bug reports is the mention of resource requests (eg. WebResource.axd).
Note that such requests are often not logged (lest they inflate the log files size with event of relative little interest). This absence from the log file and the fact they are often cached (and hence the relative random and infrequent occurrence of the bug) may explain how this possible origin of the bug go "under the radar". This also suggests that in trying to recreate the bug, (while tracking in the logs, in real time etc) it may be useful to prevent the web browser from caching (or for the least to clear it cache initially).
In short, here are a few ideas and things to look for:
start logging the *.axd requests
try and co-relate such axd requests with the error events in the exception log
look for pages with resource references
if in a Farm setting, ensure that all instances use the same key (apparently the snippet provided in the question hint at multiple IIS servers)
Be suspicious of pages with 3rd party tie-ins (search services, affiliate programs...)
Hope this helps ;-)
Are you sure your problem is cryptography related, and not caused by oversized ViewState?
If ViewState is the problem, you can chunk it - change the value of pages / MaxPageStateFieldLength in web.config

Categories

Resources