How to use Tempdata to display the list - asp.net

I have did the excel upload in dotnet core .I had to use tempdata to retrieve the details of the excel in list.Instead in my below code i had used Static object to retrieve the list.My code works as like this ,when i click on upload button it will display the details in the excel sheet.and when click on save it will save it to database and i need to edit in grid view using ajax call also .Help me out
My Action in controller is
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
using (var stream = new FileStream(path, FileMode.Create))
{
await excelfile.CopyToAsync(stream);
}
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
employeesListObject.EmpModelList = employeesViewModelList;
return View(employeesListObject);
}
}
catch(Exception ex)
{
TempData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}

Try this, using your own list.
List<string> SomeList = new List<string>();
TempData["MyList"] = SomeList;
//then to get data just do
SomeList = TempData["MyList"] as List<string>; //This converts back to List<T>
Once you add the list to the TempData, you can retrive it from any Action or View in the same controller

Related

Sftp upload from memory stream asp.net

I am trying to upload a csv file that is created from a query and upload via sftp.
I am trying to avoid creating a file and then reading the file to upload it by keeping the data in memory.
Thanks in advance
var customerAddresses = addresses.Select(p => new { p.Customer.Name, p.Customer.AlternateName, p.City, p.StateProvince });
using (var memoryStream = new MemoryStream())
{
//if you pass a file path to streamWriter it creates a csv with the correct format and data
using (var streamWriter = new StreamWriter())
{
using (var csv = new CsvWriter(streamWriter))
{
csv.WriteRecords(customerAddresses);
var fileName = DateTime.UtcNow.ToString(dateFromat) + destinationFileName;
var privateKey = new PrivateKeyFile(sshKeyLocation);
var connectionInfo = new PrivateKeyConnectionInfo(address,
username,
new PrivateKeyFile(sshKeyLocation)
);
memoryStream.Flush();
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
client.ChangeDirectory(serverDirectory);
client.UploadFile(memoryStream, fileName); //is always an empty file
}
}
}
Try adding setting memoryStream Position to beginning with Seek before calling UploadFile and calling streamWriter.Flush();, not memoryStream.Flush():
streamWriter.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
client.ChangeDirectory(serverDirectory);
client.UploadFile(memoryStream, fileName);
}
I never figured out how to get it to work with MemoryStream and changed to to write a file and then read and upload that file.
public HttpResponseMessage Post([FromBody] CustomerIds[] CustomerIds)
{
try
{
if(CustomerIds.Length == 0)
{
throw new Exception("No customer ids passed in post body.");
}
else if (!File.Exists(sshKeyLocation))
{
throw new Exception("Missing ssh file.");
}
if(!Directory.Exists(localDirectory))
{
Directory.CreateDirectory(localDirectory);
}
var customerAddresses = _repository.GetPrimaryAddress(CustomerIds.Select(c => c.Id))
.Select(p => new
{
p.Customer.Name,
p.Customer.AlternateName,
p.City,
p.StateProvince
}
);
if (customerAddresses == null || !customerAddresses.Any())
{
throw new Exception("No customer addresses found for selected customers.");
}
var fileName = DateTime.UtcNow.ToString(dateFromat) + destinationFileName;
var localFilePath = Path.Combine(localDirectory, fileName);
CreateFile(customerAddresses, localFilePath);
UploadFile(localFilePath, fileName);
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
catch(Exception error)
{
logger.Error(error, error.Message);
throw error;
}
}
private void CreateFile(IEnumerable<object> customerAddresses, string filePath)
{
using (TextWriter streamWriter = new StreamWriter(filePath))
using (var csv = new CsvWriter(streamWriter))
{
csv.WriteRecords(customerAddresses);
}
}
private void UploadFile(string localFilePath, string destinationFileName)
{
var connectionInfo = new PrivateKeyConnectionInfo(address,
username,
new PrivateKeyFile(sshKeyLocation)
);
using (var fileStream = new FileStream(localFilePath, FileMode.Open))
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
client.ChangeDirectory(serverDirectory);
client.UploadFile(fileStream, destinationFileName);
}
}
I've run out of time to continue trying to upload using the MemoryStream and will just have to use this solution. Disappointed I couldn't get it to work.

How to send image file along with other parameter in asp.net?

I want to send image files to SQL Server using C#.
The below code is working and saving files and their paths into the database. I need the same data in my API endpoint's response. I've created a custom response class, called RegistrationResponse.
I'm beginner in this so I'm looking for help.
public async Task<RegistrationResponse> PostFormData(HttpRequestMessage request)
{
object data = "";
NameValueCollection col = HttpContext.Current.Request.Form;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/images");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
//read file data
foreach (MultipartFileData dataItem in provider.FileData)
{
try
{
string description = string.Empty;
string userId = string.Empty;
String fileName = string.Empty;
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.ToString().ToLower() == "userid")
{
userId = val;
}
else if (key.ToString().ToLower() == "description")
{
description = val;
}
}
}
String name = dataItem.Headers.ContentDisposition.FileName.Replace("\"", "");
fileName = userId + Path.GetExtension(name);
File.Move(dataItem.LocalFileName, Path.Combine(root, fileName));
using (var db = new AlumniDBEntities())
{
//saving path and data in database table
Post userPost = new Post();
userPost.Files = fileName;
userPost.Description = description;
userPost.UserID = Convert.ToInt32(userId);
userPost.CreatedDate = DateTime.Now;
db.Posts.Add(userPost);
db.SaveChanges();
data = db.Posts.Where(x => x.PostID ==
userPost.PostID).FirstOrDefault();
string output = JsonConvert.SerializeObject(data);
}
}
catch (Exception ex)
{
return Request.CreateResponse(ex);
}
}
return Request.CreateResponse(HttpStatusCode.Created);
});
var response = new RegistrationResponse
{
success = true,
status = HttpStatusCode.OK,
message = "Success",
data = data
};
return response;
}

