File Download popup overwrites the alert popup - c#

When the user clicks on the "Export to Excel" link, the standard "File download" dialog is presented to the user. See here for an example image.
But before exporting the excel file, I want to display an alert popup. But the Save dialog is obscuring the view of the alert popup.
How can I display the popup without it being obscured?
Here is my code...
dsResult = clsObj.getSearchResults_BL(detObj);
if (OrdDifference != null && OrdDifference.Any())
{
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alert('.....')", true);
set(dsResult, strName);
}
else
{
set(dsResult, strName);
}
private void set(DataSet ds, string strFileName)
{
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2007;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
try
{
sheet.Name = strFileName;
sheet.ImportDataTable(ds.Tables[0], true, 1, 1, -1, -1);
...
workbook.SaveAs(strFileName, ExcelSaveType.SaveAsXLS, HttpContext.Current.Response, ExcelDownloadType.PromptDialog);
}
catch (Exception ex)
{
}
}

Your problem is here:
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alert('.....')", true);
set(dsResult, strName);
Because the set method in your program is writing to the Response Stream the call to ScriptManager.RegisterClientScriptBlock ends up doing nothing.
You need to do this on two steps:
if (OrdDifference != null && OrdDifference.Any())
{
//Just do this, nothing more.
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alertUser('Some Message Here')", true);
}
Now define the alertUser function in Javascript:
function alertUser(message)
{
alert(message);
window.location='AccepServiceOrder.aspx?o=Export';
}
Now on Page_Load check for the o parameter in the query string
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["o"]!=null)
{
dsResult = clsObj.getSearchResults_BL(detObj);
set(dsResult, strName);
}
}

Related

DotNetNuke WebForm Alert Dialog box

I am currently developing a DotNetNuke module. However, I failed to prompt user an alert dialog box in certain situations like record duplication.
I am using the following code to display an alert box in Controller class.
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
The following is my full code.
Form.ascx.cs
void cmdUpdate_Click(object sender, EventArgs e)
{
UdtController.UpdateRow(Data, ModuleId, False);
}
UdtController.cs
public void UpdateRow(DataSet ds, int rowNr, bool isDataToImport)
{
var values = new Dictionary<int, string>();
string strIsUnique = "";
foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows)
{
var strColumnName = field[FieldsTableColumn.Title].ToString();
strIsUnique = field[FieldsTableColumn.Searchable].ToString();
var strValueColumn = ((!isDataToImport &&
ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName +
DataTableColumn.
Appendix_Original))
? strColumnName + DataTableColumn.Appendix_Original
: strColumnName);
if (strIsUnique == "True")
{
int uniqueDataCount = FieldController.uniqueData(currentRow[strValueColumn].AsString());
if (uniqueDataCount == 0)
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
else
{
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
break;
}
}
else
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
}
FieldController.UpdateData(userDefinedRowId, values);
}
You need to reference the Page, not create a new form.
Page page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
However DNN has it's own message box you could use:
http://uxguide.dotnetnuke.com/UIPatterns/AlertDialog.html

Conditional confirm box in c#

How to call a conditional confirm box from c#.
I have 2 hidden fields and based on the condition I want to call confirm box.
After that I also want what user has pressed (clicked on yes or No).
Design:-
<input type="submit" id="btnAddPaymentMethod" onserverclick="AddPaymentMethod_Click" runat="server" value="add payment method" />
Code:-
protected void Next_Click(object sender, EventArgs e)
{
if (hdnDefault.Value == hdnPrimary.Value) { return; }
else
{
//open confirm box
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "confirm('Do you want to save new default payment method?');", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
}
I have tried below jQuery Code:-
function Confirm(msg) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(msg)) {
confirm_value.value = "Yes";
$('#btnAddPaymentMethod').click();
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
protected void Next_Click(object sender, EventArgs e)
{
if (hdnDefault.Value == hdnPrimary.Value) {
return;
} else {
//open confirm box
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "Confirm('Do you want to save new default payment method?');", true);
}
}
protected void AddPaymentMethod_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes") {
ScriptManager.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
} else {
ScriptManager.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
function Confirm(msg) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
confirm_value.value = confirm(msg)? "Yes" : "No";
document.forms[0].appendChild(confirm_value);
$('#btnAddPaymentMethod').click();
}
I have not run your code. But when you have runat="server" for an input control it will append with the asp.net unique Id. So try to access the input control by it's name ending with btnAddPaymentMethod as below.
Change from $('#btnAddPaymentMethod').click(); to $('[id$=btnAddPaymentMethod]').click();
This jQuery code will open a confirm dialog, with an 'ok' and 'cancel' buttons.
Here an anchor tag with an id of myConfirmPageLink, when clicked, will ask for confirmation. If ok is clicked it proceeds to the target, and if cancel is clicked it stays on the same page.
$("a#myConfirmPageLink").click(function(){
return confirm("Are you sure you want to go to that page/site ?");
});
This should be easy to modify for your purposes.

