streamwriter how to - streamwriter

I have been researching how I can use StreamWriter to create a new html file and save it server side. I am fairly knowledgeable with javascript, and lesser with PHP. I have read over the example posted here :
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/5a13f536-b3ac-4f9f-ac8f-70ee1909d04d
if (!File.Exists("Test.htm"))
{
StreamWriter stream = new StreamWriter("Test.htm", true, System.Text.Encoding.UTF8);
stream.Write(#"<html>" + stream.NewLine+#"<body>" +stream.NewLine);
stream.Write(#"<table width='100%' cellpadding='10' style='margin-top:10px'
cellspacing='3' border='1' rules='all'>
<tr>
<td>
<h3>
<span style='font-family:Verdana'> My Test Is here</span></h3>
</td>
</tr>
</table>" + stream.NewLine +"</body>" + stream.NewLine +"</html>");
stream.Flush();
stream.Close();
}
.
Can anyone tell me where this code goes? Is this an external script? Is there anything that needs to be installed server side for StreamWriter to work?

The code is in C#.
You can create an ASP.NET HTTP handler and create the file on the server side. The request from the browser might invoke this request to write a file to the disk.
But I think if you are looking for writing html output on the Output stream, you can also do so using StreamWriter which is more relevant to get response back from the server.

Related

Sending a mail or invite through asp

I'm trying to send email or invite dynamically using asp page.
I used,
Oapp = new Outlook.Application();
But the problem is when executed, the page tries to open a new outlook application and sends a mail. I want the page to use the existing or open outlook application and send a mail.
Can anyone help me???
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
As a workaround you may consider using EWS or Outlook API, see EWS Managed API, EWS, and web services in Exchange for more information.
For sending emails use System.Net.* classes for sending emails from the server-side.
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString() );
}
// Display the values in the ContentDisposition for the attachment.
ContentDisposition cd = data.ContentDisposition;
Console.WriteLine("Content disposition");
Console.WriteLine(cd.ToString());
Console.WriteLine("File {0}", cd.FileName);
Console.WriteLine("Size {0}", cd.Size);
Console.WriteLine("Creation {0}", cd.CreationDate);
Console.WriteLine("Modification {0}", cd.ModificationDate);
Console.WriteLine("Read {0}", cd.ReadDate);
Console.WriteLine("Inline {0}", cd.Inline);
Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
foreach (DictionaryEntry d in cd.Parameters)
{
Console.WriteLine("{0} = {1}", d.Key, d.Value);
}
data.Dispose();
}

SpringMVC download file,the response result has data but explorer can't download file

