LINQ file upload malfunction w EF - c#

I am refactoring a section of my app to save a file to the Db in a bit field. In other places I have used the SqlCommand method but here I would like to latch on to my existing EF procedure, for many reasons not apparent. The uploader works fine but it breaks down when it gets to the LINQ. When I query the Db, instead of the usual "0x25504462D..." in the bit field, I get simply "0x". Attempting to view the file gets a message "file is empty". Am I close? The other fields are inserted perfectly, and there are no errors in the insert process. How do I "feed" the file to the fileUpload? Please advise.
HttpPostedFileBase file = Request.Files[inputTagName];
FileUpload fileUpload = new FileUpload();
using (DBEntities ode = new DBEntities())
{
(check if file exists...)
else
{
MyModels.File newfile = new MyModels.File();
newfile.ID = Guid.NewGuid();
newfile.Name = fn;
newfile.VirtualPath = filePath;
newfile.DateTimeUploaded = DateTime.Now;
newfile.binFile = fileUpload.FileBytes;
ode.AddToFiles(newfile);
}
ode.SaveChanges();
}

You could try getting the `byte[]' value of the uploaded file.
HttpPostedFileBase file = Request.Files[inputTagName];
var uploadedFile = new byte[file.InputStream.Length];
using (DBEntities ode = new DBEntities())
{
(check if file exists...)
else
{
MyModels.File newfile = new MyModels.File();
newfile.ID = Guid.NewGuid();
newfile.Name = fn;
newfile.VirtualPath = filePath;
newfile.DateTimeUploaded = DateTime.Now;
newfile.binFile = uploadedFile;
ode.AddToFiles(newfile);
}
ode.SaveChanges();
}

After much lamenting and gnashing of teeth (and encouragement from #denchu) it was apparent I needed to read the data:
HttpPostedFileBase file = Request.Files[inputTagName];
//var uploadedFile = new byte[file.InputStream.Length];
BinaryReader br = new BinaryReader(file.InputStream);
byte[] uploadedFile = br.ReadBytes(file.ContentLength);
using (DBEntities ode = new DBEntities())
{
(check if file exists...)
else
{
MyModels.File newfile = new MyModels.File();
newfile.ID = Guid.NewGuid();
newfile.Name = fn;
newfile.VirtualPath = filePath;
newfile.DateTimeUploaded = DateTime.Now;
newfile.binFile = uploadedFile;
ode.AddToFiles(newfile);
}
ode.SaveChanges();
}

Related

Attaching files to xero invoice using Xero.NetStandard.OAuth2.Api

I am trying to attach a file to the Xero invoice and using Xero.NetStandard.OAuth2.Api and the net framework starter app for it.
Below is the code we are using to attach, however it throws an error : A validation exception occurred:The file couldn't be uploaded because it isn't a supported file type.
We are uploading and .png type file also tried using a .pdf file
var xeroToken = TokenUtilities.GetStoredToken();
var utcTimeNow = DateTime.UtcNow;
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
XeroConfiguration XeroConfig = new XeroConfiguration
{
ClientId = ConfigurationManager.AppSettings["XeroClientId"],
ClientSecret = ConfigurationManager.AppSettings["XeroClientSecret"],
CallbackUri = new Uri(ConfigurationManager.AppSettings["XeroCallbackUri"]),
Scope = ConfigurationManager.AppSettings["XeroScope"],
State = ConfigurationManager.AppSettings["XeroState"]
};
if (utcTimeNow > xeroToken.ExpiresAtUtc)
{
var client = new XeroClient(XeroConfig, httpClientFactory);
xeroToken = (XeroOAuth2Token)await client.RefreshAccessTokenAsync(xeroToken);
TokenUtilities.StoreToken(xeroToken);
}
string accessToken = xeroToken.AccessToken;
string xeroTenantId = xeroToken.Tenants[0].TenantId.ToString();
var AccountingApi = new AccountingApi();
var sevenDaysAgo = DateTime.Now.AddDays(-7).ToString("yyyy, MM, dd");
var invoicesFilter = "Date >= DateTime(" + sevenDaysAgo + ")";
var response = await AccountingApi.GetInvoicesAsync(accessToken, xeroTenantId, null, invoicesFilter);
var invoices = response._Invoices;
foreach (Invoice inv in invoices)
{
if (inv.HasAttachments == false && inv.InvoiceID != null)
{
string filePath = ConfigurationManager.AppSettings["AttachmentPath"].ToString();
filePath = Path.Combine(filePath, inv.InvoiceNumber);
string[] filePaths = Directory.GetFiles(filePath);
foreach (var file in filePaths)
{
byte[] contentFileBytes = System.IO.File.ReadAllBytes(file);
Guid invoiceId = Guid.Parse(inv.InvoiceID.ToString());
var attachResponse = await AccountingApi.CreateInvoiceAttachmentByFileNameAsync(accessToken, xeroTenantId, invoiceId, System.IO.Path.GetFileNameWithoutExtension(file), true, contentFileBytes);
}
}
}
Could anyone please help, if there is any sample code for attaching a file to invoice created.

save generated pdf on server

I'm generating pdf from view using ROTATIVA
public ActionResult StandartPDF()
{
var makeCvSession = Session["makeCV"];
var something = new Rotativa.ViewAsPdf("StandartPDF", makeCvSession) { FileName = "cv.pdf" };
return something;
}
using that code user can download it. But at first I want to it on server. How can I do that?
I solved that using SaveOnServerPath property in Rotativa class
public ActionResult StandartPDF()
{
var makeCvSession = Session["makeCV"];
var root = Server.MapPath("~/PDF/");
var pdfname = String.Format("{0}.pdf", Guid.NewGuid().ToString());
var path = Path.Combine(root, pdfname);
path = Path.GetFullPath(path);
var something = new Rotativa.ViewAsPdf("StandartPDF", makeCvSession) { FileName = "cv.pdf", SaveOnServerPath = path };
return something;
}

Amazon Order API or Report API to get SKU number and total quantity sold?

I want a list of all SKU for which there were any sales between the From Date and To Date with the quantity sold. I am all confused what to do - should I use Amazon MWS Order API for this or Report API for this? Does anyone have a c# code which shows how a report is requested and downloaded at my end for further processing i.e. saving the data in databases.
Any help would be much appreciated.
p.s. I have a large volume of data
UPDATE: Meanwhile I have written this code to get the report type and save the data. Now the error is "Access to path denied"
private const string targetRptType = "_GET_CONVERGED_FLAT_FILE_ORDER_REPORT_DATA_";
try
{
RequestReportRequest reportRequestRequest = new RequestReportRequest();
reportRequestRequest.Merchant = merchantId;
reportRequestRequest.ReportType = targetRptType;
reportRequestRequest.StartDate = DateTime.Now.AddDays(-3);
reportRequestRequest.EndDate = DateTime.Now;
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
config.ServiceURL = "https://mws.amazonservices.com";
MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, applicationName, applicationVersion, config);
RequestReportResponse requestResponse = service.RequestReport(reportRequestRequest);
Thread.Sleep(15000);
Response.Write(requestResponse.RequestReportResult.ReportRequestInfo.ReportProcessingStatus);
GetReportRequestListRequest reportRequestListRequest = new GetReportRequestListRequest();
reportRequestListRequest.Merchant = merchantId;
List<ReportRequestInfo> myListzz = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new GetReportRequestListResponse();
reportRequestListResponse = service.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new GetReportRequestListResult();
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
while (myListzz[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Thread.Sleep(20000);
reportRequestListResponse = service.GetReportRequestList(reportRequestListRequest);
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
}
GetReportListRequest listRequest = new GetReportListRequest();
listRequest.Merchant = merchantId;
listRequest.ReportRequestIdList = new IdList();
listRequest.ReportRequestIdList.Id.Add(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportListResponse listResponse = service.GetReportList(listRequest);
//MessageBox.Show(listResponse.GetReportListResult.ReportInfo.ToString());
GetReportListResult getReportListResult = listResponse.GetReportListResult;
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = merchantId;
reportRequest.WithReportId(getReportListResult.ReportInfo[0].ReportId);
GetReportResponse reportResponse = new GetReportResponse();
try
{
reportRequest.Report = File.Open("C:\\AmazonReport.csv", FileMode.OpenOrCreate, FileAccess.ReadWrite); // Getting error access to path denied
reportResponse = service.GetReport(reportRequest);
}
catch (MarketplaceWebServiceException exe)
{
Response.Write(exe);
}
StreamReader sr = new StreamReader(reportRequest.Report);
Response.Write(sr.ReadToEnd());
sr.Close();
}
catch (MarketplaceWebServiceException ex)
{
Response.Write(ex.Message);
}
Can anyone please check my code and suggest if this is the correct way to get data from a report? I am still not able to save the report.
UPDATE 2
I have changed the path and now the error is gone and the file is created but it is just a 1 kb file with 2 records.. looks like it is not fetching full data. Not sure if the code is correct or not. Checking this on scratchpad https://mws.amazonservices.com/scratchpad/index.html
I would save the report in your current working directory. Access to C:\ is usually locked down unless you are running as an admin. Use the following if you want to be explicit (if you provide just a file name and not a fully justified path, it will also save in your current working directory)
reportRequest.Report = File.Open(Path.Combine(Directory.GetCurrentDirectory(), "AmazonReport.csv"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
The Orders API would make this much easier in my opinion. You can request Orders using a Date range and get everything you need.

Trying to download file from FileCabinet in NetSuite using C# program

I need to download JPG file from FileCabinet in NetSuite. For that I know the file name, so I searched file and assigned to FileObject. I got the object right, but got NULL content. I am providing here some code. Can anybody point out the error or any missing step here? Thank you.
var result = _service.search(flSearch);
if (result.totalRecords > 0)
{
recordList = result.recordList;
Record[] records = new Record[recordList.Length];
for (int j = 0; j < recordList.Length; j++)
{
if (recordList[j] is File)
{
File itemImage = (File)(recordList[j]);
byte[] data;
data = new Byte[(int)itemImage.fileSize];
data = itemImage.content; //Here getting NULL value
FileStream inFile;
using (inFile = new FileStream("newImage.jpg", FileMode.Create, FileAccess.Write))
{
inFile.Write(data, 0, data.Length);
}
}
}
}
itemImage is just a string - base64.
take that string and do a base64 decode and save that to your local file.
If the search is based on the internal id of the file you want to search, then the following code may help
var service = LoginNetSuite();
Tuple<string, string> fileContent = null;
FileSearch fileSearch = new FileSearch();
FileSearchBasic fileSearchBasic = new FileSearchBasic();
// Specify the folder in which the search is to be done.
SearchMultiSelectField folderFilter = new SearchMultiSelectField();
folderFilter.#operator = SearchMultiSelectFieldOperator.anyOf;
folderFilter.operatorSpecified = true;
RecordRef[] folder = new RecordRef[1];
folder[0] = new RecordRef();
folder[0].internalId = "78990"; // 78990 => Internal id of the folder.
folderFilter.searchValue = folder;
fileSearchBasic.folder = folderFilter;
// Specify the file internal id.
SearchMultiSelectField fileFilter = new SearchMultiSelectField();
fileFilter.#operator = SearchMultiSelectFieldOperator.anyOf;
fileFilter.operatorSpecified = true;
RecordRef[] rec = new RecordRef[1];
rec[0] = new RecordRef();
rec[0].internalId = "345656"; // 345656 => Internal id of the file.
fileFilter.searchValue = rec;
fileSearchBasic.internalId = fileFilter;
fileSearch.basic = fileSearchBasic;
var result = service.search(fileSearch);
var recordList = (Record[])result.recordList;
if (recordList != null && recordList.Length != 0)
{
var file = (File)result.recordList.First();
fileContent = new Tuple<string, string>(file.url, file.name);
}
In this code the folder internal id and the file internal id is given as the search parameters. So the file search will be done in the specified file cabinet with specified file id.
The response from netsuite will consist of the internal id, file name, url, folder name etc. The file can be downloaded from the url location.

Error: The name 'Name' does not exist in the current context

I've gone editing code -> which is never a good thing!
the code is for a file uploader in MVC. The thing was I was uploading two files at a time which meant they were inserted into separate rows in a database. This is the original code:
public ActionResult Index()
{
ViewData["Message"] = "Convert your eBooks!";
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile1()) continue;
string mimeType = Request.Files[upload].ContentType;
Stream fileStream = Request.Files[upload].InputStream;
string fileName = Path.GetFileName(Request.Files[upload].FileName);
int fileLength = Request.Files[upload].ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
const string connect = #"Server=localhost;Database=Images;user id=taraw; password=siemensbs;";
using (var conn = new SqlConnection(connect))
{
var qry = "INSERT INTO FileStore (FileContent, MimeType, FileName) VALUES (#FileContent, #MimeType, #FileName)";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#FileContent", fileData);
cmd.Parameters.AddWithValue("#MimeType", mimeType);
cmd.Parameters.AddWithValue("#FileName", fileName);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return View();
}
Here is my attempt at modifying the code in order to take in the files separately as opposed to using a loop, and inserting them into a single row in a database table:
public ActionResult Index()
{
if (!Request.Files["FileUpload1"].HasFile1())
{
string mimeTypePDF = Request.Files["FileUpload1"].ContentType;
Stream fileStreamPDF = Request.Files["FileUpload1"].InputStream;
string fileNamePDF = Path.GetFileName(Request.Files["FileUpload1"].FileName);
int fileLengthPDF = Request.Files["FileUpload1"].ContentLength;
byte[] fileDataPDF = new byte[fileLengthPDF];
fileStreamPDF.Read(fileDataPDF, 0, fileLengthPDF);
}
if(!Request.Files["FileUpload2"].HasFile1())
{
string mimeTypeCover = Request.Files["FileUpload2"].ContentType;
Stream fileStreamCover = Request.Files["FileUpload2"].InputStream;
string fileNameCover = Path.GetFileName(Request.Files["FileUpload2"].FileName);
int fileLengthCover = Request.Files["FileUpload2"].ContentLength;
byte[] fileDataCover = new byte[fileLengthCover];
fileStreamCover.Read(fileDataCover, 0, fileLengthCover);
}
const string connect = #"Server=localhost;Database=Images;user id=taraw; password=siemensbs;";
using (var conn = new SqlConnection(connect))
{
var qry = "INSERT INTO Book (FileContentPDF, MimeTypePDF, FileNamePDF, FileContentCover, MimeTypeCover, FileNameCover) VALUES (#FileContentPDF, #MimeTypePDF, #FileNamePDF, #FileContentCover, #MimeTypeCover, #FileNameCover)";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#FileContentPDF", fileDataPDF);
cmd.Parameters.AddWithValue("#MimeTypePDF", mimeTypePDF);
cmd.Parameters.AddWithValue("#FileNamePDF", fileNamePDF);
cmd.Parameters.AddWithValue("#FileContentCover", fileDataCover);
cmd.Parameters.AddWithValue("#MimeTypeCover", mimeTypeCover);
cmd.Parameters.AddWithValue("#FileNameCover", fileNameCover);
conn.Open();
cmd.ExecuteNonQuery();
}
return View();
}
Now I get the following errors for each cmd.Parameters.AddWithValue:
The name 'fileDataPDF' does not exist
in the current context
I'm presuming this is because it is outside of the IF statements but I'm a bit stuck on how to structure it. I eventually want to use linq to insert the files into the database as the above method is not ideal, but my main aim for now is to just get this bit working.
Any help would be appreciated greatly :)
You need to declare the variables outside of the if conditional scopes. e.g.
string mimeTypePDF;
string fileNamePDF;
byte[] fileDataPDF;
if (!Request.Files["FileUpload1"].HasFile1())
{
mimeTypePDF = Request.Files["FileUpload1"].ContentType;
Stream fileStreamPDF = Request.Files["FileUpload1"].InputStream;
fileNamePDF = Path.GetFileName(Request.Files["FileUpload1"].FileName);
int fileLengthPDF = Request.Files["FileUpload1"].ContentLength;
fileDataPDF = new byte[fileLengthPDF];
fileStreamPDF.Read(fileDataPDF, 0, fileLengthPDF);
}
(Fwiw, I think there are better ways to handle this multifile upload, but the above is simplest way to handle your question.)
You need to declare fileDataPDF outside the if statement, otherwise its only visible to the if block.
How about byte[] fileDataPDF; before if
and fileDataPDF = new byte[fileLengthPDF]; inside if?

Categories

Resources