web config string with a link asp.net webform - asp.net

I have a key in my webconfig
<add key ="ForgotPasswordPageNonMemberMessage" value ="You are not a full member and you will not be able to login. Please click here to discover more about full membership."/>
I would like click here to take me to my link e.g., www.abeprakash.com
Is this possible?
In the code I am simply using
lblFailureMessage.Text = ConfigurationManager.AppSettings("ForgotPasswordPageNonMemberMessage")

For now this is what I have done
<add key ="ForgotPasswordPageNonMemberMessage" value ="You are not a full member and you will not be able to login. To discover more about full membership"/>
<asp:Label ID="ForgotPasswordPageMessage" runat="server"></asp:Label>
<asp:Label ID="MyWebsite" runat="server">cilck here</asp:Label>
just simply show and hide MyWebsite based on the condition when ForgotPasswordPageMessage is shown.
Please suggest if you have any better way of doing this.

Related

Where is the code that runs when a button is clicked in ASP.NET

I'm trying to learn basic aspects of ASP.NET by analyzing the default Web Site project with Visual Studio 2010.
In the Register.aspx page there are fields for user registration and this button:
<asp:Button ID="CreateUserButton" runat="server" CommandName="MoveNext"
Text="Create User" ValidationGroup="RegisterUserValidationGroup"/>
The button does register an user, but I can't find the piece of code that is run and even less how code was associated to that button. I've tried searching the solution for all the identifier keywords and found nothing relevant. Searching on the web mentions a Button.OnClick method that I also can't find.
Any info on the basic aspects of ASP.NET will help me; thanks in advance.
Edit: hierarchically, the button is inside:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser">
<WizardSteps>
<asp:CreateUserWizardStep ID="RegisterUserWizardStep" runat="server">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
There is a RegisterUser_CreatedUser method on the code behind and it does:
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/";
}
Response.Redirect(continueUrl);
}
I was expecting some kind of inserting of user data on a database. I wonder, is this all that the button does?
The button you are looking it should be in CreateUserWizardStep control. I don't know much about this control but probably control looks for a child button having CommandName = "MoveNext", then it hooks for its click event.
Try changing the CommandName to something else like "test", it should NOT hit the breakpoint on RegisterUser_CreatedUser event.
Also note that CreatedUser <- event is telling that user is created, now the rest of the code is just authenticating the same user. Behind that, the user is already been created and saved in database.
If you also look in the web.config you will find this ConnectionString
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
Since you are using the Visual Studio's Default Web Application project, these all things are already done by Visual Studio for you.
An aspx page will also have a "code behind" file with the same name but a different extension (the letters after the dot) which depends on the language it's written in. Visual basic files have a .vb extension while C# files have a .cs extension.
Try looking for Register.vb or Register.cs and see if that's more fruitful.
If you're using a development environment like Visual Studio, you'll probably find that in the Solution Explorer you can click to expand the aspx file and see its code behind file underneath. If you're not, you might want to pick up a copy of the free express edition:
http://www.visualstudio.com/en-US/products/visual-studio-express-vs
When you find the code-behind, look for method called "MoveNext" - that's the code that'll run when you click the button, as specified by the CommandName attribute of the asp: Tag.
You've complicated a couple of things and you are completely not at fault but partly the project templates which comes with VS 2010 IDE. Let me try to help you one by one:
Learning basics of ASP.Net : For this you should be using "ASP.NET Empty Web Application" project template present in Visual Studio 2010. You've started with "ASP.NET Web Application" project template which has complicated things for
you. To start afresh "ASP.NET Web Application" looks the obvious choice for anyone though but it comes with a precooked boiler-plate code meant for ASP.NET membership forms authentication and its associated controls which is the root cause of all your confusion. To get started with the basics take the "ASP.NET Empty Web Application" project template I've suggested above and then add a new "Web Form" and then add various basic server web controls like button or text box to get started with concepts like event handling and code behind stuff.
Your other problem -
"The button does register an user, but I can't find the piece of code
that is run and even less how code was associated to that button"
That is because the button that you are seeing on Register.aspx page is
NOT an individual server web control but it is part of a composite control asp:CreateUserWizard instead. All the events of various controls be it a button, label or text box which are part of the asp:CreateUserWizard composite control is handled by the parent composite control asp:CreateUserWizard. You will NOT find all that code in your code behind file as this is present in System.Web.dll which is referenced in your project.
Since all the control events present on the composite control are handled by a common function written inside the code of composite control it has to distinguish exactly which control was clicked by the user (to take an appropriate action) which caused the current page post back for which CommandName property comes into picture. There is a switch case statement inside that common function for parent composite control which uses the CommandName property.
So essentially what happened is when you tried to start understanding basics of ASP.Net server web controls and event handling you actually got into the path of understanding ASP.Net Membership & role web server controls & providers which might be comparatively tough to understand and grasp initially. Hope this helps you to get started and further your understanding on ASP.Net world.

