Why is this alertbox not appearing? - c#

I've got almost got a web project finished for an assignment, but I've hit a stumbling block in the form of an alertbox that refuses to pop up when called. The assignment is to create a web form for users to submit personal information to a website. Once they fill in all the textboxes and click a button to register, that will call the function registerMe in the code behind as seen below. Once they do that, the idea is that the function will first check to make sure that the user hasn't already registered on the website, then it will stuff all the values from the Textboxes into a Session object (which is using Candidate.curCandidate as a wrapper). This Session object will then be added to the Application state data to save it.
Now, here's the weird thing. In the if statement below, if the statement is true, all the values will be saved to the session and then the Application state data as desired, but the Alertbox won't appear. However, if the if statement is false, an Alertbox WILL appear. So, I'm guessing that somehow reading and writing all these values is interfering with the activation of an Alertbox, but I have no idea why.
protected void registerMe(object sender, EventArgs e)
{
String successText;
if (Candidate.curCandidate.appProperty == false)
{
Candidate.curCandidate.ssNumberProperty = socSec.Text;
Candidate.curCandidate.emailAddressProperty = email.Text;
Candidate.curCandidate.userIDProperty = userName0.Text;
Candidate.curCandidate.passwordProperty = password0.Text;
Candidate.curCandidate.dateOfBirthProperty = dateBirth.Text;
Candidate.curCandidate.firstNameProperty = fName0.Text;
Candidate.curCandidate.lastNameProperty = lName0.Text;
Candidate.curCandidate.streetAddressProperty = strAdd0.Text;
Candidate.curCandidate.cityProperty = city0.Text;
Candidate.curCandidate.stateProperty = state0.Text;
Candidate.curCandidate.positionProperty = jobs0.SelectedIndex;
Candidate.curCandidate.applicationStatusProperty = appStatus0.Text;
Candidate.curCandidate.appProperty = true;
Application[Candidate.curCandidate.ssNumberProperty]=Candidate.curCandidate;
successText = "Thank you. Candidate Information Added Successfully.\n" +
"E-Mail Address You Entered will be used to notify you of any\n" +
"updates for the position you applied for.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('" + successText + "');", true);
}
else
{
successText = "Registration unsuccessful.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('" + successText + "');", true);
}
}

Try to remove \n from successText and see if it works.
If you really need it, try to double escape it like below:
successText = "... Successfully.\\n"

Related

MailItem.Display(true|false) exception when used in WinForms