Implement check availability functionality on save button

I have created a link button in aspx form which check availablity of login email address and its functionality is as.
protected void lnkCheckAvailable_Click(object sender, EventArgs e)
{
SystemUserBL bl = new SystemUserBL(SessionContext.SystemUser);
ds = new DataSet();
bl.FetchForLoginEmailAddress(ds, txtLoginEmailAddress.Text);
if (ds.Tables[0].Rows.Count > 0)
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>This User Name is already in use by another user.</b>";
}
else
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>Congratulations! " + txtLoginEmailAddress.Text + " is available.</b>";
}
}
It's working fine when user will click on check availability link button. There is another button "Save" which saves the user information in the table. Now my issue is that if it displays "This User Name is already in use by another user." message the information is still saved in the database. Please tell me how to prevent this!!!
You can return true or false based on user name exists in database or not. You can create a method which will check user availability.
When user press save button you will call that method if method returns true it means user exists.
private bool CheckUserAvailability()
{
SystemUserBL bl = new SystemUserBL(SessionContext.SystemUser);
ds = new DataSet();
bl.FetchForLoginEmailAddress(ds, txtLoginEmailAddress.Text);
if (ds.Tables[0].Rows.Count > 0)
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>This User Name is already in use by another user.</b>";
return true;
}
else
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>Congratulations! " + txtLoginEmailAddress.Text + " is available.</b>";
return false;
}
}
You can also call this method on link click.
protected void lnkCheckAvailable_Click(object sender, EventArgs e)
{
CheckUserAvailability();
}
You will call this method on Save button if user don't exist than save information in database.
protected void Savebtn_Click(object sender, EventArgs e)
{
if(CheckUserAvailability() == false)
{
SaveUserInfoToDataBase();
}
}

Word Add-In Ribbon

I created an Office Add-In project and I added ribbon menu for application. When I build my project word document have my ribbon there is no problem.
How can I save the active document as a file using StreamReader when clicking on a button from the ribbon menu using the button click event below?
private void btnsavefile_Click(object sender, RibbonControlEventArgs e)
{
//Getting FileStream here.
}
I found the following solution in Stack Overflow. Hopefully it is relevant to you.
Serialize current ActiveDocument from office 2007 add-in
Personally, I have done the same when I was dealing with this scenario. I have saved a copy of the file to the temporary location and pushed the copy to the server. In this case, the active document stays as is.
Excel.Workbook xlb = Globals.ThisAddIn.Application.ActiveWorkbook;
xlb.SaveCopyAs(filePath);
Hope this helps!
void Application_DocumentBeforeClose(Word.Document document, ref bool Cancel)
{
try
{
string filePath = this.Application.ActiveDocument.FullName.ToString();
string fileName = this.Application.ActiveDocument.Name;
//dialogFilePath = filePath;
dialogFileName = fileName;
string tempFile;
string tempPath;
if (true)
{
var confirmResult = System.Windows.Forms.MessageBox.Show("Are you sure to save this document ??",
"Confirm Save!!",
System.Windows.Forms.MessageBoxButtons.YesNo);
if (confirmResult == System.Windows.Forms.DialogResult.Yes)
{
//document.Save();
var iPersistFile = (IPersistFile)document;
iPersistFile.Save(tempPath, false);
//Do some action here
}
Word._Document wDocument = Application.Documents[fileName] as Word._Document;
//wDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
ThisAddIn.doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
}
catch (Exception exception)
{
}
}
Create Word Addin project-> Add Ribbon visual designer from add new item.
Add menu to Ribbon designer and write below code in ribbonsample.cs
public partial class RibbonSample
{
private void RibbonSample_Load(object sender, RibbonUIEventArgs e)
{
// Initialise log4net
}
//Adding items in menu from DB
public RibbonSample()
: base(Globals.Factory.GetRibbonFactory())
{
InitializeComponent();
try
{
System.Data.DataTable dt = new DataAcces().GetData();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
RibbonButton Field = this.Factory.CreateRibbonButton();
Field.Label = dt.Rows[i][1].ToString();
Field.Tag = i;
Field.ControlSize =
Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
Field.Click += Field_Click;
menu1.Items.Add(Field);
}
}
else
{
System.Windows.Forms.MessageBox.Show("No Fields are available in database");
}
}
catch (Exception exception)
{
//thrw exception
}
}
//Select menu item text in word
void Field_Click(object sender, RibbonControlEventArgs e)
{
try
{
Microsoft.Office.Interop.Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;
currentRange.Text = (sender as RibbonButton).Label;
}
catch (Exception exception)
{
log.Error(friendlyErrorMessage + " Field_Click Details:" + exception.Message, exception);
}
}
}

