I have a problem and I would really appreciate your help.
An external application is sending via GET some parameters on address of my asp.net page. (something like http://mypage.com/default.aspx?id=123). I read this parameter on page load and do some other things.
If I receive the parameter correctly I must answer immediately the external application (the same which send me the parameter) with plain text 'OK'.
How to do this reply with c# asp.net ? Any sample code ? Thanks in advance for help.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Page.Request.QueryString["id"];
if (!String.IsNullOrEmpty(id))
{
SendAnswer();
}
}
private void SendAnswer()
{
// ??????? send simple reply 'OK' as plain text
}
}
You can send anything you want with Response.Write. You might have to do Response.Clear first.
Related
Everyone that has responded to my questions have been so very helpful and I am closing in on finishing this app. My challenge now is to make 3 fields read only based on a login.
I have the following code that does exactly what I need and assign the currently logged in user to a text field. What I want to do is make some other text fields (Read Only) if the login user does not equal a specific value. For example, if submitted_by_email_username does not equal administrator1#samplecompany.com then make the text field (Salary_in) which is a textbox, Read Only. I can read code much than I write it these days so I apologize if this is a simple request. I would like to make three fields Read Only based on that logic in the COde Behind.
protected void Page_PreInit(object sender, EventArgs e)
{
if (submitted_by_email_username != null)
{
_ = Context.User.Identity.Name;
if (User.Identity.IsAuthenticated)
submitted_by_email_username.Text = User.Identity.Name;
}
}
First of all, you don't need code in Page_PreInit 99.9% of the time in webforms. Even with dynamic controls you would only need Page_Load.
But you can make a TextBox readonly by using the Enabled property.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
submitted_by_email_username.Enabled = false;
submitted_by_email_username.Text = User.Identity.Name;
}
}
I was using Form Authentication in my test. And also have some test user name .But found a weird problem for a specified name. That is all of test names except only one named amybeyond can works in the test.
Please help to review my code in my test.
LoginTest.aspx (This is a login form for user name and password input.)
public partial class LoginTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//after succeed validating user. then redirect to LoginSuccess.aspx page.
bool bValidate=Membership.ValidateUser("amybeyond", "11111111");
if (bValidate)
{
FormsAuthentication.SetAuthCookie("AmyBeyond", false);
Response.Redirect("LoginSuccess.aspx");
}
}
}
LoginSuccess.aspx (In this page, just simply test if current request is authenticated after redirecting.)
public partial class LoginSuccess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//the HttpContext.Current.Request.IsAuthenticated always false in the IE.
if (HttpContext.Current.Request.IsAuthenticated)
{
Response.Write("ok, you login successfully.");
}
}
}
I am sure the Membership.ValidateUser is successfully executed and return true. The problem is it can't know the authenticated status after successfully redirecting.
I didn't know if I miss something or did something wrong. If there is . Please help to tell me .thanks.
Added
I read the source code of FormsAuthentication.SetAuthCookie. and add the cookieless="UseCookies" in the Forms element of the Web.config. Hope to make sure the cookie is added to the Response(This is done by the source code HttpContext.Current.Response.Cookies.Add(cookie)). Still doesn't work.
public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
Initialize();
HttpContext current = HttpContext.Current;
if (!current.Request.IsSecureConnection && RequireSSL)
{
throw new HttpException(SR.GetString("Connection_not_secure_creating_secure_cookie"));
}
bool flag = CookielessHelperClass.UseCookieless(current, false, CookieMode);
HttpCookie cookie = GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
if (!flag)
{
HttpContext.Current.Response.Cookies.Add(cookie);
current.CookielessHelper.SetCookieValue('F', null);
}
else
{
current.CookielessHelper.SetCookieValue('F', cookie.Value);
}
}
Added
The http capturing detail shows below. in the LoginTest.aspx there is a cookie named FwLoginCookie , after redirect to LoginSuccess.aspx this cookie is lost. please help to review it .
Finally got why did this weird thing happen! It is because there is an another cookie named ACA_USER_READ_ANNOUNCEMENT sent to response. It is so large size (more than 5800bytes) that the browser (in my test it is IE) would ignore all the cookies include the Form authentication cookie(about 300bytes).
But other browser like chrome/firefox is not the same behavior with IE when encounter this case (huge cookie size.).
If it is not right . Please kindly correct me . Thanks.
Having just added a new button in my web application, I get an error when clicking on it, and I'm wondering if this is related to misplaced code. I will describe what/where I did, briefly. Thanks very much.
In ascx file:
<asp:Button ID="btn_rezerv" runat="server" Text="Reserve film" OnClick="btn_rezerv_Click"/>
In the ascx.cs file:
namespace CinProj.UserControls
{
public partial class FilmsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string categId = Request.QueryString["CategID"];
string filmId = Request.QueryString["FilmID"];
....
if (categId != null)
{
.....
}
if (filmId != null)
{
......
Button btn_rezerv = (Button)item.FindControl("btn_rezerv");
}
}
protected void btn_rezerv_Click(object sender, EventArgs e)
{
string fid = Request.QueryString["FilmID"];
ShoppingCartAccess.AddItem(fid);
}
}
}
"Server Error in '/' Application.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "
Another problem could be because your PopulateControls method should probably only be called when during the Page Load when it's not a PostBack. I can't tell from above, but to me it looks like it only needs done on Load. Try wrapping that call with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateControls();
}
}
It's likely the result of making some sort of client change that the server doesn't know about. Many times this is the result of changing values in a dropdown in JavaScript, for example.
To fix, you could:
Do away with using JavaScript for said modification
Use an UpdatePanel and add your control to it. If the client needs to make a change, trigger the UpdatePanel's update in order for the control's viewstate to update.
I have a button on my aspx page. I want to use javascript confirm before continuing execution when clicking on that button. I can do it easily if i am writing javascript in aspx page itself . But my problem is each time the confirm message may be different. I need to check various condition to generate appropriate confirm message.
Can I call confirm in my code behind, so that I can construct confirm message from there?
What I'm trying is:
protected void Button1_Click(object sender, EventArgs e)
{
//just the algorithm given here
string message=constructMessage(); \\ its just a function to construct the confirm message
if(confirm(message)) // i know i cant use javascript in code behind direct. How can i do this
{
//do something
}
else
{
// do nothing
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string message=
"if(confirm("+message+"))
{
//do something
}
else
{
// do nothing
}";
this.ClientScriptManager.RegisterStartupScript(typeof(this.Page), "warning", message, true);
//Prints out your client script with <script> tags
}
For further reference on ClientScriptManager
I just got this link which describes different ways of calling javascript
http://www.codedigest.com/Articles/ASPNET/314_Multiple_Ways_to_Call_Javascript_Function_from_CodeBehind_in_ASPNet.aspx
may be this will help..
Is it recommended to check the Page.IsPostBack in a user control Page_Load Event like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
I am getting wierd results
Edit ~ Here is the thing. When the main form is loaded, I use Request.QueryString to get the customer id which I then place in a SESSION variable.
On the control Load event I read the SESSION variable to get the data for that customer. So, do I need to check PostBack at the control level?
Edit ~ Here is the load event of the control
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Getting and storing the customer account number
if (string.IsNullOrEmpty((string)Session["CustomerNumber"]))
{
Session["CustomerNumber"] = cust.GetCustomerNumber(myHelper.GetCustomerIDFromQueryString());
LoadProductData();
}
}
}
Here is the myHelper Class
static class myHelper
{
public static Guid GetCustomerIDFromQueryString()
{
//Getting the GUID (used as customerid in CRM) from the URL request of the selected account.
return Sql.ToGuid(System.Web.HttpContext.Current.Request["ID"]);
}
}
}
If you use "!IsPostBack" in page load, when the user click other control it do a postBack, so you don't get your data.
I hope that helps you.
Just checking it for no reason? Absolutely not. If you should do something only on first load and not on subsequent post backs then it's the pattern that should be used.
Are you sure that you will always have a "CustomerNumber" already stored in the Session by the time you get to your page? Is there any rhyme or reason that you can find as to when you get data and when you don't?