ASP.NET select element inside Layout Template

If I add Layout Template element like the following code, I am not able to select element directly.
<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false">
<LayoutTemplate>
<asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
</LayoutTemplate>
</asp:Login>
Instead, I need to select element like this:
String userName = LoginUser.UserName.Text;
Actually, what is the use of LayoutTemplate and why does it cause me not able to select element directly?
LayoutTemplate helps you designing multiple layouts.
You can have more than 1 layout.
The LayoutTemplate is only here to customize the appearance of the Login Control. The Login Control encapsulates the inner Control like an Placeholder. Maybe you want to use the Authenticate Event to get the username and password while verifying the userdata.
Cato, i have a similar question. but i was able to get the username and password text values with this code:
string userName = LoginUser.UserName;
string passWord = LoginUser.Password;
That 'UserName' and 'Password' property on LoginUser are string values, not the elements themselves, which is my problem. I need to get the element because i want to set focus on the username element. But Microsoft seems to have put us between a rock and a hard place, yet again, on this issue.
But it seems to me, that the string values are what you were looking for anyways. So maybe my response answers your question.

using postbackurl to pass variables without referencing ctl00$MainContent

I'm hoping there's a cleaner way of doing this. My source page markup has some simple inputs and a submit button:
<asp:TextBox runat="server" ID="TBPostDateFrom" placeholder="From" />
<asp:TextBox runat="server" ID="TBPostDateTo" placeholder="Present" />
...
<asp:Button ID="BtnDetailedResults" PostBackUrl="~/Auth/ResultsDetail.aspx" runat="server" Text="View Detailed Results" />
On my target page, I'm trying to reference those controls and use them as datasource select parameters. So far the only way I've found to do that is to use the long asp generated names "ctl00$MainContent$TBPostDateFrom" and "ctl00$MainContent$TBPostDateTo":
SDSDetailedResults.SelectParameters.Add("PDFrom", Request.Form["ctl00$MainContent$TBPostDateFrom"]);
SDSDetailedResults.SelectParameters.Add("PDTo", Request.Form["ctl00$MainContent$TBPostDateTo"]);
Is there a way I can reference those controls without using the long ct100$...? Or a way to reference the controls directly? I'm guessing if sometime down the road I change my master page, or content controls, these references would get messed up.
I've tried adding using adding the ClientIDMode=Static to the inputs like:
<asp:TextBox runat="server" ID="TBPostDateFrom" placeholder="From" ClientIDMode="Static" />
But that appears to only change the ID. On my target page, I'm still unable to reference it without using the ct100$....
I've also tried using the Page.PreviousPage method, but the objects end up empty:
if (Page.PreviousPage != null)
{
//post date
TextBox PostDateFrom = (TextBox)Page.PreviousPage.FindControl("TBPostDateFrom");
TextBox PostDateTo = (TextBox)Page.PreviousPage.FindControl("TBPostDateTo");
//at this point both PostDateFrom and PostDateTo are empty, if I do this:
SDSDetailedResults.SelectParameters.Add("PostDateFrom", PostDateFrom.Text);
SDSDetailedResults.SelectParameters.Add("PostDateTo", PostDateTo.Text);
// I get an IIS error saying the object references dont' exist, or are null
}
}
Thanks in advance, any help or guidance is much appreciated!
For a search page, I would recommend using the QueryString to pass information to your later page, rather than trying to reference the controls from the previous page.
This will be especially useful if you want to use this functionality from different technologies. You won't have to worry about where the request came from.
SearchPage.aspx:
//Button Click:
var page = "ResultsDetail.aspx";
var url = String.Format("{0}?TBPostDateFrom={1}&TBPostDateTo={2}", page, TBPostDateFrom.Text, TBPostDateTo.Text);
Response.Redirect(url);
ResultDetails.aspx:
var from = DateTime.Parse(Request.QueryString["TBPostDateFrom"]);
var to = DateTime.Parse(Request.QueryString["TBPostDateTo"]);
//Do search based on parameters
For more information: MSDN - How to: Pass Values Between ASP.NET Web Pages

Where are my Menu Items coming from?

