iis7 website accessed externally downloads files to server instead of local machine - iis-7

I've a site set up in IIS. It's allows users to download files from a remote cloud to their own local desktop. HOWEVER, the context seems to be mixed up, because when I access the website externally via the IP, and execute the download, it saves the file to the server hosting the site, and not locally. What's going on??
My relevant lines code:
using (var sw2 = new FileStream(filePath,FileMode.Create))
{
try
{
var request = new RestRequest("drives/{chunk}");
RestResponse resp2 = client.Execute(request);
sw2.Write(resp2.RawBytes, 0, resp2.RawBytes.Length);
}
}

Your code is writing a file to the local filesystem of the server. If you want to send the file to the client, you need to do something like
Response.BinaryWrite(resp2.RawBytes);
The Response object is what you use to send data back to the client who made the request to your page.

I imagine that code snippet you posted is running in some sort of code-behind somewhere. That is running on the server - it's not going to be running on the client. You will need to write those bytes in the Response object and specify what content-type, etc. and allow the user to Save the file himself.

Related

Why won't OAuth work on web server?

I have an ASP.Net web application running on Windows Server 2012, and need to make calls to social networking sites using oauth to generate some of the page content. Everything works on my development machine, but I can't even get a single response back ("unable to connect to the remote server" error).
I disabled the firewall to test that. No luck. I created a console application to test it that way. A simple HttpWebRequest will get the html for any page I throw at it, but not any oauth request. I've used different libraries to try to achieve this, including Linq2Twitter, Spring.Social, and HigLabo. All work locally, but not on the server. I've found nothing useful in the server event log.
Can anyone give me some clues what might be happening?
EDIT: Here's some code I'm using with the HigLabo library to try to retrieve the user timeline.
using HigLabo.Net.Twitter;
var cl = new TwitterClient(consumerKey, consumerSecret, accessToken, accessTokenSecret);
var rr = cl.GetHomeTimeline();
foreach (var r in rr)
{
//Console.WriteLine(r.CreatedAt + ":" + r.Text);
}
I'm aware that accessToken & accessTokenSecret aren't/shouldn't be necessary for a simple timeline read, but this is just to make sure it works first.
This turned out to be a firewall issue, as had been suspected. But not the server firewall. This was a problem with the ISP. They had an internal firewall that was blocking all traffic to/from the social network sites. They were able to resolve it quickly with a phonecall, but it was not a coding or configuration error on my part.