Editing HTML with a WYSIWYG Editor

I have a datagridview with HTML strings. Using a CellDoubleClick event, I am displaying the html string in a WebBrowser control.
In Form1
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex != 0 && e.RowIndex != -1)
{
string s = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
this.f2 = new Form2(s);
f2.ShowDialog();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
In Form2
private IHTMLDocument2 doc;
string reply;
public Form2(string reply)
{
InitializeComponent();
this.reply = reply;
}
private void Form2_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = reply; <--- string from DataGridView
IHTMLTxtRange range = doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML(webBrowser1.DocumentText);
range.collapse(false);
range.select();
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
}
Using the above code, I can successfully display the HTML string as a plaintext, however I am unable to edit it. Alternatively, if I use this code:
private IHTMLDocument2 doc;
private void Form2_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = reply; <--- string from DataGridView
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
IHTMLTxtRange range = doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML(webBrowser1.DocumentText);
range.collapse(false);
range.select();
}
It will be a blank form, but I will be able to write to it.
I have a feeling it has to do with range.pasteHTML(webBrowser1.DocumentText); being in the Form2_Load method, but I'm unaware of any other method that will allow me to display the HTML string from the DataGridView upon opening Form2.
I want to allow users to be able to edit the HTML string as plaintext (after which it will be converted back to HTML and displayed in the datagridview).
Its possible! You can edit HTML using the default WebBrowser control,
Add a reference to the "Microsoft.mshtml.dll" file, available here.
Assuming your WebBrowser is named "browser", add this code in the Form.Load event
(browser.Document.DomDocument as mshtml.IHTMLDocument2).designMode = "On";
Call the following functions to format the selected text:
browser.document.ExecCommand("Bold", false, null);
browser.document.ExecCommand("Underline", false, null);
browser.document.ExecCommand("Italics", false, null);
browser.document.ExecCommand("StrikeThrough", false, null);
browser.document.ExecCommand("FontName", false, "Times New Roman");
browser.document.ExecCommand("FontName", false, "Arial");
browser.document.ExecCommand("FontName", false, "etc.");
browser.document.ExecCommand("FontSize", false, "1");
browser.document.ExecCommand("FontSize", false, "2");
browser.document.ExecCommand("FontSize", false, "3");
browser.document.ExecCommand("InsertUnorderedList", false, null);
browser.document.ExecCommand("InsertOrderedList", false, null);
browser.document.ExecCommand("Cut", false, null);
browser.document.ExecCommand("Copy", false, null);
browser.document.ExecCommand("Paste", false, null);
browser.document.ExecCommand("CreateLink", true, null);
The WebBrowser control does not allow editing, and is designed to view web pages only. Its actually the Internet Explorer/Trident rendering engine operating behind the scenes that parses the HTML and renders the final page complete with DOM/JS support. No popular browser supports editing of HTML pages, IMO, and neither does IE.

Categories