I'm creating an Outlook Add In, which has a subform. The form has a button on it, through which I would like to generate a mailitem, if the user clicks it. I'd like to auto-populate some info in the email, and then leave it for the user to send at their leisure.
My code looks like the following:
private void btnMailDocNotice_Click(object sender, EventArgs e)
{
string clientInfo = string.Empty;
string matInfo = string.Empty;
string author = string.Empty;
string dType = string.Empty;
string fLocation = string.Empty;
string keyWords = string.Empty;
string docName = string.Empty;
clientInfo = this.mCboClient.Text + " " + lblClient;
matInfo = this.mCboMatter.Text + " " + lblMatter;
author = this.txtAuthor.Text;
dType = this.mCboDocType.Text.ToUpper();
fLocation = this.txtSavePath.Text;
keyWords = this.txtKeyWords.Text;
docName = this.txtDocName.Text;
this.sendDocNotice = true;
this.Hide();
CreateMailItem(clientInfo, matInfo, author, dType, this.operatorCode.ToUpper(), fLocation, keyWords, docName);
this.Show();
}
private void CreateMailItem(string clientInfo, string matInfo, string author, string dType, string profiledBy, string fLocation, string keyWords, string docName)
{
this.DNoticeItem = (Outlook.MailItem)ThisAddIn.myApp.CreateItem(Outlook.OlItemType.olMailItem);
this.DNoticeItem.Subject = "Document: " + docName;
this.DNoticeItem.HTMLBody = "<span style=\"font-family:Calibri; font-size: 11pt;\">KeyWords: " + keyWords + "</span>";
this.DNoticeItem.HTMLBody += "<br />Client: " + clientInfo;
this.DNoticeItem.HTMLBody += "<br />Matter: " + matInfo;
this.DNoticeItem.HTMLBody += "<br />Author: " + author;
this.DNoticeItem.HTMLBody += "<br />Doc Type: " + dtClient;
this.DNoticeItem.HTMLBody += "<br />Profiled by: " + profiledBy;
this.DNoticeItem.HTMLBody += "<br />File://" + fLocation;
this.DNoticeItem.Importance = Outlook.OlImportance.olImportanceNormal;
this.DNoticeItem.Display(false);
}
The problem that I'm running into, is it fires an exception on the mailitem.display function, whether I use true or false (doing a bit of research says that determines if the user can access the main Outlook window or not while the mailitem is open). The exception is a COM Exception of "A dialog box is open. Close it and try again". I've tried hiding the WinForm prior to the function call that creates the mail item, then show it again after the function is exited, but it didn't work. I've tried a version of the code where I use System.Diagnostics.Process.Start() to try and open the file after saving it to disk, and while it doesn't fire an exception from the add in, Outlook prompts the user with a message box of the same message from the ComException. I even tried creating a field to see if the doc notice email should be drafted, and thought to have the code take care of that after a form.close() call, thinking the close call would at least dispose of the dialog box that was locking Outlook, and I still got the same exception.
Is there a way to achieve what I want? Does anyone have any suggestions? I'm kind of stuck at the moment, and would appreciate any help/pointers/suggestions anyone has to offer in this issue. My sincere apologies if this is a duplicative question - I couldn't find a good answer to the question. Thank you in advance for your time.
Firstly, why not display yoru own form modelessly?
Secondly (and this is pretty important) do not use code like the following
this.DNoticeItem.HTMLBody += "<br />Client: " + clientInfo;
Every time you run a line like that, you retrieve HTMLBody, add some stuff to it (making the HTML malformed), then set HTMLBody again and force Outlook to make sense of your (malformed) HTML. This (assuming Outlook can parse and fix your HTML) will result in HTML being returned to be different from what you set it to.
Build the HTML body once using a regular string, and set HTMLBody property only once.

Debugging: Microsoft JScript runtime error

