Submit function stopped working when Captcha Control Added - c#

I had everything working fine then when I put in the Captcha control it stopped going to the function where it creates the user.
So if I remove the control from the aspx page it works fine and goes directly to the CreatingUser function.
-- aspx --
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="true"
OnCreatedUser="RegisterUser_CreatedUser"
OnCreatingUser="RegisterUser_CreatingUser">
<cc1:CaptchaControl id="CControl" runat="server" CaptchaBackgroundNoise="Low" CaptchaFontWarping="Low" CaptchaLineNoise="Low" CaptchaMaxTimeout="300" ></cc1:CaptchaControl>
--Behind Code--
protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
{
Captcha.V2.CaptchaControl mycaptcha = (Captcha.V2.CaptchaControl)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("CControl");
mycaptcha.Validate();
Boolean answer = mycaptcha.IsValid;
if (answer == false)
{
e.Cancel = true;
}
// Testing area where it worked before just to see...
//
// .....
}

Related

WebForms model binding insert stopped working

I am using webforms model binding on EF6 code first project. I have a page that was working perfectly. It stopped working with no apparent reason. The insert method is not called anymore. I have another insert page and it works perfectly still. Anyone know of anything that would cause this?
Here is some of the markup that it is using.
<asp:FormView runat="server" ID="fvTour"
ItemType="CommonInterface.Tour" DefaultMode="Insert"
InsertItemPosition="FirstItem" InsertMethod="InsertItem"
OnItemCommand="ItemCommand" RenderOuterTable="false">
Code behind
public void InsertItem()
{
using (_db)
{
FileUpload picUpload = (FileUpload)fvTour.FindControl("fuploadTour");
if (picUpload == null || !picUpload.HasFile) return;
var item = new CommonInterface.Tour();
item.MemberID = (int)Session["MemberID"];
item.FID = LoginBLL.GetFID(item.MemberID);
item.TourSubmitDate = DateTime.Now;
item.PID = null;
item.TourState = ((DropDownList)fvTour.FindControl("ddlState")).SelectedItem.Text;
item.TourCounty = ((DropDownList)fvTour.FindControl("ddlCounties")).SelectedItem.Text;
item.TourLayout = ((DropDownList)fvTour.FindControl("ddlLayout")).SelectedItem.Text;
item.TourType = ((DropDownList)fvTour.FindControl("ddlType")).SelectedItem.Text;
TryUpdateModel(item);
if (ModelState.IsValid)
{
// Save changes
_db.Tours.Add(item);
_db.SaveChanges();
Response.Redirect("Default");
}
}
}
Edit 2:
Try to use OnItemCommand and see if that works. Set OnItemCommand="ItemCommand" back to your markup and try the following on code behind:
public void ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
InsertItem();
}
}
Make sure that the button you press has a CommandName="Insert" attribute set.
You should be able to set a breakpoint on this method at least. Then you can see if the button fires an event at all.

How to access the value attribute of a progress tag from backend code

I'm trying to make a progress bar to display during some "modifying" we are doing to 200,000+ rows from an excel document. I just wanted to try something simple, but I can't seem to get the value attribute from the progress tag.
For example if I had something simple like:
<asp:UpdatePanel ID="upnlPercent" runat="server">
<progress id="progressPercent" runat="server"></progress>
</asp:UpdatePanel>
And:
public static void CleanExcelSheet()
{
for(int i = 0; i < rows.Count; i++)
{
... // Clean whatever
progressPercent.Value = i / rows.Count;
upnlPercent.Update();
}
}
Is anyone aware of a simple way I could handle something like this? I'm open to other suggestions also if this doesn't really seem like a viable solution.
Thanks a bunch!
what you would want to do, is store the percent in a session var Session["percent"], and set a Load handler to your update panel where you would update the progress from the session var.
on client side, you would use javascript to make the update panel post back and update each certain amount of miliseconds.
an important thing to remember, is to run your cleaning function on a separate thread so it would not block your app, and allow the app to listen to post backs from the update panel.
here is an example of how to do it:
aspx:
this is our update panel with an element inside which we will update
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
<label id="Label_For_Server_Time" runat="server"></label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click" />
in your aspx header, add the following code:
this code calls the built-in asp.net postback function on the update panel, it will fire the Load handler of the update panel without refreshing the whole page
<script type="text/javascript">
window.onload = function () {
setInterval("__doPostBack('<%=UpdatePanel1.ClientID%>', '');", 1000);
}
</script>
code behind:
this is the load handler for the update panel, it fires everytime the panel is posting back from the aspx page, we are checking if the session var exists, and setting the label text:
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
if (Session["percent"] != null)
{
Label_For_Server_Time.InnerText = Session["percent"].ToString();
}
}
this is your function, we are running it on a separate thread to not block the app and setting the session var accordingly.
public void CleanExcelSheet()
{
new Thread(delegate()
{
for (int i = 0; i < 100000000; i++)
{
//... your cleaning here
float _f = (float)i / 100000000;
Session["percent"] = _f;
}
}).Start();
}
protected void Button1_Click(object sender, EventArgs e)
{
CleanExcelSheet();
}
On the server side, the type of progressPercent is HtmlGenericControl, which allows you to get/set properties like this:
progressPercent.Attributes["value"] = (i / rows.Count).ToString();
Or if the attribute is not already present, you may have to do the following:
progressPercent.Attributes.Add("value", (i / rows.Count).ToString());