I've taken over this website with no documentation (Yay!). Maybe this will help others to understand the SiteMap functionality. I have an idea how the SiteMenu is being built, but want to check with my buddies here at SO to be sure.
I have a Main.Master which calls for a SiteMenuHorizontal User Control.
<%# Register Src="uc2Menu.ascx" TagPrefix="uc2" TagName="smHorizontal" %>
...
<uc2:smHorizontal id="uc2Menu" runat="server" />
The User Control is pretty simple:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="uc2Menu.ascx.vb" Inherits="uc2Menu" %>
<asp:Menu id="siteMenu" runat="server" DataSourceID="menuSiteMapDataSource" Orientation="Horizontal" />
<asp:SiteMapDataSource ID="menuSiteMapDataSource" runat="server" ShowStartingNode="false" />
No help from the control's codebehind:
Public Partial Class uc2Menu
Inherits System.Web.UI.UserControl
Protected Sub siteMenu_MenuItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles siteMenu.MenuItemDataBound
e.Item.Target = CType(e.Item.DataItem, SiteMapNode)("Target")
End Sub
End Class
The Web.Config DOES specify a SiteMap:
<siteMap enabled="true" defaultProvider="objSiteMap">
<providers>
<clear/>
<add name="objSiteMap" type="LOC.DLL.objSiteMap" securityTrimmingEnabled="true" expirationInterval="1"/>
</providers>
</siteMap>
LOC.DLL.objSiteMap inherits SiteMapProvider and has overloads/overrides etc. The methods grab a table from a DB and build a SiteMapNode, or SiteMapNodeCollection.
My confusion is: How is this class populating my web page? There are no visible calls to the SiteMap.
My assumption is this:
When the site (or page) is built (or compiled?), my User Control calls its Datasource, Global.System.Web.UI.WebControls.SiteMapDataSource. Somehow, that control references the Web.Config for a reference to LOC.DLL.objSiteMap, and runs the Override/Overload methods to retrieve a SiteMapNode(/Collection), and return it back to my control?
I have a feeling I've got it down, but wanted to get a confirmation and/or clarification, and hopefully help others in the future who take over projects with dynamic site menus.
How is this class populating my web page? There are no visible calls
to the SiteMap.
SiteMapProvider is based on ASP.Net's Provider model, similar to Membership and Role providers.
My assumption is this: When the site (or page) is built (or
compiled?), my User Control calls its Datasource,
Global.System.Web.UI.WebControls. SiteMapDataSource. Somehow, that
control references the Web.Config for a reference to
LOC.DLL.objSiteMap, and runs the Override/Overload methods to retrieve
a SiteMapNode(/Collection), and return it back to my control?
Yes, your assumption is correct.
Your user control calls the default site map provider objSiteMap, and the sitemap is created on every page request dynamically.
FYI: Since you have set objSiteMap as the defaultprovider, you do not need to do anything. However, if you want a provider other than the default, you'll need to set a provider name explicitly.
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server"
SiteMapProvider="AnotherProvider" />
You're pretty much right on the money with your analysis.
The main connection here that I think you're missing is that the web.config value defaultProvider="objSiteMap" is what causes the SiteMapDataSource in your UserControl to connect to the "objSiteMap" provider in your web.config.
Since it is set as the "default provider", any SiteMap's in your project will be populated using that LOC.DLL.objSiteMap provider (unless you specifically override the default in the code).

asp.net sanitizing user input

Does asp.net have a built in mechanism that can sanitize all textbox input instead of redirecting to the error page?
I have a textbox input where a user can enter a name, but if they try to enter and <> tags the page automatically throws an error. I just want to handle this error in a user friendly way.
You'll want to look at the AntiXSS library for that. It's a dll so it's easy to drop in and start using it.
The download is at CodePlex.
You can use the ASP.NET RegularExpressionValidator control with a pattern like: ^[^<>]*$
<asp:RegularExpressionValidator ID="rev" runat="server"
ControlToValidate="txtBox"
ErrorMessage="The <> tags are not allowed!"
ValidationExpression="[^<>]*" />
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtBox"
ErrorMessage="Value can't be empty" />
The RequiredFieldValidator is used in conjunction with the RegularExpressionValidator to prevent blank entries. If that textbox is optional, and only needs to be validated when something is entered, then you don't have to use the RequiredFieldValidator.
The benefit of doing it this way is that the error can be handled gracefully and the user can be notified on the same page.
However, if you need to do this for many textboxes and you just want to present something nicer than the error page, you could handle the ValidateRequest error to provide a friendlier message and keep the user on the same page (not just replace it with a custom error page). For more info, check out Kirk Evans' post: Handling ValidateRequest errors within a Page (refer to the section titled Overriding the OnError Method).
Read this for a step-by-step: http://yourtahir.wordpress.com/2008/03/28/aspnet-not-allow-html-in-text-boxserver-error-in-application-a-potentialy-dangerous-requestform-value-was-detected/
You have to do some web.config work.
ASP.net has validation controls
[http://msdn.microsoft.com/en-us/library/7kh55542.aspx][1]
Also there is Mark Down Editor which is a control that strips out html tags etc.

Resources