Cookies viewstate are not maintaining in AjaxControlToolkit - c#

I have cookies and viewstate in below control .
This ajax Control is used to upload multiple file images.
protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
int userid = 25;
DAL_Cart objdalcart = new DAL_Cart();
if (Viewstate["Imagestringname"] == null)
{
objdalcart.InsertTempImage(userid, ImageName, 1);
}
else
{
objdalcart.InsertTempImage(userid, ImageName, 0);
}
Response.Cookies["JewelleryUserCookiesUserId"].Value = Convert.ToString(userid);
Response.Cookies["JewelleryUserCookiesUserId"].Expires = DateTime.Now.AddYears(1);
Viewstate["Imagestringname"] = ImageName + ",";
}
The issue is when I try to retrive view state value or Cookies value on different click event of button in same page I am not able to retrive the value
protected void lnkcheckout_Click(object sender, EventArgs e)
{
if (Request.Cookies["JewelleryUserCookiesUserId"] == null || Request.Cookies["JewelleryUserCookiesUserId"].Value == "")
{
}
if (Viewstate["Imagestringname"] != null)
{}
}
For both the case it is going in if condition. for viewstate I have placed Enableviewstate=true on master page .Any idea why?
Review
Want ajax multiple file upload on my button click event

var c = new HttpCookie("JewelleryUserCookiesUserId");
c.Value = Convert.ToString(userid);
c.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(c);
Just note: this is insecure. the client can manipualte the cookie...

Related

Winforms Webbrowser control URL Validation

I am trying to validate a winform web browser control url when a button is clicked. I would like to see if the web browser's current url matches a certain url. When I try to run this code the program freezes
private void button_Click(object sender, EventArgs e)
{
// Check to see if web browser is at URL
if (webBrowser1.Url.ToString != "www.google.com" || webBrowser1.Url.ToString == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else {
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
Here you go.
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Url = new Uri("https://www.google.ca");
// Check to see if web browser is at URL
if (webBrowser1.Url != null)
{
if (webBrowser1.Url.ToString() != "https://www.google.com" || webBrowser1.Url.ToString() == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else
{
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
}
1) Please use the schema with the URL.
2) Use ToString() as a function.

Checking that the query string has not changed

I have the following code to check that a query string has not changed:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Label_Error.Visible = false;
string query_string = Request.QueryString["GUID"].ToString();
Session["GUID"] = query_string;
}
else
{
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
}
}
Now, I have this code in a button-click event handler to check that the value of the query string has not changed (again):
protected void ImageButton_LogIn_Click(object sender, ImageClickEventArgs e)
{
Validation val = new Validation();
string GUID = "";
string query_string = "";
try
{
GUID = Session["GUID"].ToString();
query_string = Request.QueryString["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (val.EmptyString(GUID) == true || val.checkTransactionGUIDExists(GUID) == false || GUID.Equals(query_string) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
Now, the problems are two:
1) if I change the query string in the URL and click on the button, the user is not redirected to the error page.
2) if I change the query string in the URL and hit enter in the address bar, the user is not redirected to the error page.
What I want basically is that, when the user is redirected to the web page, it saves the query string into a session. If the user changes the value of the query string in the address bar, and either pressed enter in the address bar or presses my button, he is redirected to the error page.
However, my code is failing. Can anyone help please? Thanks :)
How about this instead?
protected void Page_Load(object sender, EventArgs e)
{
// Always get the query string no matter how the user go to this page
string query_string = Request.QueryString["GUID"].ToString();
// Only store the query string in Session if there is nothing in Session for it
if(null == Session["GUID"])
{
Session["GUID"] = query_string;
}
if (!this.IsPostBack)
{
Label_Error.Visible = false;
}
// Always check to see if the query string value matches what is in Session
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
This should solve your problem of the Session value being overwritten when a query string is put into the address bar and enter is pressed by the user.
I think you problem is that Response.Redirect needs the false at the final of the sentence like Response.Redirect("CheckOutErrorPage.htm", false); becouse that you have it inside the try cath the error will be throw.
I hope that help you.

XML nodes editing.

I assign values from a queryString to these textboxes and that works fine , but whenever I edit the text in one of them and try to get the edited data to be saved in XML node, I can't
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString != null)
{
TextBox_firstname.Text = Request.QueryString["column1"];
TextBox_lastname.Text = Request.QueryString["column2"];
}
else
{
}
}
Is there something with this code? It saves the unedited version in the nodes!
public string str_id;
public int id;
id = int.Parse(str_id);
XDocument xdoc = XDocument.Load(filepath);
if (id == 1)
{
var StudentNodeWithID1 = xdoc.Descendants("students")
.Elements("student")
.Where(s => s.Element("id").Value == "1")
.SingleOrDefault();
StudentNodeWithID1.Element("first_name").Value = TextBox_firstname.Text;
StudentNodeWithID1.Element("last_name").Value = TextBox_lastname.Text;
}
Page_Load is fired on every load (on postback as well as on initial load). Your code is currently defaulting those values from Request.QueryString on every load, before your event handler tries to save it.
Do this instead:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Request.QueryString != null)
{
TextBox_firstname.Text = Request.QueryString["column1"];
TextBox_lastname.Text = Request.QueryString["column2"];
}
else
{
}
}
If you are submitting the edited textboxes, then you will need to wrap the code in your Pageload with IsPostback check to ensure that values do not get reset to their originals.

Two dropdown in a page ( conflict )

Two dropdownlists drop1, drop2 have separate selected index changed. Any dropdown, on selectedindexchanged, goes to another page. If we use back button in browser it goes back to our home page and one of dropdown will be selected position. If we change the other dropdown, it works only the first selected index changed in the coding section
How can we solve this problem?
code
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
string zCenterId="0";
if(Request.QueryString["LCID"]!=null)
{
zCenterId = Request.QueryString["LCID"].ToString();
}
ManageActivityAdminUIController ObjCtrl = new ManageActivityAdminUIController();
List<ManageActivityAdminUIInfo> ObjInfo = ObjCtrl.GetActivityList(zCenterId );
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataBind();
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataTextField = "ActivityName";
drplistactivity.DataValueField = "ID";
drplistactivity.DataBind();
drplistactivity.Items.Insert(0, new ListItem("<--Select Activity-->", "0"));
ManageCoursesController ObjCtrl = new ManageCoursesController();
List<ManageCoursesInfo> ObjInfo = ObjCtrl.GetCourses(zCenterId );
drplistcourse.DataSource = ObjInfo;
drplistcourse.DataTextField = "CourseName";
drplistcourse.DataValueField = "ID";
drplistcourse.DataBind();
drplistcourse.Items.Insert(0, new ListItem("<--Select Course-->", "0"));
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void drplistactivity_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Activity.aspx?ActivityId="+drplistactivity.SelectedItem.Value);
Response.Redirect(url);
}
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}
If ViewState is off (on the dropdown or any of its parents - all the way up to the page) then the event won't fire. (It should post back though...)
The problem seems to be caused by the caching of your page.
I'd say that your two events are triggered, but you can not see it because of redirect
You may disable caching of your form :
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Response.Expires = -1;
or you may test the eventtarget inside your eventhandlers
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
if(drplistcourse.UniqueID!=Request.Form["__EVENTTARGET"])
return;
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}

DropDownList SelectedValue doesn't Change

In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protected void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}
Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}
You don't need to use Redirect and QueryString.
Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).
you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..
You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}

Categories

Resources