I want to upload file to S3 with BOM. How can I do this?
var transferUtility = new TransferUtility(client);
string content = "hello";
byte[] b = DefaultEncoding.GetBytes(content);
using (var fileStream = new MemoryStream(b))
{
var request = new TransferUtilityUploadRequest
{
BucketName = bucket,
InputStream = fileStream,
Key = NormalizePath(Path.Combine(folder, file.Name)),
};
}
transferUtility.Upload(request);
When I download file from S3 it's UTF-8, but not UTF-8-BOM
var transferUtility = new TransferUtility(client);
string content = "hello";
byte[] b = Encoding.UTF8.GetPreamble().Concat(DefaultEncoding.GetBytes(content)).ToArray();
using (var fileStream = new MemoryStream(b))
{
var request = new TransferUtilityUploadRequest
{
BucketName = bucket,
InputStream = fileStream,
Key = NormalizePath(Path.Combine(folder, file.Name)),
};
}
transferUtility.Upload(request);
Related
I'm trying to convert/Create a PKCS7 "p7b" Certificate from signed certificate pem + chain using BouncyCastle or .net Cryptography class
I tried to use only BC without success, so I use BC only to read pem certs and then transform it to an X509Certificate2 object. What I'm looking for at the end is a pem string at the end starting with "-----BEGIN PKCS7-----" to save it as p7b file
what have I done..
public void DownloadP7bFile(string certId)
{
var records = (DataView)myCertDataSource.Select(DataSourceSelectArguments.Empty);
var selected = Guid.Parse(certId);
foreach (DataRow row in records.Table.Rows)
{
if (!Guid.Parse(row.Field<Guid>("cert_id").ToString()).Equals(selected)) continue;
var filename = row.Field<string>("cert_fqdn_main");
var certContent2 = row.Field<string>("certHash_certificate");
var certissuer = row.Field<string>("certHash_issuer");
DataTable chaincerts = GetChainCertsFromDB(certissuer);
//### get pem string from DB to BC cert objects
Org.BouncyCastle.X509.X509Certificate serverCert = CreateCertObjFromPem(certContent2);
Org.BouncyCastle.X509.X509Certificate interCert = CreateCertObjFromPem(chaincerts.Rows[0].Field<string>("cacert_pemhash"));
Org.BouncyCastle.X509.X509Certificate rootCert = CreateCertObjFromPem(chaincerts.Rows[1].Field<string>("cacert_pemhash"));
//### transform to X509Certificate2 object
System.Security.Cryptography.X509Certificates.X509Certificate2 serverCert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2();
System.Security.Cryptography.X509Certificates.X509Certificate2 interCert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2();
System.Security.Cryptography.X509Certificates.X509Certificate2 rootCert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2();
serverCert2.Import(serverCert.GetEncoded());
interCert2.Import(interCert.GetEncoded());
rootCert2.Import(rootCert.GetEncoded());
//### collect all needed certificates
var collection = new System.Security.Cryptography.X509Certificates.X509Certificate2Collection();
collection.Add(rootCert2);
collection.Add(interCert2);
collection.Add(serverCert2);
var pkcs7ContentBytes = collection.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs7);
//### Test if pkcs7 can be read ###
System.Security.Cryptography.Pkcs.SignedCms sigcms = new System.Security.Cryptography.Pkcs.SignedCms();
sigcms.Decode(pkcs7ContentBytes);
if (sigcms.Certificates.Count > 0)
{
Console.WriteLine("Aussteller: {0}", sigcms.Certificates[0].IssuerName.Name);
Console.WriteLine("Gültig bis {0}", sigcms.Certificates[0].NotAfter);
}
var sigvar2 = sigcms.Encode();
var pkcs7Content = Convert.ToBase64String(pkcs7ContentBytes); //das gute
var certEncodedBytes = Convert.FromBase64String(pkcs7Content);
var certContent = Encoding.UTF8.GetString(certEncodedBytes);
var certContent7 = UTF8Encoding.UTF8.GetString(certEncodedBytes);
var CertContent8 = Convert.ToBase64String(sigvar2);
var CertContent8Bytes = Convert.FromBase64String(CertContent8);
var certfromsig = sigcms.Certificates.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs7);
//var pkcs7cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certEncodedBytes);
//var pkcs7cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(sigvar2);
//System.Security.Cryptography.Pkcs.EnvelopedCms pkcs7Envelop = new System.Security.Cryptography.Pkcs.EnvelopedCms();
//File.WriteAllBytes(#"")
//string utfString = Encoding.UTF8.GetString(pkcs7ContentBytes, 0, pkcs7ContentBytes.Length);
var memoryStream = new MemoryStream(certEncodedBytes);
//var cryptostream = new System.Security.Cryptography.CryptoStream(memoryStream);
//memoryStream.Write(pkcs7ContentBytes, 0, pkcs7ContentBytes.Length);
var test31 = memoryStream.ToArray();
var test32 = memoryStream.Read(certEncodedBytes, 0, certEncodedBytes.Length);
memoryStream.Flush();
memoryStream.Close();
//var test30 = DecoderConverter.ConvertX509ToPkcs7(rootCert, interCert, serverCert);
PerformFileDownload(filename, "p7b", pkcs7Content);
break;
}
}
This is my code
string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
string fileName = file.FileName.Split("\\").LastOrDefault();
filePath = Path.Combine(filePath, fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
await file.CopyToAsync(fileStream);
}
}
I want to save the file name with unique id (GUID) in Database ?
string filePath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
string fileName = file.FileName.Split("\\").LastOrDefault();
System.IO.File.Move(filePath+ "\\" + fileName, Convert.ToString(Guid.NewGuid())+ Path.GetExtension(fileName));
filePath = Path.Combine(filePath, documents.SavedAs);
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
await file.CopyToAsync(fileStream);
}
}
I'm trying to post a file in a json object to an external rest api over https. I have confirmed the json object is formatted correctly, do I have to do anything special to post to a rest api over https? I'm using the answer found over here as a guide: How to post JSON to the server?
private static void PostDatatoFTP(string FileName,
string fileString, string centerCode, string fileType) {
try {
byte[] plainTextBytes = Encoding.ASCII.GetBytes(fileString);
string base64File = Convert.ToBase64String(plainTextBytes);
FileInfo fileInfo = new FileInfo {
FileData = base64File,
FileName = FileName,
FileType = fileType,
FileVersion = _fileVersion
};
FileInfo[] transmitFileInfo = new FileInfo[1];
transmitFileInfo[0] = fileInfo;
Json jsonObject = new Json {
RequestType = _RequestType,
APIVersion = _apiVersion,
SubmissionId = Guid.NewGuid().ToString(),
UserId = _ftpUsername,
Password = _ftpPassword,
Vendor = _vendor,
CenterCode = centerCode,
FileInfo = transmitFileInfo
};
var json = JsonConvert.SerializeObject(jsonObject);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_uploadPath);
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream())) {
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream() ?? throw new InvalidOperationException())) {
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
}
catch (WebException e) {
Console.WriteLine(e.Message);
String status = ((HttpWebResponse)e.Response).StatusDescription;
Console.WriteLine(status);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
I'm trying to post to WCF service. I get this error
"You must write ContentLength bytes to the request stream before calling [Begin]GetResponse."
Code:
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "patron=WTM";
byte[] data = encoding.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8733/FileShareWebServices/UploadFile");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = data.Length;
httpWebRequest.GetRequestStream();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Your posted code doesn't write anything to the request stream which is most likely the cause of the error. Once you get the request stream you should write to it the contents and the length, like this:
using (Stream requestStream = httpWebRequest.GetRequestStream)
{
requestStream.Write(data, 0, data.Length);
}
The complete code would look like this:
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "patron=WTM";
byte[] data = encoding.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8733/FileShareWebServices/UploadFile");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = data.Length;
//httpWebRequest.GetRequestStream();
// Code to write data to the stream
using (Stream requestStream = httpWebRequest.GetRequestStream)
{
requestStream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I am using this code but gives me this error:
Failed to retrieve data from the database. Details: [Database Vendor Code: 201 ]
public JsonResult ReportCertificateOfEmployment(int EmployeeId, int SigId, string SigPosition)
{
string Userkey = "gHeOai6bFzWskyUxX2ivq4+pJ7ALwbzwF55dZvy/23BrHAfvDVj7mg ";
string PassKey = "lLAHwegN8zdS7mIZyZZj+EmzlkUXkvEYxLvgAYjuBVtU8sw6wKXy2g ";
string rptlogin = ConfigurationManager.AppSettings.Get("rptlogin");
string rptPassword = ConfigurationManager.AppSettings.Get("rptPassword");
MemoryStream oStream;
CertificateOfEmployment rpt = new CertificateOfEmployment();
rpt.Refresh();
rpt.SetDatabaseLogon(rptlogin, rptPassword);
rpt.SetParameterValue(0, EmployeeId);
rpt.SetParameterValue(1, SigId);
rpt.SetParameterValue(2, SigPosition);
rpt.SetParameterValue(3, DateTime.Now);
oStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); --------- this gives me an error
// extract only the fielname
string filename = Convert.ToString((DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second) + Convert.ToString(DateTime.Now.Millisecond)) + "BarangayClearance";
var len = oStream.Length;
// store the file inside ~/App_Data/uploads folder
// var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
// file.SaveAs(path);
FileTransferServiceClient client2 = new FileTransferServiceClient();
RemoteFileInfo rmi = new RemoteFileInfo();
DateTime dt = DateTime.Now;
// upload file using webservice
DownloadRequest dr = new DownloadRequest();
//web service method to upload a file and return the unique id of the newly uploaded file
string fId = client2.UploadFileGetId("", filename, len, PassKey, Userkey, oStream);
//Instantiate the object Img which is a table in the database server of the application
//Download file using web service;
//DownloadFile in Refence.cs has been edited to return a RemoteFileInfo Class
//before, the return type of DownloadFile method was a Stream type
JsonResult result = new JsonResult();
result.Data = new
{
fileId = fId,
filename = filename
};
rpt.Close();
rpt.Dispose();
var arr = oStream.ToArray();
oStream.Close();
oStream.Dispose();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}