How can I use If-else condition to the following statement? - asp.net-mvc

This is the space in my Controller section and I would like to rectify the code
public ActionResult UploadFiles(FileDetails fileDetails)
{
for(int i=0;Request.Files.Count > i;i++)
{
if (Request.Files.Count > 0)
{
var file = Request.Files[i];
var fileType = Path.GetExtension(file.FileName); //-> I have declared the variable but I don't know how to create file type using if-else condition
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/UploadFileDetails/"), fileName);
file.SaveAs(path);
fileDetails.FileName = fileName;
}
else
{
if (file != null && file.ContentLength > 0)
{
var imageName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/FileImage/"), imageName);
file.SaveAs(path);
fileDetails.Imagename = imageName;
}
}
}
}
_context.FileDetails.Add(fileDetails);
_context.SaveChanges();
return RedirectToAction("UploadFiles", "FileManagement");
}
If value=1 is files and value=2 is image files how to split the extensions?

Related

Getting same Current and Original value of change tracker modified state

Below is my override saveChanges Methed which calls SetChanges Method
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
SetChanges();
OnBeforeSaving();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
Right now, Sometimes code works completely fine but in some scenario It gives same value of both property.OriginalValue and property.CurrentValue for Modification so I am not able find what is the issue in my code
private void SetChanges()
{
Guid SystemLogId = Guid.NewGuid();
var currentDate = DateTime.Now;
var entitiesTracker = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified || p.State == EntityState.Added).ToList();
foreach (var entry in entitiesTracker)
{
var pagename = entry.Entity.GetType().Name;
if (pagename != "ExceptionLog")
{
var rowid = 0;
try
{
rowid = int.Parse(entry.OriginalValues["Id"].ToString());
}
catch (Exception)
{ }
SystemLog sysLog = new SystemLog();
List<SystemChangeLog> changeLog = new List<SystemChangeLog>();
foreach (PropertyEntry property in entry.Properties)
{
string propertyName = property.Metadata.Name;
switch (entry.State)
{
case EntityState.Added:
sysLog.Event = "Created";
break;
case EntityState.Modified:
{
sysLog.Event = "Updated";
if (propertyName != "ModifiedDate" && propertyName != "CreatedDate" && propertyName != "ModifiedBy" && propertyName != "CreatedBy" && propertyName != "RowVersion")
{
var original = Convert.ToString(property.OriginalValue);
var current = Convert.ToString(property.CurrentValue);
if (property.IsModified && !original.Equals(current))
{
SystemChangeLog log = new SystemChangeLog()
{
Property = propertyName,
OldValue = original,
NewValue = current,
DateOfChange = currentDate,
rowid = rowid,
SystemLogId = SystemLogId.ToString(),
};
changeLog.Add(log);
}
}
}
break;
}
}
base.Set<SystemChangeLog>().AddRange(changeLog);
if(changeLog.Count() >0 || entry.State == EntityState.Added)
{
sysLog.UserId = UserId;
sysLog.Date = currentDate;
sysLog.Page = pagename;
sysLog.Location = ExceptionHandler(entry, "Location");
sysLog.IPAddress = ExceptionHandler(entry, "IPAddress");
sysLog.MACAddress = ExceptionHandler(entry, "MACAddress");
sysLog.SystemLogId = SystemLogId.ToString();
base.Set<SystemLog>().Add(sysLog);
}
}
}
}
And also Is there any way to make it fast for more than thousand entry
hope below code can help:
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
setChanges(); // to get new value and old value
var result = base.SaveChanges(acceptAllChangesOnSuccess);
OnAfterSaveChanges();// to get auto added id
return result;
}

How to make file uploading optional using Mvc 4

I am uploading 3 types of files, i.e 1)video 2)image 3)document.
if i am uploading all three files at once so it is upload and show successfully, but if i want to skip one the file of uploading then it giving me following errors. Please Help me here:
httpPostedFile.SaveAs(fileSavePath);
db.SaveChanges();
one the errors is because of sending path to db i guess.
[HttpPost]
public ActionResult AddSKU(SKU_Det skufiles, IEnumerable<HttpPostedFileBase> files)
{
var httpPostedFile = Request.Files[0];
if (httpPostedFile != null)
{
var uploadFilesDir = System.Web.HttpContext.Current.Server.MapPath("~/Content/Videos");
if (!Directory.Exists(uploadFilesDir))
{
Directory.CreateDirectory(uploadFilesDir);
}
var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);
httpPostedFile.SaveAs(fileSavePath);
}
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(HttpContext.Server.MapPath("~/Areas/Admin/Images/") + file.FileName);
}
}
SKU_Det sku = new SKU_Det();
sku.SKU = skufiles.SKU;
sku.VideoPath = Request.Files[0].FileName;
sku.Imagepath = sku.FilePath = Request.Files[1].FileName;
sku.FilePath = sku.FilePath = Request.Files[2].FileName;
db.SKU_Det.Add(sku);
db.SaveChanges();

MVC Import .csv