Xamarin iOS: How can I open a pdf file using a standard reader

I need to open a pdf file using a default reader, android works, but for iOS i can not. And I do not have a solid experience with C # only 2 months
public void SaveOpen(string filename, MemoryStream stream)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, filename);
//Create a file and write the stream into it.
FileStream fileStream = File.Open(filePath, FileMode.Create);
stream.Position = 0;
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Close();
UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (currentController.PresentedViewController != null)
currentController = currentController.PresentedViewController;
UIView currentView = currentController.View;
}
To open a pdf file from a filePath:
public void OpenPDF(string filePath)
{
FileInfo fi = new FileInfo(filePath);
QLPreviewController previewController = new QLPreviewController();
previewController.DataSource = new PreviewControllerDataSource(fi.FullName, fi.Name);
UINavigationController controller = FindNavigationController();
if (controller != null)
controller.PresentViewController(previewController, true, null);
}
private UINavigationController FindNavigationController()
{
foreach (var window in UIApplication.SharedApplication.Windows)
{
if (window.RootViewController.NavigationController != null)
{
return window.RootViewController.NavigationController;
}
var value = CheckSubs(window.RootViewController.ChildViewControllers);
if (value != null)
return value;
}
return null;
}
private UINavigationController CheckSubs(UIViewController[] controllers)
{
foreach (var controller in controllers)
{
if (controller.NavigationController != null)
{
return controller.NavigationController;
}
var value = CheckSubs(controller.ChildViewControllers);
return value;
}
return null;
}
So, in your code, after saving it, just call OpenPDF with the correct path.

Open XML generates only <NewDataSet /> tag from a full Excel file, but work for other files

I have an excel file full of data, and I'm trying to use Open XML SDK to convert this file into xml file.
I followed the documentation and other questions here on stackoverflow. However, the output of the xml file is always <NewDataSet />. Knowing that I tried other excel files and it worked fine.
Here is how my excel file looks like:
And here is my code "I tried two approaches":
The first approach is to use DataSet.GetXML(), it returned the same value as the next code does.
var xmlDS = new ConvertExcelToXml().GetXML(filePath);
string xmlPath = server.MapPath("~/UploadedFiles/XML/");
StreamWriter xmlFile = new StreamWriter(xmlPath + Path.GetFileNameWithoutExtension(fileName) + ".xml");
xmlDS.WriteXml(xmlFile);
//The used method to return the excel file dataset
public DataSet GetXML(string filename)
{
using (DataSet ds = new DataSet())
{
ds.Tables.Add(this.ReadExcelFile(filename));
return ds;
}
}
//This method used to return DataTable for previous method
private DataTable ReadExcelFile(string filename)
{
DataTable dt = new DataTable();
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
IEnumerable<Sheet> sheetcollection = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheetcollection.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId);
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rowcollection = sheetData.Descendants<Row>();
if (rowcollection.Count() == 0)
{
return dt;
}
foreach (Cell cell in rowcollection.ElementAt(0))
{
dt.Columns.Add(GetValueOfCell(spreadsheetDocument, cell));
}
foreach (Row row in rowcollection)
{
DataRow temprow = dt.NewRow();
int columnIndex = 0;
foreach (Cell cell in row.Descendants<Cell>())
{
int cellColumnIndex = GetColumnIndex(GetColumnName(cell.CellReference));
if (columnIndex < cellColumnIndex)
{
do
{
temprow[columnIndex] = string.Empty;
columnIndex++;
}
while (columnIndex < cellColumnIndex);
}
temprow[columnIndex] = GetValueOfCell(spreadsheetDocument, cell);
columnIndex++;
}
dt.Rows.Add(temprow);
}
}
dt.Rows.RemoveAt(0);
return dt;
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}

How to upload a file on a server through api call in asp.net mvc

public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
WebClient webClient = new WebClient();
byte[] responseBinary = webClient.UploadFile(apiUrl, file.FileName);
string response = Encoding.UTF8.GetString(responseBinary);
/* Giving error here. How to proceed?
}
I want to upload a single file to this url and the response is shown in the figure above. How to proceed further with the same in C#? Please help
Try your code like below.
public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1];
file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(apiURL, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return new
{
code = result.StatusCode,
message = "Successful",
data = new
{
success = true,
filename = file.FileName
}
};
}
else
{
return new
{
code = result.StatusCode,
message = "Error"
};
}
}
}
}

Resources