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;
}
Related
I have this code to download a file in the database, but it only downloads the first user upload.
I tried using LastOrDefault and reverse to download the most recent file but I couldn't.
Does anyone have any idea how to do it?
[HttpGet]
[Route("~/DownloadFileCNPJ/{Id}")]
public async Task<IActionResult> DownloadFileCNPJ(long Id)
{
using (var context = new MyDbContext())
{
var cartaoCnpj = (from j in context.CartaoCNPJCedentes
where j.CedenteId.Equals(Id)
select j).Reverse().FirstOrDefault();
if (cartaoCnpj != null)
{
var content = new System.IO.MemoryStream(cartaoCnpj.CartaoCNPJ);
var contentType = cartaoCnpj.TipoCartãoCNPJ;
var fileName = cartaoCnpj.NomeArquivoCNPJ;
return File(content, contentType, fileName);
}
return null;
}
}
I need to get (not download) the content from 10.000~ manifest files within a project in Azure DevOps, but I don't manage to achieve this. I have found several ways to retrieve the content from one file at a time, but in this context, it is neither an efficient nor sustainable solution. I have managed to retrieve all files of a particular file type by checking if the file path ends with the name of the file, then using the TfvcHttpClientBase.GetItemsBatch method. However, this method does not return the item's content.
Program.cs
using Microsoft.TeamFoundation.SourceControl.WebApi;
AzureRest azureRest = new AzureRest();
var tfvcItems = azureRest.GetTfvcItems();
List<TfvcItemDescriptor> itemDescriptorsList = new List<TfvcItemDescriptor>();
foreach(var item in tfvcItems)
{
//Example manifest file .NET
if (item.Path.EndsWith("packages.config"))
{
var itemDescriptor = new TfvcItemDescriptor()
{
Path = item.Path,
RecursionLevel = VersionControlRecursionType.None,
Version = "",
VersionOption = TfvcVersionOption.None,
VersionType = TfvcVersionType.Latest
};
itemDescriptorsList.Add(itemDescriptor);
}
}
TfvcItemDescriptor[] itemDescriptorsArray = itemDescriptorsList.ToArray();
var itemBatch = azureRest.GetTfvcItemsBatch(itemDescriptorsArray);
foreach(var itemList in itemBatch)
{
foreach(var itemListList in itemList)
{
Console.WriteLine("Content: " + itemListList.Content); //empty/null
Console.WriteLine("ContentMetadata: " + itemListList.ContentMetadata); //not empty/null
}
}
AzureRest.cs
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
public class AzureRest
{
const string ORG_URL = "https://org/url/url";
const string PROJECT = "Project";
const string PAT = "PersonalAccessToken";
private string GetTokenConfig()
{
return PAT;
}
private string GetProjectNameConfig()
{
return PROJECT;
}
private VssConnection Authenticate()
{
string token = GetTokenConfig();
string projectName = GetProjectNameConfig();
var credentials = new VssBasicCredential(string.Empty, token);
var connection = new VssConnection(new Uri(ORG_URL), credentials);
return connection;
}
public List<TfvcItem> GetTfvcItems()
{
var connection = Authenticate();
using (TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>())
{
var tfvcItems = tfvcClient.GetItemsAsync(scopePath: "/Path", recursionLevel: VersionControlRecursionType.Full, true).Result;
return tfvcItems;
}
}
public List<List<TfvcItem>> GetTfvcItemsBatch(TfvcItemDescriptor[] itemDescriptors)
{
TfvcItemRequestData requestData = new TfvcItemRequestData()
{
IncludeContentMetadata = true,
IncludeLinks = true,
ItemDescriptors = itemDescriptors
};
var connection = Authenticate();
using (TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>())
{
var tfvcItems = tfvcClient.GetItemsBatchAsync(requestData).Result;
return tfvcItems;
}
}
}
}
For reference:
I have tested the codes you shared and when debugging at "itemDescriptorsList" and have found that there is no content specified in it, so that's why you cannot get the txt content.
You should first check and add the content property into the "itemDescriptorsList".
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.
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();
}
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.