Authentication Issue when accesing Reporting Service

Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
When the user clicks on the button to download the .pdf which the Reporting automatically generates (the end-user never sees the html version of the Report), it asks for windows credentials.
If the user enters a valid credential (and this credential must be a valid credential on the server which the Reporting Service is deployed), the .pdf is obviously downloaded.
But this can't happen. The end-user must download the .pdf directly, without asking for credentials. Afterall, he doesn't even have the credentials.
Response.Redirect("http://MyServer/ReportServer/Pages/ReportViewer.aspx?%2fReportLuiza%2fReportContract&rs:Format=PDF&NMB_CONTRACT=" + txtNmbContractReport.Text);
The code snippet above, shows the first version of my code when the user clicks the button. This one propmts for the Windows credentials.
I already tried to change on IIS the Authentication of the virtual directory ReportServer, but the only one which works is the Windows Credentials. The other ones doesn't even let me open the virtual directory of the Report or the Report Manager's virtual directory.
When I tried to change it to Anonymous Authentication he couldn't access the DataBase. Then I choose the option to Credentials stored securely on the report server. Still doesn't work.
The physical directory of my ReportServer virtual directory points to the reporting server folder on the Hard Disk (C:\Program Files\Microsoft SQL Server\MSSQL.5\Reporting Services\ReportServer). I moved the same folder to my wwwroot directory.
Didn't work. The virtual directory didn't even open. Then I read this could be a problem because I had the same name on two folders (one in C: and other in wwwroot). So I changed the name of the one in wwwroot. Same issue of the DataBase connection couldn't be done.
I returned the physical path to C:
Below, is the second version of my button's event code:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
When I'm debugging (on Visual Studio 2010), the code above works fine, doesn't asking for credentials (unfortunately, it doesn't prompt the option to open, save or cancel de file download. But this is another problem, no need to worry with it now) and save the file on C:.
When published, the code doesn't work. An erros says: The permission granted to user 'IIS APPPOOL\ASP.NET v4.0' are insuficient for performing this operation. So I added to the Reporting Service's users this user. When I tried again, the error is: Login failed for user IISAPPPOOL\ASP.NET v4.0. Cannot create a connection to data source 'MyDataSourceName'.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Summarizing: I need a solution where there is no credential prompt, and the user can choose where it wants to save the .pdf file.
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.
One solution would be to create a new App Pool with an account that has the rights to access your restricted resources and then assign your web application to it.

copy file from local to remote server

I'm dynamically creating html files on my local system (using HTMLTEXTWRITER, then save them using streamwriter to local file system). I want to copy this file to my remote server withour user interaction, so that my users can read file. I use C#
for instance I want to copy from d:\myfile.html to mysite.com\myfile.html, how can I do it?
I have used this and it worked. may be useful
for holding path of local
rPath = "\\" & Request.UserHostAddress & "\c$\temp\"
for output file
rOutput = Session.SessionID & "_" & Format(Date.Now(), "ddMMyyhhmmss") & ".pdf"
now: report will be created at localhost\c\temp
You can't use the System.IO classes for this (unless you have access to the remote server as a network drive), but you can programmatically POST the file from the client to the remote server over HTTP using System.Net.
Here's a snippet using the WebRequest class:
WebRequest request = WebRequest.Create( url );
request.Timeout = 1000; // some appropriate value
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0; // set a length here
using( StreamWriter requestStream = new StreamWriter( request.GetRequestStream(), System.Text.Encoding.UTF8) ) {
// write to the stream here using requestStream.Write();
requestStream.Close();
}
More info for HTTP: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Alternatively, you could use a protocol designed for transferring files like FTP (or something more secure) which isn't that hard to do in code.
FTP options: http://msdn.microsoft.com/en-us/library/ms229718
Is you remote server based on Windows and in the same workgroup or domain with you working machine ? If so, you can turn on the Windows File Sharing on the server. Then you can copy your file with cmd like this:
copy c:\test.txt \\mysite.com
The path "\\mysite.com" is also valid used by File.Copy in C#.
Otherwise, you need to set up a FTP environment on you server and use the FTP related API in C#.
You could set-up an FTP server and copy the files programmatically via FTP.
An example would be found here or here.
There are three ways by which you can copy the file to remote server.
Using normal file copy mode. Here you need to have access to the the webserver shared path. If the webserver is in same network as your application, then you can share the webroot and provide write access to the user who is running the application. He can then use File.Copy("source.txt", "\\Servername\SharedFolderName\target.txt").
The second approach is to use FTP to copy the file to the remote server. This MSDN example would help you on how to do this. This will work with most of the shared hosting providers.
You can use HTTP POST as noted by Tim. But this would let any user to perform the post. You may have to take care of user provisioning, authentication and authorization. IMO, keep this as last option as provisioning user and providing rights to certain path, may become cumbersome.

Error handling in ASHX code

I created an ASHX file and use it to handle async file uploads.
Since the site might not be hosted on our servers, I want to check for write permissions and delete permissions and supply the end user (site content editor in this case) with an error they can deal with.
I'm using uploadify for the upload, I'm not sure, but I`m guessing this complicates the return of a message that can be shown on the page, but maybe not.
I ended up using the c# code in ashx file to check for permissions on the directory and returned different status codes as JSON objects.
context.response.write("{success: 'false', message: '" + ex + "'}")
And in the client side JS I just access response.message if response.success = false.
Everything works well.
Thank you!
Before the user is able to attempt an upload, trying writing and reading a small file to the destination on the server (on the server side), if this fails then you can supply them with an appropriate message.

ASP.NET website problem while requesting XML data from remote server

I am writing code in asp.net to get XML data from external webserver.
*.cs Code
connection string: URL of external(third party) server for XML data
WebRequest req = WebRequest.Create(connectionString);
req.Proxy = WebProxy.GetDefaultProxy();
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
req.Timeout = 1000;
using (WebResponse resp = req.GetResponse())
{
// reading data from XML file
}
Key Point
1. GetDefaultProxy() return information about proxy
2. Default Credentials() return username password which i have written in web.config as shown below
Web.config
<identity impersonate="true"
username="Username of PC where website is running"
password="password"/>
Problem Statement:
After installing website setup : Above code working fine at WindowsXP but the same code doesn't work at Windows server 2003. I am not able to find out what extra we need to configure in Windows Server 2003.
Please help me to find out the solution?
[EDIT]
Very random beheviour is observed at server. Sometimes the data comes and appear at client(browser) when we logged into windows server 2003.
But when we loggedout from server and try to request for data from client(browser) at another PC. It appear for very short duration. After say wait of 1 hour the data doesn't comes for new request.
An error message might be useful??
But at a guess I'd say it's that the proxy isn't configured on the 2003 server.
Check the firewall on Windows Server 2003 and make sure port 80 outbound is allowed (assuming that is the port used by the web service).
This might help. It's about proxy and .NET app.

Resources