Getting Javascript values from client on page load

I'm trying to determine the client window size on pageload, to use in creating a bitmap using c#. From reading on SO and elsewhere, I know that one method would be to:
Write a Javascript function to get the relevant values;
Store these in hidden fields;
Read the value using the code behind (c#) and then do stuff with it.
However, I'm getting tripped up by the execution sequence that runs code behind BEFORE any Javascript, even though I've set <body onload... to get and set the relevant values. (see below)
I know the rest of my code works, because, when I execute, the page shows the word "by" and the button. Then, after I have clicked the button and the page reloads, it can now suddenly read the two hidden values.
My question is, how can I get my c# Page_Load code to get those two hidden values from the client side, before it executes the rest of my code, and without the need for user action like clicking a button?
My page:
<body onload="getScreenSize()">
<form id="form1" runat="server">
<input type="hidden" name="hiddenW" ID="hiddenW" runat="server" />
<input type="hidden" name="hiddenH" ID="hiddenH" runat="server" />
<script>
function getScreenSize() {
var myW = document.getElementById("hiddenW");
myW.value = window.innerWidth;
var myH = document.getElementById("hiddenH");
myH.value = window.innerHeight;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hiddenW.Value+" by " +hiddenH.Value);
}
}
On first run (when I need those values), it shows
and after I click the button, it proves the Javascript works:
The question then, is how do I get those values before the rest of my Page_Load code runs, so that I can go straight into generating and displaying my image?
You cannot get the client window size before the C# Page_Load() executes because the page is rendered to the client after the C# code execution is complete.
The window size may change during page load, hence you have to get the window size only after page load is complete.
Solution:
You can use ajax to send the values to the back-end, after the page has loaded completely.
OR
You can cause a post-back using java-script after you get the correct value, this way:
JQuery:
$(function() {
var width = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
$('#hdn_width').val(width);
$('#hdn_height').val(height);
$('#your_form').submit();
});
C#:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// Use hdn_width and hdn_height here
}
}
catch (Exception ex)
{
}
}
Use the IsPostBack property
This would solve your problem
For Example
if(!Page.IsPostBack)
{
//Control Initialization
//Your code goes here
}
I used a timer to postback once and two none-displayed textboxes to store the window-values width and height. the textboxes are filled with a javascript:
document.getElementById('<%=TxWd.ClientID %>').value = window.innerWidth;
document.getElementById('<%=TxHt.ClientID %>').value = window.innerHeight;
In code behind (VB.NET):
Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Session("seswidth") = Val(TxWd.Text)
Session("sesheigth") = Val(TxHt.Text)
Timer1.Enabled = False
End Sub

Telerik window automatically opens after every page refresh

