MultipartFormDataContent encode single quote in .NET Standard - httpclient

I have file which name contains single quote like Test'Quote.html
in order to upload file to server, I'm using HttpClient and MultipartFormDataContent like:
using (var formContent = new MultipartFormDataContent($"{new string('-', 10)}-{DateTime.Now.Ticks}"))
{
foreach (var file in files)
{
var fileContent = new StreamContent(file.Stream);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);
formContent.Add(fileContent, file.Name, file.Filename);
}
await client.PostAsync(address, formContent)
}
I check formContent and I see:
And I cannot upload file to server because it says that filename is invalid, seems that last filename is taken in consideration instead of first one.
How to disable or avoid encoding such name ?

Related

Protractor - Create a txt file as report with the "Expect..." result

I'm trying to create a report for my scenario, I want to execute some validations and add the retults in a string, then, write this string in a TXT file (for each validation I would like to add the result and execute again till the last item), something like this:
it ("Perform the loop to search for different strings", function()
{
browser.waitForAngularEnabled(false);
browser.get("http://WebSite.es");
//strings[] contains 57 strings inside the json file
for (var i = 0; i == jsonfile.strings.length ; ++i)
{
var valuetoInput = json.Strings[i];
var writeInFile;
browser.wait;
httpGet("http://website.es/search/offers/list/"+valuetoInput+"?page=1&pages=3&limit=20").then(function(result) {
writeInFile = writeInFile + "Validation for String: "+ json.Strings[i] + " Results is: " + expect(result.statusCode).toBe(200) + "\n";
});
if (i == jsonfile.strings.length)
{
console.log("Executions finished");
var fs = require('fs');
var outputFilename = "Output.txt";
fs.writeFile(outputFilename, "Validation of Get requests with each string:\n " + writeInFile, function(err) {
if(err)
{
console.log(err);
}
else {
console.log("File saved to " + outputFilename);
}
});
}
};
});
But when I check my file I only get the first row writen in the way I want and nothing else, could you please let me know what am I doing wrong?
*The validation works properly in the screen for each of string in my file used as data base
**I'm a newbie with protractor
Thank you a lot!!
writeFile documentation
Asynchronously writes data to a file, replacing the file if it already
exists
You are overwriting the file every time, which is why it only has 1 line.
The easiest way would probably (my opinion) be appendFile. It writes to a file without overwriting existing data and will also create the file if it doesnt exist in the first place.
You could also re-read that log file, store that data in a variable, and re-write to that file with the old AND new data included in it. You could also create a writeStream etc.
There are quite a few ways to go about it and plenty of other answers
on SO specifically on those functions that can provide more info.
Node.js Write a line into a .txt file
Node.js read and write file lines
Final note, if you are using Jasmine you can also create a custom jasmine reporter. They have methods that contain exactly what you want (status Pass/Fail, actual vs expected values etc) and it's fairly easy to set up with Protractor

OpenXml ChangeDocumentType