I am desperately in need of debugging help, been stuck at this error for 6 days now.....
the error I get in my ASp.net app is :
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<script type='text/j'.
Below is the relevant code snippet,
CollyDataExchangeWebService Col_ValSub = new CollyDataExchangeWebService();
CollyReportServiceRequest ServiceReq = new CollyReportServiceRequest();
CollyReportServiceRequestData ServiceReqData = new CollyReportServiceRequestData();
ServiceReqData.AmendmentIndicatorSpecified = true;
ServiceReqData.AmendmentIndicator = false;
ServiceReqData.CollyReport = ColRep;
ServiceReq.ServiceRequestData = ServiceReqData;
ServiceReq.ServiceRequestHeader = ServiceHeader;
errValidate = null;
//btnOK.OnClientClick = "MSGShow()";
bool Valid = true;
string ErrMsgs = "";
if (((System.Web.UI.WebControls.Button)(sender)).CommandArgument == "Validate")
{
CollyReportServiceResponse ValResponse = Col_ValSub.validateReport(ServiceReq);
switch (ValResponse.ServiceResponseHeader.ServiceStatus)
{
case ServiceStatus.Successful:
btnOK.OnClientClick = "";
valHeader.Text = "Validation is Completed. No errors were found";
mlValPopup.Show();
break;
case ServiceStatus.ValidationErrors:
Valid = false;
ErrMsgs = ErrMsgs + _ValidationError(ValResponse);
ValBTN.Update();
mlValPopup.Show();
break;
case ServiceStatus.SystemError:
btnOK.OnClientClick = "";
Valid = false;
ErrMsgs = ErrMsgs + _SystemError(ValResponse);
ValBTN.Update();
mlValPopup.Show();
break;
}
After hours of debugging I found this line to be causing the error:
CollyReportServiceResponse ValResponse = Col_ValSub.validateReport(ServiceReq);
After 6 days of debugging and frustration I found that SOME records cause this issue and others dont in OLDER versions of the code but in new version ALL of the records lead to this error so it has to do something with the data in the DB which means SOME method in the code behaves differently to nulls but I cant find out exactly what the issue is because my app is 30k lines of code
after searching around and trying various solutions, the below 2 are not the solutions to my issue.
forums.asp.net/t/1357862.aspx
http://www.vbforums.com/showthread.php?t=656246
I want to mention that I am already having a difficult time dealing with this application because it was written by other programmers that are now long gone leaving behind non-documented or commented spaghetti code.
I did not code this but other programmers from past have put Response.Write in code:
private void MessageBox(string msg)
{
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
msg = null;
}
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
}
This one is in another method:
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("alert('No search resuls were found');");
Response.Write("</script>");
Or This:
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
}
After Jrummel`s comment I added this to code and then nothing at all happened.
private void MessageBox(string msg)
{/*
if (!string.IsNullOrEmpty(msg))
{
Global.tmpmsg = msg;
msg = null;
}
Response.Write("<script type=\"text/javascript\" language=\"javascript\">");
Response.Write("window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');");
Response.Write("</script>");
*/
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "<script type=\"text/javascript\" language=\"javascript\">" + " " + "window.open('ErrorPage.aspx?msg=" + "','PopUp','screenX=0,screenY=0,width=700,height=340,resizable=1,status=no,scrollbars=yes,toolbars=no');" + " " + "</script>";
cs.RegisterStartupScript(cstype, csname1, cstext1, false);
}
}
I have found the error after 2 weeks of debugging and 2 days of Brute Forcing:
In one of the 800 DB columns that I have there was a null/improper value. This value reacted with one of the 150 methods in my ASP.NET code in such a way as to present a JavaScript error even though Response.Write() was NOT the issue. I have not found which method it was that reacted to this value but I have found the solution which is to simply input a valid value on the column record..
How a programmer can brute force to find the issue:
In my case after long days of debugging I took a sample of one working record and another sample of an error leading record. Once I had achieved this, I used
DELETE FROM tablename WHERE UniqueColID= unique identifier for the error causing record
Then I did:
INSERT INTO tablename ([uniqueIdentifier],[ column 2],[column 3]) SELECT #UniqueIdentifierofErrorCausingRecord, column2, [column3] FROM TableName WHERE [uniqueIdentifier]=#UniqueIdentifierForWorkingRecord;
What the first statement does is delete the non working record then the 2nd statement reinserts that record with identical column values of the working record but with the UniqueIdentifier of the Non working record. This way I can go through each table to find which table is causing the error and then I can pinpoint which column of that table is the issue.
The specific issue in my case was DateTime.TryParse() because a table column value was inserted in improper format.. The code performed field population in one of the methods without a try and catch using the DateTime.Parse method.... After some testing it seems even a try/catch is not able to pick this error up as it is a javascript error..
Don't use Response.Write().
Instead, create a LiteralControl and add it to the page.
Use ClientScriptManager to add scripts to the page. Here's an example from MSDN:
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}

Script not working when called from .cs file

I am tryong to do the following in a Row_Command event of a gridview. But the the pop up box never comes up, I have tried it in so many different ways.. but yet no luck. Please if someone can see the issue i would really appreciate a pointer.
protected void Gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Merchant")
{
if (ItemsAvailable)
{
StringBuilder sb = new StringBuilder();
MyClass class = new MyClass();
TList<LineItems> otherItems = MyClass.GetItems(id);
bool IsNotAvailable = false;
foreach (LineItems item in otherItems)
{
Merchandise skuMerchandise = skuMerchandise.GetMerchandise(otherItems.mid);
if (skuMerchandise != null)
{
if (skuMerchandise.AvailableItems <= 0)
{
sb.Append(OtherItems.Name);
sb.Append(Environment.NewLine);
IsNotAvailable = true;
}
}
}
if (IsNotAvailable)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key",
"function Redirect() {location.href = 'homePage.aspx';}
if(confirm('The items : "+sb.ToString()+" will arrive in 1 month.
Do you wish to continue?') == true){Redirect();};", true);
}
}
}
Everytime i click the button, it just passes like nothing.. never prompts eveb though IsNotAvailable is true when I add a breakpoint.
You can go for a simpler way,
Define the javascript function in the design/separate script file so that it accepts the name of item. eg. myFunction(itemName)
And in your CS file, simply add a call to that function,
if (IsNotAvailable)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key",
"myFunction('" + itemName + "')
}
}
It will make things simpler and you would be able to confirm if this is a Javascript issue or a problem in how you are writing it through CS file.
Update:
Your first goal should be to make sure that your JS function is working for you, so before anything, add the following code in an empty html file and run it,
<script type='text/javascript'>
ItemNotInStock('item');
function ItemNotInStock(itemName)
{
var message = "The following items are no longer in stock :" + itemName + ".
Would you like to continue?";
if (confirm(message) == true)
{ location.href = "homePage.aspx"; }
}
If you redirect correctly then do what's mentioned below.
Define the following javascript in your design file(tested it locally, working for me in chrome,)
<script type='text/javascript'>
function ItemNotInStock(itemName)
{
var message = "The following items are no longer in stock :" + itemName + ".
Would you like to continue?";
if (confirm(message) == true)
{ location.href = "homePage.aspx"; }
}
In your C# code, add following line
if (IsNotAvailable)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "key",
string.Format("ItemNotInStock('{0}');", itemName);
}
}
Make sure your JavaScript code is executed by using breakpoints available in the developer tools of the browser of your choice, like Chrome Developer Tools: Breakpoints
BTW: Why do you create an instance of Merchandise if you instantly discard it with the next line?

RequiredFieldValidator ErrorMessage does not delete itself even though TEXT does?

This is some old code that I am not too familiar with :
RequiredFieldValidator vldRequired = new RequiredFieldValidator();
vldRequired.Display = ValidatorDisplay.Dynamic;
vldRequired.Text = "*";
vldRequired.ControlToValidate = "txtSetting";
vldRequired.ID = "vldRequired";
vldRequired.Enabled = true;
vldRequired.ErrorMessage = SettingTitle + " is required";
returnCell.Controls.Add(vldRequired);
Where, IF you tab passed a required field the * will show up next to it. THE ErrorMessage only shows up when a Submit is clicked (that is all fine).
However, once you fill in the required field and tab out of the input, the "*" goes away but the ErrorMessage stays -- I cannot figure out how to make that ErrorMessage go away when the * does.
Help?
Ok, I just ran into a similar issue on one of my projects. It's been a while since I've used the requiredFieldValidator. Try removing your Text Property as it interferes with the Error Message. Also ensure that you don't have a Validation Summary on the page as that may cause fixed messages to linger in front of the user even though they have corrected the the problem on the client side.
RequiredFieldValidator vldRequired = new RequiredFieldValidator();
vldRequired.Display = ValidatorDisplay.Dynamic;
//vldRequired.Text = "*";
vldRequired.ControlToValidate = "txtSetting";
vldRequired.ID = "vldRequired";
vldRequired.Enabled = true;
vldRequired.ErrorMessage = SettingTitle + " is required";
returnCell.Controls.Add(vldRequired);

Creating a customized "Yes / No" alert box in asp.net (javascript) - Part 2

I am trying to create a customized messagebox using javascript but not getting too far.
string txtConfirmMessage = "On " + DateTime.Now + ", ";
txtConfirmMessage = txtConfirmMessage + sUserID;
txtConfirmMessage = txtConfirmMessage + " added this record. Do you want to continue? ";
btnSubmit.OnClientClick = #"return confirm('" + txtConfirmMessage + "' Do you want to continue);";
I need to display a custom message involving the UserID, the date, and the value that the user has enetered. When I click the Submit button, the messagebox does not pop up.
Update:
I know this code is executed at the Page_Load event. However, is it possible to display in this alert box, a value that the user has selected (that action occurs after the page load event) ?
Any ideas to resolve this issue?
The javascript that you have is not valid, as the "confirm" method taks a single parameter, but you are giving it two bits.
Try this modified version.
string messageFormat = "On {0}, {1} added this record. Do you want to continue?";
string formattedMessage = string.format(messageFormat, DateTime.Now, sUserID);
btnSubmit.OnClientClick = "return confirm('" + formattedMessage + "');";
You just have an extra string after the one you're passing to confirm(), change it to this:
btnSubmit.OnClientClick = #"return confirm('" + txtConfirmMessage + "');";
About the update of the question, you could assign an OnClientClick event handler to the button as late as PreRender and the value will be persisted in the ViewState.

Categories