As the title says.
I set the values in java like this:
response.setHeader("Content-Disposition", "attachment; filename=" + targetName);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
I debugged in chrome explorer, and the response body is:
Question solved by changing the submit method in JS file.
At first I send request by this:
Ext.Ajax.request({
utl:'',
params:{},
method:'POST'
});
Butajax can't download a file but can receive json/html/js/string format body.
So in extjs, if you want to download file, DO NOT USE ajax request.
And maybe you'll need use native javascript to do it.
For example:
var form = document.createElement("form);
form.method='POST';
form.action='/';
//deal with data
document.body.appendChild(form);
form.submit();

Get HTTP Response from a url by using C#

Environment: ASP.Net MVC 4 using C#
I need to get image by using GET request to a URL /inbound/faxes/{id}/image
I used the code below
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("/inbound/faxes/238991717/image");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader stream = new StreamReader(response.GetResponseStream());
but it flags "URL not valid"
I used the complete URL www.interfax.net/inbound/faxes/{id}/image
but the result is same
I want to follow this article to receive faxes
Accepting incoming fax notifications by callback
Can anyone help me to get fax...?
Try like this:
using (var client = new WebClient())
{
byte[] imageData = client.DownloadData("http://www.interfax.net/inbound/faxes/{id}/image");
}
Notice how the url is prefixed with the protocol (HTTP in this case). Also make sure you have replaced the {id} part of the url with the actual id of the image you are trying to retrieve.

session, httphandler, java applet work together

i have a aspx page see:
<%# Page Language="C#" %>
<%
HttpContext.Current.Session["UserID"] = "ABC1";
Response.Write(HttpContext.Current.Session["UserID"].ToString());
%>
<script>
var parameters = { OpenURL: "test.pdf", java_arguments: "-Xmx256m" };
var attributes = {archive:"webviewerS.jar,jPDFViewerS.jar", code:"qoppa.webViewer.PDFWebViewer", width:"100%", Height:"95%"};
var version = "1.6.0";
deployJava.runApplet(attributes, parameters, version);
</script>
The page load and created a session variable, and i also added a custom httphandler to handle the http request of pdf, every user type the path with .pdf will run the class
response.Cookies["UserID"].HttpOnly = false;
if (HttpContext.Current.Session["UserID"] != null)
{
response.ContentType = "application/pdf";
response.WriteFile(request.PhysicalPath);
}
else
{
response.Write("access denied");
}
The main objective of this script to test is it possible to view the pdf only by using the java applet within that aspx page. But finally,
var parameters = { OpenURL: "test.pdf", java_arguments: "-Xmx256m" };
the java applet request to load the pdf, but it seems the session could not be detected at httphandler, but the above code is successful if i directly type the .pdf path after i loaded the .aspx page.
If the applet request the pdf file, the result of the seesion["UserID"] will be null, why it can't detect the session value?
Have you tried using something like Fiddler or Charles to see the applet request going back from the browser to the server?
There will normally be a cookie called ASP.NET_SessionId or possibly a querystring parameter called sessionId to maintain the session depending on the server configuration.
From ASP.NET Session State Overview
By default, SessionID values are stored in a cookie. However, you can
also configure the application to store SessionID values in the URL
for a "cookieless" session.
The Java applet probably doesn't include this in the request and so the server thinks it's a different session.

how to open a file by its full path?

I have a GridView which has following template field that holds the filename, when the user clicks the filename, I call window.open() to open the file. My question is I can only pass relative path to window.open(). I got an error if I use full path. Is there any way I can use full path to open a file? Thanks.
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkFile" runat="server"
Text='<%# Eval("FileName")%>' OnClick="lnkFile_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Added: The actual location of the file is defined in web.config.
I have wrote following lnkFile_Click(). The old part will open a new window for the file, but I cannot pass fullpath of the file. The new part will let you have a choice to open or save the file. My question is, will this cause security issue?
protected void lnkFile_Click(object sender, System.EventArgs e)
{
string fileName = ConfigurationSettings.AppSettings["SPRAttachmentLocation"] + "\\SPR" + sprID + "\\" + ((LinkButton)sender).Text;
if (!File.Exists(fileName))
{
Exception ex = new Exception("Could not find the file, please contact your administrator.");
Response.Write("<p align=\"center\"><br /><br /><br /><br />There has been an Error: <strong>" + ex.Message + "</strong></p>\n");
return;
}
New:
byte[] bts = System.IO.File.ReadAllBytes(fileName);
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "");
Response.AddHeader("Content-Length", bts.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bts);
Response.Flush();
Response.End();
Old:
string newWindowUrl = "/SPR_Upload/SPR" + sprID + "/" + ((LinkButton)sender).Text;
string javaScript =
"<script type='text/javascript'>\n" +
"<!--\n" +
"window.open('" + newWindowUrl + "');\n" +
"// -->\n" +
"</script>\n";
Page.ClientScript.RegisterStartupScript(GetType(), "", javaScript);
}
Your question gives the impression that you think that you can open a file from the user's local computer. If that's the case, this is not possible.
Window.open expects a URL because the file is located on the server side, not the client side.
With that said, if you are trying to open a file located on the server side and you know the full path to the file; what you need to do is generate the virtual path within your application where the file can be found. You do this by creating a Virtual Directory in your APP from the IIS Admin Manager (Control Panel-->Admin Tools -->IIS Mgmt) and mapping this directory to the actual physical directory.
EDIT:
Say for example your whole website is physically located on the server on c:\inetpub\wwwroot\your_app. Let's assume your app can be accessed via http://example.com and the files you want to serve are physically located on d:\files. Assume further that you created a virtual directory for your app (as I explained above) and that you called this virtual folder public_files. If one knows the file name it should be possible to access the file by simply going to http://example.com/public_files/filename.ext. Since you in your app already know the file name, all you need to pass as parameter to window.open is this url (http://example.com/public_files/filename.txt)
You could try using the AppDomainAppVirtualPath to get the virtual path to the file.
string vPath = HttpRuntime.AppDomainAppVirtualPath + "/my/relative/path"
if the file is not located within the virtual directory there are a number of security issues you need to consider and address. in general it's not a good idea to access a file outside of the virtual directory.
if you must, then you will need to raise security permissions and grant access to the file on the network.

Resources