I need to convert a powerpoint template from potx to pptx. As seen here: http://www.codeproject.com/Tips/366463/Create-PowerPoint-presentation-using-PowerPoint-te I have tried with the following code. However the resulting pptx document is invalid and can't be opened by Office Powerpoint. If I skip the line newDoc.ChangeDocumentType then the resulting document is valid, but not converted to pptx.
templateContentBytes is a byte array containing the content of the potx document.
And temppath points to its local version.
using (var stream = new MemoryStream())
{
stream.Write(templateContentBytes, 0, templateContentBytes.Length);
using (var newdoc = PresentationDocument.Open(stream, true))
{
newdoc.ChangeDocumentType(PresentationDocumentType.Presentation);
PresentationPart presentationPart = newdoc.PresentationPart;
presentationPart.PresentationPropertiesPart.AddExternalRelationship(
"http://schemas.openxmlformats.org/officeDocument/2006/" + "relationships/attachedTemplate",
new Uri(tempPath, UriKind.Absolute));
presentationPart.Presentation.Save();
File.WriteAllBytes(tempPathResult, stream.ToArray());
I had the same problem, just move
File.WriteAllBytes(tempPathResult, stream.ToArray());
outside of the using

how to zip all files with asp.net 3.5

i 'm .net developer. i want to Zip all files and make a one zip file with this technique.
ZipFile multipleFilesAsZipFile = new ZipFile();
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".zip");
Response.ContentType = "application/zip";
for (int i = 0; i < filename.Length; i++)
{
string filePath = Server.MapPath("~/PostFiles/" + filename[i]);
multipleFilesAsZipFile.AddFile(filePath, string.Empty);
}
multipleFilesAsZipFile.Save(Response.OutputStream);
how ever for making this Zip i use third party library Ionic.
all files are ziped successfully but not extracted to client desktop. is there problem with my code. or this library that i'm using has been expired.
Is there free full version .net compatible library to zip all files.
Use SharpZipLib:
Nuget Package
Install-Package SharpZipLib
OR Download here
http://www.icsharpcode.net/OpenSource/SharpZipLib/
Snippet from examples:
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) {
string[] files = Directory.GetFiles(path);
foreach (string filename in files) {
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity
// Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
// A password on the ZipOutputStream is required if using AES.
// newEntry.AESKeySize = 256;
// To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
// you need to do one of the following: Specify UseZip64.Off, or set the Size.
// If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
// but the zip will be in Zip64 format which not all utilities can understand.
// zipStream.UseZip64 = UseZip64.Off;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
// the "using" will close the stream even if an exception occurs
byte[ ] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename)) {
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[ ] folders = Directory.GetDirectories(path);
foreach (string folder in folders) {
CompressFolder(folder, zipStream, folderOffset);
}
}
Taken from : https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
Works awesome!

Upload Servlet with custom file keys

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename

merge word documents to a single document

I used the code in the link mentioned below to merge word files into a single file
http://devpinoy.org/blogs/keithrull/archive/2007/06/09/updated-how-to-merge-multiple-microsoft-word-documents.aspx
However, seeing the output file i realized that it was unable to copy header image in the first document. How do we merge documents preserving format and content.
I will suggest to use GroupDocs.Merger Cloud for merging multiple word document to a single word document, it keeps the formatting and contents of the source documents. It is a platform independent REST API solution without depending on any third-party tool or software.
Sample C# code:
var configuration = new GroupDocs.Merger.Cloud.Sdk.Client.Configuration(MyAppSid, MyAppKey);
var apiInstance_Document = new GroupDocs.Merger.Cloud.Sdk.Api.DocumentApi(configuration);
var apiInstance_File = new GroupDocs.Merger.Cloud.Sdk.Api.FileApi(configuration);
var pathToSourceFiles = #"C:/Temp/input/";
var remoteFolder = "Temp/";
var joinItem_list = new List<JoinItem>();
try
{
DirectoryInfo dir = new DirectoryInfo(pathToSourceFiles);
System.IO.FileInfo[] files = dir.GetFiles();
foreach (System.IO.FileInfo file in files)
{
var request_upload = new GroupDocs.Merger.Cloud.Sdk.Model.Requests.UploadFileRequest(remoteFolder + file.Name, File.Open(file.FullName, FileMode.Open));
var response_upload = apiInstance_File.UploadFile(request_upload);
var item = new JoinItem
{
FileInfo = new GroupDocs.Merger.Cloud.Sdk.Model.FileInfo
{ FilePath = remoteFolder + file.Name }
};
joinItem_list.Add(item);
}
var options = new JoinOptions
{
JoinItems = joinItem_list,
OutputPath = remoteFolder + "Merged_Document.docx"
};
var request = new JoinRequest(options);
var response = apiInstance_Document.Join(request);
Console.WriteLine("Output file path: " + response.Path);
}
catch (Exception e)
{
Console.WriteLine("Exception while Merging Documents: " + e.Message);
}
That code is inserting a page break after each file.
Since sections control headers, if a second or subsequent document has a header, you'll probably be wanting to keep the original section properties, and insert those after your first document.
If you look at your original document as a docx, you'll probably see that your section is a document level section properties element.
The easiest way around your problem may be to create a second section properties element inside the last paragraph (which contains the header information). Then this should just stay there when the documents are merged (ie other paragraphs added after it).
That's the theory. See also http://www.pcreview.co.uk/forums/thread-898133.php
But I haven't tried it; it assumes InsertFile behaves as I expect it should.