When code is placed onClick event it does not show open save dialog box and no exception is thrown but works fine onLoad event,opens a open save dialog box to save a word file..
string strDocBody;
strDocBody = "<html " + "xmlns:o='urn:schemas-microsoft-com:office:office' " + "xmlns:w='urn:schemas-microsoft-com:office:word'" + "xmlns='http://www.w3.org/TR/REC-html40'>" + "<head>" + "<title>Version and Release Management</title>";
strDocBody = strDocBody + "<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:Zoom>100</w:Zoom>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->";
strDocBody = strDocBody + "<style> #page" + "{size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt;" + " margin:0.75in 0.50in 0.75in 0.50in ; " + " mso-header-margin:.5in; " + " mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + " {page:Section1;}" + "p.MsoFooter, li.MsoFooter, div.MsoFooter{margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" + "p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" + "-->" + "</style>" + "</head>";
strDocBody = strDocBody + "<body lang=EN-US style='tab-interval:.5in'>" + "<div class=Section1>" + "<h1>This is my Heading</h1>" + "<h2>This is my Sub Heading</h2>" + "<p style='color:navy;'> This is blue text</p>" + "<p style='font-weight:bold; color:green;'><u> This is green bold underlined text </u></p>" + "<p style='color:red'><I>" + DateTime.Now + "</I></p>" + "<!--[if supportFields]>" + "<div style='mso-element:header' id=h1><p class=MsoHeader><span style='mso-tab-count:4'></span><span style='mso-field-code: PAGE '></span> </p></div>" + "<div style='mso-element:footer' id=f1> " + "<p class=MsoFooter style='border:none;mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'><o:p> </o:p></p> " + "Page <span style='mso-field-code: PAGE '><span style='mso-no-proof:yes'>1</span></span> of <span style='mso-field-code: NUMPAGES '></span>" + " <span style='mso-tab-count: 12'> <span style='mso-field-code: DATE '></span> " + " </p></div><![endif]-->" + "</div> </body> </html> ";
//Force this content to be downloaded as a Word document
Response.AddHeader("Content-Type", "application/msword");
Response.AddHeader("Content-disposition", "attachment; filename=TEST.doc");
Response.Charset = "";
Response.Write(strDocBody);
I suppose you are trying to feed the data in strDocBody as a Word file to the user. In order to do that, this data has to be the only thing that web server passes to the browser. That's why it works fine when you put it in your OnLoad event handler. It's not the case when you put it in button click handler.
If you want this behavior on button click, this button has to redirect user to another URL which will send the document data and nothing else.
Create a page specifically for serving document, let it be Document.aspx.
Now, I don't know if you need to perform any additional logic on button click. If not, you can just use LinkButton:
<asp:LinkButton runat="server" ID="docLink" Text="Document"
PostBackUrl="Document.aspx" />
Otherwise, just add redirect call in your onClick handler:
protected void btnButton1_Click(object sender, EventArgs e)
{
// ....
Response.Redirect("Document.aspx");
}
based on my experience, this indeed doesn't work for onClick since the headers has already been sent.
This could be because headers were already posted to the client browser. Try clearing with Response.Clear(), make sure you're not within an Ajax call. Another trick is to open a new page, using a client-side anchor with argument compiled dynamically.
EDIT: of course if you clear your Response, page will be blank after asking the user to download the file. Always keep in mind the stateless synchronous behavior of client-server http communication.
Related
I'm trying to generate an email with some basic formatting based on labels in a FormView. I'm going the route of Process.Start("mailto:... instead of System.Net.Mail so the email opens up in the default email client to give the user a chance to edit To: CC: etc without making a new form just to handle that. I've got the following code-behind to handle an "Email Form" button for emailing the URL of the webform.
protected void fvBF_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Email")
{
Label lblBFID = (Label)fvBookingForm.FindControl("lblBFID");
Label lblProjectID = (Label)fvBookingForm.FindControl("lblProjectNum");
Label lblProjectName = (Label)fvBookingForm.FindControl("lblProjectName");
Label lblReleaseName = (Label)fvBookingForm.FindControl("lblReleaseName");
Label lblPMName = (Label)fvBookingForm.FindControl("lblPM");
String strReleaseName = String.IsNullOrEmpty(lblReleaseName.Text) ? "[Description]" : lblReleaseName.Text;
String pmFirst = lblPMName.Text.ToString().Split()[0];
String pmLast = lblPMName.Text.ToString().Split()[1];
String strSubject = "BF " + lblBFID.Text + " - " + lblProjectName.Text + " - Release " + strReleaseName;
String strBody = "A Booking Form for Project #"+ lblProjectID.Text + " - " + lblProjectName.Text +
" - Release " + strReleaseName + " has been created or modified. \n\n" + Request.Url.ToString();
Process.Start("mailto:" + pmFirst + "." + pmLast + "#company.com?subject=" +
HttpUtility.HtmlAttributeEncode(strSubject) + "&body=" +
HttpUtility.HtmlAttributeEncode(strBody).Replace("\n", Environment.NewLine));
}
}
However, when the email is generated, there are no line breaks in the body between the "A Booking Form...." sentence and the URL. I've tried putting Environment.NewLine directly in the string.
...created or modified. " + Environment.Newline + Environment.NewLine + Request.Url.ToString();
Which basically gives me the same results. I've tried replacing the \n with <br /> which doesn't add the line break and for some reason, doesn't display the URL either. I can only guess that the problem has to do with the HtmlAttributeEncode() and getting it to parse the NewLine properly. Is there something I'm missing here?
You might want to try .Replace("\r\n", "<br />") on the body after you have done your encoding of the body.
You should probably use StringBuilder here instead of String.
You can then do the following:
StringBuilder builder = new StringBuilder();
builder.AppendLine(string.Format("A Booking Form for Project #{0} - {1}",lblProjectID.Text, lblProjectName.Text));
builder.AppendLine(string.Format(" - Release {0} has been created or modified.", strReleaseName));
builder.AppendLine();
builder.AppendLine(Request.Url.ToString());
String strBody = builder.ToString();
You can also include (char)10 and (char)13 in your string creation. e.g.:
string.Format("First Line{0}{1}Second Line", (char)10, (char)13);
Model.Message = "my message \n second message";
then add this style to string tag style="white-space: pre-line;"
example <h3 style="white-space: pre-line;">#Model.Message</h3>
I'm trying to create a secondary tile, which shows pictures in rotation like in the photos app. I have tried something like this:
SecondaryTile tile = GenerateSecondaryTile("NewTile", "SecondaryTile");
await tile.RequestCreateAsync();
var ImageUrl = selectedFileList.ElementAt(0).Path;
string tileXmlString =
"<tile>"
+ "<visual>"
+ "<binding template='TileSmall'>"
+ "<image src='" + selectedFileList.ElementAt(0).Path + "' alt='image'/>"
+ "<image src='" + selectedFileList.ElementAt(1).Path + "' alt='image'/>"
+ "<image src='" + selectedFileList.ElementAt(2).Path + "' alt='image'/>"
+ "<image src='" + selectedFileList.ElementAt(3).Path + "' alt='image'/>"
+ "<image src='" + selectedFileList.ElementAt(4).Path + "' alt='image'/>"
+ "</binding>"
+ "</visual>"
+ "</tile>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(tileXmlString);
TileNotification notifyTile = new TileNotification(xmlDoc);
TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(notifyTile);
I have tried setting the type as both background and peek but it doesn't give the required result. And also I would not like to use a background task as my app already uses one and I wouldn't want to increase the overhead which might cause the task to fail entirely. I wouldn't mind if the images were limited to 5 like earlier in Windows phone 8.1.
For reference : check this out : Skip to 0:30
This is for Primary Tile, but it should work the same way. Make your own XML Template, then reference your image. Enable notification queue then update the Tile with the TileNotification. Do this up to five times to put five images on the Live Tile stack.
var myStorageFile = await Package.Current.InstalledLocation.GetFileAsync("LiveTileTemplate.xml");
string liveTileTemplate = await FileIO.ReadTextAsync(myStorageFile);
liveTileTemplate = liveTileTemplate.Replace("squareImageSource", FilePathFullPrefix + GetFilePathSquareTile(imageID));
TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
TileUpdateManager.CreateTileUpdaterForApplication().Update(new TileNotification(mergedXML));
I'm currently working on a small program that gets data from mongoDB and matches it with other data. My program is currently printing out the data, but it needs to add a <asp:button />with an unique ID to it so I can save the data for each product.
Here is my code:
public void showCoolers_Click(object sender, EventArgs e)
{
var items = "";
var connectionString = "mongodb://localhost:27017/";
var mongoClient = new MongoClient(connectionString);
MongoServer server = mongoClient.GetServer();
MongoDatabase database = server.GetDatabase("mydb");
MongoCollection<cpuCoolers> collection = database.GetCollection<cpuCoolers>("cpucoolers");
foreach (cpuCoolers parts in collection.FindAll())
{
String _id = parts._id.ToString();
items = items + "<tr><td>" + parts.Aanbieder + "</td><td> " + parts.Productnaam + "</td><td>" + parts.Socket + "</td><td> " + parts.Geluidsterkte + "</td><td> " + parts.Prijs +"</td><td><asp:Button ID='x' runat='server' Text='Motherboard' CssClass='btn btn-block btn-primary'/></td></tr>";
}
lblProducts.Text = "<table><thead><tr><th>Provider</th><th>Productname</th><th>Socket</th><th>Sound production</th><th>Price</th><th>Add to MyPc!</th></thead>" + items + "</table>";
}
I print my data via changing the content oflblProduct.Text in my aspx file. If I add a asp:button to this it doesn't show up, however a regular Html button does, why is that and is there a way to print out a asp:button's?
You can't render an asp.net button the way you are trying, you would need to use a regular html button as you found out.
The asp:button is something that asp.net interprets while it is building your page; by the time you _Click function is executed, its too late in the page lifecycle to render asp.net controls - so HTML buttons are your only option at that point in the page execution.
Here is an overview of the asp.net page life cycle that might help you understand it better:
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx
Since yesterday, I try to run a sample of code to display a chart with FusionCharts and Mvc3 Razor and nothing works. Please.... help!!! :)
Here is what I have done:
I took the projet from Libero. here
After that, I used the project convertor here to upgrade the project from Mvc2 to Mvc3.
When I try to run to code (F5 and show the result in browser), that works fine; all graphics are displayed correctly.
If I just create a new view with razor (.cshtml) instead of the current .aspx (replacing a view from the old syntax to the new razor) and I try to displayed the same graphic, the page is displayed correctly but without graphic. When I look into the page source with firebug or any other tools, no code is behind the scene. I also don't have any errors while looking with the Web Developer tool in Firefox.
I just tried to add a Html.Raw in front of the code that generate the javascript to not encode the output and I have the same result. Also trying with returning HtmlString but again same result; no graphic is displayed.
The key to don't miss in this problem is that if I try the exact same code but with an .aspx file, all is correct.
In .aspx, the code looks like this:
<%=Html.FChart("Chart01", ViewData["MyChart"], 600, 400)%>
And in .cshtml:
#{Html.FChart("Chart01", ViewData["MyChart"], 600, 400); }
And finally, the html helper to generate this bunch of code:
private static string RenderChart(string controlId, string xmlData, FusionChartBase chart, int width, int height)
{
String sControlId = controlId;
String sJsVarId = "_lib_JS_" + controlId;
String sDivId = "_lib_DIV_" + controlId;
String sObjId = "_lib_OBJ_" + controlId;
String sWidth = width.ToString();
String sHeight = height.ToString();
StringBuilder oBuilder = new StringBuilder();
oBuilder.AppendLine(#"<div id=""" + sDivId + #""" align=""center""></div>");
oBuilder.AppendLine(#"<script type=""text/javascript"">");
oBuilder.AppendLine(#"var " + sControlId + #" = (function() {");
oBuilder.AppendLine(#" return {");
oBuilder.AppendLine(#" containerId: '" + sDivId + "',");
oBuilder.AppendLine(#" xmlData: '',");
oBuilder.AppendLine(#" chartType: '',");
oBuilder.AppendLine(#" showChart: function() {");
oBuilder.AppendLine();
oBuilder.AppendFormat(#" var chartURL = '{0}' + this.chartType.replace('Chart', '{1}');", UrlSWF, SufixSWF);
oBuilder.AppendLine(#" var " + sJsVarId + #" = new FusionCharts(chartURL, """ + sObjId + #""", """ + sWidth + #""", """ + sHeight + #""");");
oBuilder.AppendLine(#" " + sJsVarId + #".setDataXML(this.xmlData);");
oBuilder.AppendLine(#" " + sJsVarId + #".render(""" + sDivId + #""");");
oBuilder.AppendLine(#" }");
oBuilder.AppendLine(#" }");
oBuilder.AppendLine(#"})();");
oBuilder.AppendLine(#"setTimeout(function(){");
oBuilder.AppendLine(#" " + sControlId + #".xmlData = """ + xmlData.Replace(#"""", #"'") + #""";");
oBuilder.AppendLine(#" " + sControlId + #".chartType = """ + chart.ChartType + #""";");
oBuilder.AppendLine(#" " + sControlId + #".showChart();");
oBuilder.AppendLine(#"},0);");
oBuilder.AppendLine(#"</script>");
return oBuilder.ToString();
}
I don't know if I must set some configuration options in the web.config or what I don't understand in the behavior of Mvc2 compare to Mvc3, but it's very frustrating.
If you have any idea, a big thanx in advance.
It should be #Html.FChart("Chart01", ViewData["MyChart"], 600, 400) instead of #{Html.FChart("Chart01", ViewData["MyChart"], 600, 400); }
FusionCharts provides a .NET library which makes rendering charts a one liner - read through the FusionCharts Documentation.
They have a recent tutorial up on their blog - JavaScript Charts with ASP.NET (C#) Using FusionCharts XT
I'm trying to format a literal control on a code-behind page:
BillerLiteral.Text = "<p class="'no-margin'"/>" + attendee1.FirstName + " " +
attendee1.LastName + "</p> <p class=""no-margin"">" + attendee1.Address1 + "," +
attendee1.Address2 + "</p><p class=""margin"">" + attendee1.City + "," +
attendee1.State + " " + attendee1.ZipCode + "</p><p>" + attendee1.Email + "</p>";
Right after I added that line, I get compilation errors even though it compiles fine.
Compilation Error Description: An error occurred during the compilation of a
resource required to service this request. Please review the following specific
error details and modify your source code appropriately.
Compiler Error Message: The compiler failed with error code 1.
Here's the detailed compiler output:
c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE> "c:\Window
\Microsoft.NET\Framework\v3.5\csc.exe" /t:library /utf8output /R:"C:\Windows
\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089
\System.ServiceModel.dll"
/R:"C:\Windows\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a
\System.Web.Services.dll" /R:"C:\Windows\assembly\GAC_32\System.Data
\2.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Windows\assembly\GAC_MSIL
\System.Runtime.Serialization\3.0.0.0__b77a5c561934e089
\System.Runtime.Serialization.dll" /R:"C:\Windows\assembly\GAC_MSIL\System
\2.0.0.0__b77a5c561934e089\System.dll" /R:"C:\Windows\assembly\GAC_MSIL
\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:
"C:\Windows\assembly\GAC_MSIL\System.WorkflowServices\3.5.0.0__31bf3856ad364e35
\System.WorkflowServices.dll" /R:"C:\Windows\assembly\GAC_32\
System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\
System.EnterpriseServices.dll"
/R:"C:\Windows\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a
\System.Configuration.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.IdentityModel
\3.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\Windows\assembly
\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\System.Core.dll" /R:
"C:\Windows\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a
\System.Web.Mobile.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.Xml
\2.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"
C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll"
/R:"C:\Windows\assembly\GAC_MSIL\System.ServiceModel.Web
\3.5.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll"
/R:"C:\Windows\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35
\System.Web.Extensions.dll" /R:"C:\Windows\assembly\GAC_MSIL
\System.Data.DataSetExtensions\3.5.0.0__b77a5c561934e089
\System.Data.DataSetExtensions.dll" /R:"C:\Users\jeffreyeas\AppData\Local
\Temp\Temporary ASP.NET Files\awchallenge\ae85f60c\8aef9183\App_Code.fkizkk6y.dll"
/R:"C:\Windows\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089
\System.Xml.Linq.dll" /R:"C:\Windows\assembly\GAC_32\System.Web
\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /out:"C:\Users\jeffreyeas\AppData\Local
\Temp\Temporary ASP.NET Files\awchallenge\ae85f60c\8aef9183
\App_Web_page_two.aspx.cdcab7d2.dkslispb.dll" /D:DEBUG /debug+ /optimize-
/win32res:"C:\Users\jeffreyeas\AppData\Local\Temp\Temporary ASP.NET Files\awchallenge
\ae85f60c\8aef9183\vuyv4kby.res" /w:4 /nowarn:1659;1699;1701 /warnaserror-
"C:\Users\jeffreyeas\AppData\Local\Temp\Temporary ASP.NET Files\awchallenge\ae85f60c
\8aef9183\App_Web_page_two.aspx.cdcab7d2.dkslispb.0.cs" "C:\Users\jeffreyeas\AppData
\Local\Temp\Temporary ASP.NET Files\awchallenge\ae85f60c\8aef9183
\App_Web_page_two.aspx.cdcab7d2.dkslispb.1.cs" "C:\Users\jeffreyeas\AppData\Local
\Temp\Temporary ASP.NET Files\awchallenge\ae85f60c\8aef9183
\App_Web_page_two.aspx.cdcab7d2.dkslispb.2.cs"
What am I missing?
Your quotes are wrong in "<p class="'no-margin'"/>"
BillerLiteral.Text = "<p class=\"no-margin\"/>" + attendee1.FirstName + " " + attendee1.LastName + "</p> <p class=\"no-margin\">" + attendee1.Address1 + "," + attendee1.Address2 + "</p><p class=\"margin\">" + attendee1.City + "," + attendee1.State + " " + attendee1.ZipCode + "</p><p>" + attendee1.Email + "</p>";
try this