I am using Telerik RadControls in my project and and have a menu where I have an 'About' button. When I click the 'About' button a window pops up describing the application. The problem is if I refresh the page or navigate to another page then back to the first page the window automatically pops up.
The goal is only have that window pop up when the user clicks the about button.
here is the code I used to get that window:
<!--About Window-->
<telerik:RadWindowManager runat="server" EnableViewState="false" KeepInScreenBounds="true"></telerik:RadWindowManager>
<telerik:RadWindow ID="AboutMenu" Behaviors="Close" Animation="None" runat="server" Width="360px" KeepInScreenBounds="true" Height="360px" Modal="true" VisibleStatusbar="false" Skin="Glow">
<ContentTemplate>
<p style="text-align: center;">Sample Window Information</p>
</ContentTemplate>
</telerik:RadWindow>
Javascript
function OnClientItemClick(sender, eventArgs) {
if (window.args.get_item().get_text() == "About") {
var radwindow = window.$find(window.AboutMenu.ClientID);
window.args.set_cancel(true);
}
}
.cs
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
AboutMenu.VisibleOnPageLoad = true;
}
}
The window works but it loads whenever the page loads and thats where I think the line AboutMenu.VisibleOnPageLoad = true comes into play and is causing the error but when I take out that line it won't display at all.
Instead of using VisibleOnPageLoad try using the following code to open the window on itemclick.
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
string script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
}
}
Or, just use the OnCLientItemClicking event of the menu to open the RadWindow and cancel the postback. But you will need to fix you JS code, because the arguements are in the context of the current function. ALso, the reference to RW may break unless you have made your own array of ClientIDs.
function OnClientItemClicking(sender, eventArgs) {
if (eventArgs.get_item().get_text() == "About") {
var radwindow = window.$find(<%=AboutMenu.ClientID%>);
radwindow.show();
eventArgs.set_cancel(true);
}
}

Page.Unload Event inside a Update Panel

I have a Image Button declared as,
<div>
<asp:ImageButton ID="btnDoWork" runat="server" ImageUrl="/_LAYOUTS/1033/IMAGES/row.png" ValidationGroup="Page" />
</div>
<div>
<asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
</div>
within a update panel,
now in code behind I am doing something like this,
btnDoWork = (ImageButton)this.control.FindControl("btnDoWork"); //this code is in childcontrols method
btnDoWork.Click += new ImageClickEventHandler(btnDoWork_Click);
then
protected void btnDoWork_Click(object sender, ImageClickEventArgs e)
{
//Process a bit of code and at end,
this.Page.Unload += new EventHandler(Page_Unload_MessageBox);
and then in button click event,
public static void Page_Unload_Page_Unload_MessageBox(object sender, EventArgs e)
{
System.Globalization.CultureInfo _culture = Thread.CurrentThread.CurrentUICulture;
StringBuilder sb = new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("$('body').append(\"<div id='M'><span id='text'>" +
SPUtility.GetLocalizedString("$Resources:abc", "def", (uint)_culture.LCID) +
"</span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'>" +
SPUtility.GetLocalizedString("$Resources:OK", "def", (uint)_culture.LCID) +
"</a></div></div>\");");
sb.Append("function BB() { $('#M').remove(); $('#E').remove(); return false; }");
sb.Append("function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }");
sb.Append("</script>");
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Response.Write(sb.ToString());
Now if I put email address I get error while when it tries to Response.Write I think, I wonder what alternative is there, e.g. can I use triggers in update panel or any other event or something..
here's the error I am getting now,
Note: I changed all variable names so don't get confused if something doesn't match
The message is very clear, you can not add this command HttpContext.Current.Response.Write on update panel, and that because can not know how to handle it, because the update panel is return a struct that is used by the javascript to redraw some part of the page.
The solution is to add a literal control inside the UpdatePanel, in the place you wish to add the extra html code, and write that control the render as:
txtLiteralID.Text = sb.ToString();
How ever, here you have a diferent situation than the normal, you won to render and run a script.
The main problem is how to trigger the script to run. The only way is to use the UpdatePanel handler that is this standard code:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel run the code.
UnloadMsgBox();
}
</script>
Now on the EndRequest you need to call your script, where it may all read exist in your code as:
function UnloadMsgBox()
{
// render your code of the javascript.
$('body').append(\"<div id='M'><span id='text'></span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'></a></div></div>\");
function BB() { $('#M').remove(); $('#E').remove(); return false; }"
function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }"
}
and not need to render it on UpdatePanel.
To summarize:
On the update panel you can not use the Response.Write to render something but a literal control, that renders inside him.
On the update panel you can not render javascript code and expect to run, to run a javascript code you need to use the EndRequest handler that comes with the UpdatePanel.
MS Ajax calls perform full page rendering, calculate the diff from the original, send the diff to the client, and magically merge the diff in the browser.
If you just send javascript as response, it's something the framework does not expect and it throws the message.
See a previous answer on how to invoke javascript from an UpdatePanel.

Categories

Resources