Controller
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelFile)
{
if (excelFile == null || excelFile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file<br>";
return View("Index");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx") || excelFile.FileName.EndsWith("csv"))
{
string fileName = Path.GetFileName(excelFile.FileName);
string path = Path.Combine(Server.MapPath("~/Content"), fileName);
//string path = Server.MapPath("~/Content/" + excelFile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelFile.SaveAs(path);
//Read data from excel file
MExcel.Application application = new MExcel.Application();
MExcel.Workbook workbook = application.Workbooks.Open(path);
MExcel.Worksheet worksheet = workbook.ActiveSheet;
MExcel.Range range = worksheet.UsedRange;
List<PH> publicholidays = new List<PH>();
for (int row = 0; row <= range.Rows.Count; row++)
{
PH ph = new PH();
ph.Subject = ((MExcel.Range)range.Cells[row, 1]).Text;
ph.StartDate = ((MExcel.Range)range.Cells[row, 2]).Text;
ph.EndDate = ((MExcel.Range)range.Cells[row, 4]).Text;
publicholidays.Add(ph);
}
ViewBag.Publicholidays = publicholidays;
return View("Success");
}
else
{
ViewBag.Error = "Incorrect file type<br>";
return View("Index");
}
}
}
I want to import a .csv file but why doesn't it work while when i try to import a normal .xls files, it works? Is there something wrong with my code or is it that I can't import .csv files this way?

How to append key to an image's name asp.net mvc

Here is my code to append postfix to an image:
private void SaveUpload(SledBuck sledBuck )
{
if (Request.Files.Count > 0)
{
var postFix = "_" + sledBuck.Id;
for (var index = 0; index < Request.Files.Count; index++)
{
if (Request.Files[index].ContentLength > 0)
{
var hpf = Request.Files[index];
var postedFileName = string.Format("{0}-{1}", Path.GetFileName(hpf.FileName), postFix);
string folderPath = ConfigurationManager.AppSettings["ImagePath"];
var savedFileName = Path.Combine(Server.MapPath(folderPath), postedFileName);
hpf.SaveAs(savedFileName); // Save the file
}
}
}
}
Let's say the image's name is image.jpg. I want to append primary key to it's name before updating it like image_1.jpg. For the code above the postedFileName = image.jpg_1 which is not what I want. How can I append the Id properly?
so basically what you get as hpf.FileName is FileName + Extension. You need to get the extension and work accordingly,
so proceed like this :
var hpf = Request.Files[index];
var FileExtension = Path.GetExtension(hpf.FileName);
var FileNameWithoutExtension = hpf.FileName.Replace(FileExtension, "");
var FileUniqueName = String.Format("{0}_{1}{2}", FileNameWithoutExtension, GenerateDateTimeStamp(), FileExtension);
string folderPath = ConfigurationManager.AppSettings["ImagePath"];
var savedFileName = Path.Combine(Server.MapPath(folderPath), FileUniqueName);
hpf.SaveAs(savedFileName); // Save the file
where GenerateDateTimeStamp() is
public string GenerateDateTimeStamp()
{
return DateTime.Now.ToString("ddmmyyyyMMhhssttt");
}
in here you can have your primary keys aswell.
this should give you some idea

DTE2 _applicationObject reading filename in folder

below is the current codes i have.
what it does is basically loop thru project solution project file and detect if it is a C# file. however it can't detect files that are put in a folder , how can i modify it to read a C# file in a solution folder.
Regards , Andy
foreach (var projectItem in
_applicationObject.Solution.Projects.Cast<Project>().SelectMany(project => project.ProjectItems.Cast<ProjectItem>()))
{
//for (var i = 0; i < projectItem.FileCount; i++)
//{
if (projectItem.FileCount > 0 && projectItem.Name.EndsWith(".cs")) // check if project is .Cs files
{
string fileName;
try
{
fileName = projectItem.FileNames[0];
}
catch (Exception)
{
continue;
}
//end of find filename
}
}
This will print all items in the solution, I believe.
It works with C++ solution in VS 2012.
// XXX Test
IEnumerator enumerator = m_applicationObject.Solution.GetEnumerator();
string indent = " ";
while (enumerator.MoveNext())
{
Project p = enumerator.Current as Project;
if (p != null)
{
Debug.WriteLine(p.Name);
ProcessProjectItems(p.ProjectItems, indent);
}
}
// XXX Test
void ProcessProjectItems(ProjectItems pis, string indent)
{
if (pis == null)
return;
IEnumerator items = pis.GetEnumerator();
while (items.MoveNext())
{
ProjectItem pi = items.Current as ProjectItem;
if (pi != null)
{
Debug.WriteLine(indent + pi.Name);
if (pi.ProjectItems != null)
{
ProcessProjectItems(pi.ProjectItems, indent + " ");
}
else
{
Project p = pi.Object as Project;
if (p != null && p.ProjectItems != null)
ProcessProjectItems(p.ProjectItems, indent + " ");
}
}
}
}

Resources