Uploaded file have no content when uploaded from Remote IIS Server - c#

I am trying to upload files to Google Drive using ASP.NET Core 3.0, here is my code to upload the file.
GData.File fileMetadata = new GData.File()
{
Id = null,
Name = Path.GetFileName(path),
MimeType = contentType
};
using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
FilesResource.CreateMediaUpload request = service.Files.Create(fileMetadata, stream, contentType);
request.Fields = "id";
request.Body = fileMetadata;
request.ProgressChanged += (uploadProgress) =>
{
Debug.WriteLine($"{uploadProgress.Status} {uploadProgress.BytesSent}");
};
request.ResponseReceived += (obj) =>
{
Debug.WriteLine($"File uploaded successfully {obj.Id}");
};
request.Upload();
}
Problem i am facing is, this method work fine when i run it on local IIS Server. On Remote IIS Server this method run successfully but uploaded file do not have any content in it and show 0 size
follow this link to test:
https://oauthdemo.coredata.ca/

I tested the link you provided, but the test results show that the Content-Length has a size.

After struggling of whole day finally i have sort this issue.
It was due to the temp folder. i was using FileStream to create new file in temp folder. It was a A-Sync call due to which FileStream failed to create that file.

Related

How do I download a PDF file using a URL link to local computer in c#

I'm trying to download a pdf file using a URL link to my computer, but it gives the following error:
'Unable to connect to the remote server' SocketException: A connection
attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because
connected host has failed to respond 41.180.70.243:80
I made sure that I can open the PDF in my browser when I use the link, and it works.
(I get the link from an XML response from another server).
I am using service references to integrate to another system using SOAP.
The result that I get back from the service is a XML file:
TPN_Test_ConsumerService.ConsumerSoapClient consumerServiceClient = new TPN_Test_ConsumerService.ConsumerSoapClient();
var result = consumerServiceClient.ConsumerEnquiry(securityInfo, moduleList, consumerBlock, enquiryBlock);
var PdfURL = "";
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(result));
XmlNodeList elemList = doc.GetElementsByTagName("PdfURL");
for (int i = 0; i < elemList.Count; i++)
{
PdfURL = elemList[i].InnerXml;
}
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
byte[] pdfBytes = client.DownloadData(PdfURL);
System.IO.File.WriteAllBytes("Path of file", pdfBytes);
I've tried setting the default proxy to false in the web.config file, but that also did not work.
You can download the PDF file and save it in Isolated Storage, to be able to view later offline.
So lets see how to do it step-by-step.
1- Download PDF file from a link( URL ) provided by server side:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("http://url-to-your-pdf-file.pdf"));
2- Save the downloaded PDF file in local storage:
async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length];
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storageFile.OpenFile("your-file.pdf", FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
}

C# System.UnauthorizedAccessException when using stream

I am trying to upload some files to Google Drive via my C# programme. I am using stream to work with Google Drive API function to upload a file. But I have the exception called System.UnauthorizedAccessException. But when I use File.ReadAllText function I have not got the exception. Here's my code and exception is on line 7. Thank you for your answers.
public void uploadFile(string path, DriveService service)
{
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = Path.GetFileName(path);
fileMetadata.MimeType = "txt";
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
request = service.Files.Create(fileMetadata, stream, "txt");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
}
EDIT 1:
There is link to GitHub to full source code from my project: https://github.com/Nextesro/IDK-client
Use File.OpenRead to open the file for read-only access.
using (var stream = File.OpenRead(path))
{
// ...
}

Ftp not saving files on server

I am having a strange issue with my ftp class its not sending the file to the server my main code is creating the file ok locally however its not saving it on the server no error is created just completes as if it has transfered it I checked permissions of the user and it is fine.
public void Send(string file)
{
try
{
// read the contents of the file.
byte[] contents = ReadFileContents(file);
var requestUriString = string.Concat(_remoteHost, "/", Path.GetFileName(file));
var request = (FtpWebRequest)WebRequest.Create(requestUriString);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePassword);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(contents, 0, contents.Length);
requestStream.Close();
}
}catch(Exception ex)
{
Helper.Log(ex.Message);
}
}
And I checked the request uri is fine. After futher checking .net is reporitng
I have asked the web company to check there server cause it should be there for them even though I cannot see it in filezilla some reason?
This is how my uri looks like
ftp://ftp.mydomain.biz/2018-05-09-14-11.csv
Edit2
The file should go to the root.

AWS C# lambda File upload to S3

I have created a Serverless for AWS using visual studio empty template. I am trying to send a file to it which internally gets uploaded to S3 using C#. I am able to upload the file through a console application. I need help on:
a. how to send file to API through Insomnia or Postman -- able to do it now
b. How the receive the file so that when I upload it S3 I am able to download it directly the way I sent in the API.-- able to do it now
[EDIT]
c. When trying to save the file to bucket the file size is less than the uploaded and is corrupted.
Code Snippet:
public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
{
context.Logger.LogLine(Encoding.ASCII.GetByteCount(request.Body).ToString());
MemoryStream ms = new MemoryStream();
TransferUtility utility = new TransferUtility(new AmazonS3Client("<AccessKey>", "<SecretKey>", Amazon.RegionEndpoint.USEast1));
var checker = new TransferUtilityUploadRequest()
{
InputStream = new MemoryStream(Encoding.ASCII.GetBytes(request.Body)),
BucketName = "<BucketName>",
Key = "<FileName>.pdf"
};
utility.Upload(checker);
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(checker),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" } }
};
return response;
}
Note: The file could be docx or pdf. Also I have the code to upload file stream to S3 Just need info on receiving the file through APIGatewayProxyRequest type and converting to stream.
Thanks in advance.

Error uploading attachment : The item was not found or does not exist

I m using RackSpace to upload email attachments. This is how I m trying to upload it to RackSpace Cloud:
//Skipped Authentication Setup
string containerName = ConfigurationManager.AppSettings["ContainerName"];
using (var stream = new MemoryStream())
{
StreamWriter memoryWriter = new StreamWriter(stream);
memoryWriter.Write(file);
stream.Position = 0;
stream.Seek(0, 0);
cloudFilesProvider.CreateObject(containerName, stream, fileName);
}
var header = cloudFilesProvider.GetContainerCDNHeader(containerName, "ORD");
string Url = header.CDNSslUri + "/" + fileName;
This code uploads file of size 0 into Cloud and on reaching to header variable, it throws error:
The item was not found or does not exist
Any help would be appreciated.
Can you verify that your container is CDN enabled? If it is not, when you HEAD the CDN management URL for the the container, it will return a HTTP 404. I suspect this is what is happening.
I am not sure what libraries you are using, but you can find info on how to CDN enable a container here:
https://developer.rackspace.com/docs/cloud-files/v1/developer-guide/#cdn-enabling-the-container-and-setting-a-ttl

Categories

Resources