Here I add product and save path of image, everything works fine and image path is saved
public ActionResult AddProduct(Product p, HttpPostedFileBase prodImg, decimal[] price)
{
try
{
string absoluthFolderPath = Server.MapPath("\\Images");
string pathOfImage = System.IO.Path.GetExtension(prodImg.FileName);
string newFileName = Guid.NewGuid() + pathOfImage;
absoluthFolderPath += "\\" + newFileName;
prodImg.SaveAs(absoluthFolderPath);
string relitivePath = #"\Images\" + newFileName;
p.ImagePath = relitivePath;
p.Blocked = false;
new ProductsBL().AddProduct(p);
ViewData\["msg"\] = "Successfuly";
}
catch(Exception ex)
{
}
ModelState.Clear();
return View();
}
When trying to update image path it gives me error shown on screenshot
public ActionResult Update(Product modifieDetails, HttpPostedFileBase updImg)
{
string absoluthFolderPath = Server.MapPath("\\Images");
string pathOfImage = System.IO.Path.GetExtension(updImg.FileName);
string newFileName = Guid.NewGuid() + pathOfImage;
absoluthFolderPath += "\\" + newFileName;
updImg.SaveAs(absoluthFolderPath);
string relitivePath = #"\Images\" + newFileName;
modifieDetails.ImagePath = relitivePath;
modifieDetails.Blocked = false;
new ProductsBL().UpdateProduct(modifieDetails);
return RedirectToAction("ListProduct");
}
[1]: http://i.stack.imgur.com/wgE88.png
You need to split this up:
new ProductsBL().AddProduct(p);
In order to save updates to an entity back to the store, you have to set "IsModified" on the entity, and then save the context. Like so...
using (ProductsBL context = new ProductsBL()) {
var p = (some query to get it from the store);
p.ImagePath = relitivePath;
p.Blocked = false;
p.IsModified = true;
context.SaveChanges();
}
As it is, you're creating a new entity and adding that to the store, not updating the existing one.
And, if you're coding in English, please fix the spellings: Modify, Relative, absolute.
Related
I'm attempting to add an image to a table and link it to a product. Here's the database table setup.
---- TWebProducts ----
intWebProductID
... A bunch of other variables that don't matter here
---- TWebProductImages ----
intWebProductID
intWebImageID
---- TWebImages ----
intWebImageID
varImage
Here's what I'm attempting to do which, is not working.
[HttpPost]
public ActionResult ProductEdit(IEnumerable<HttpPostedFileBase> files, TWebProduct tbl, HttpPostedFileBase file)
{
// Thumbnail image
if (file != null)
{
string path = null;
string pic = null;
pic = System.IO.Path.GetFileName(file.FileName);
path = System.IO.Path.Combine(Server.MapPath("~/ProductThumbnails/"), pic);
// file is uploaded
file.SaveAs(path);
tbl.varThumbnailImage = pic;
}
tbl.dteModified = DateTime.Now;
tbl.intCompanyID = 1;
// update the images
string fName = "";
try
{
//loop through all the files
foreach (var img in files)
{
//Save file content goes here
fName = img.FileName;
if (img != null && img.ContentLength > 0)
{
#region ImageSaving Stuff
var originalDirectory = new DirectoryInfo(string.Format("{0}ProductImages\\", Server.MapPath(#"\")));
//string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
string pathString = originalDirectory.ToString();
var fileName1 = Path.GetFileName(img.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, img.FileName);
img.SaveAs(path);
#endregion
// this is the important part
// Get all the data saved to a variable
TWebImage webImage = new TWebImage();
webImage.varImage = path;
// Add to the TWebImages and link to the Product
tbl.TWebImages.Add(webImage);
}
}
// Update the product
_unitOfWork.GetRepositoryInstance<TWebProduct>().Update(tbl);
}
catch (Exception ex)
{
}
return RedirectToAction("Products");
}
There's no error, but there's nothing in the link table or the images table.
Obviously I'm doing something wrong. I'm new to using ADO Entity and repositories. I'm pretty well versed in SQL and C#.
I don't know what to google or even what to look for. Any and all help is appreciated. Let me know if I can clarify anything.
My Project is in ASP.NET MVC, Right now I am using Razor Engine Service (RazorEngineService.RunCompile) to create multiple XML files and making it as a single Zip file and exporting it.
But the problem is that when we pass the model object each time to process the template and return it as separate XML files and completing the whole operation it takes more time to complete (Almost ~40 Seconds for 10 objects) for whole content to export.
Is there anything wrong with my current approach or am I doing it correctly right now? Please guide me If I am doing any mistakes in this approach.
private FileInfo Export(List<Model> modelList)
{
string timeStr = Datetime.Now.ToString();
string archiveFileName = "Main.zip";
string archivePath = Path.Combine(_reportFolderPath, archiveFileName);
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
foreach (var list in modelList)
{
string fileName = model.name + model.Id;
string filePath = GetModelExport(list, fileName, timeStr);
archive.CreateEntryFromFile(filePath, fileName + ".xml");
}
archive.Dispose();
}
return new FileInfo(archivePath);
}
private string GetModelExport(Model model, string fileName, string timeStr)
{
var processedTemplate = ProcessTemplate(model, TemplateName, TemplateKey);
string reportFilelName = fileName + "_" + timeStr + ".xml";
string filePath = Path.Combine(_reportFolderPath, reportFilelName);
using (var file = new StreamWriter(filePath))
{
file.Write(processedTemplate);
}
return filePath;
}
private string ProcessTemplate(Model model, string templateName, string templateKey)
{
var templateFilePath = Path.Combine(_reportTemplateFolder, templateName);
return ReportUtils.ProcessTemplate(templateFilePath, templateKey, model);
}
public static string ProcessTemplate(string templatePath, string templateKey, object model = null)
{
var templateService = RazorEngineService.Create();
var result = templateService.RunCompile(File.ReadAllText(templatePath), templateKey, null, model);
return result;
}
some of your code is missing so i cant see the whole picture, this is what i would start with..... gd luck.
public class HolderTempName
{
private TemplateService _templateService;
private Dictionary<string, string> _templateContainer;
public HolderTempName()
{
//this will save creating this everytime
_templateService = RazorEngineService.Create();
//this will hold the template so it does not have to fetch on each loop,
//if the same template is used.
_templateContainer = new Dictionary<string, string>();
}
//you will need to tweeek this to get the type out
private string GetTemplate(string templateName, templatePath)
{
if(!_templateContainer.Conatains(templateName))
{
var text = File.ReadAllText(templatePath);
_templateContainer[templateName] = text;
}
return _templateContainer[templateName];
}
private FileInfo Export(List<Model> modelList)
{
string timeStr = Datetime.Now;
string archiveFileName = "Main.zip";
string archivePath = Path.Combine(_reportFolderPath, archiveFileName);
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
foreach (var item in modelList)
{
var templateFilePath = Path.Combine(_reportTemplateFolder, TemplateName); //<--TemplateName seems like a local private
//these should come from where cant see where...
var template = GetTemplate( TemplateName, templateFilePath)
string modelResponse = ProcessModel(item,template,TemplateKey ); //<-- why is not passing in the template
//step 2;
//making this above done in parrell and then add aync, but before all that measure what is taking time
string pathname = MakeFileName(_reportFolderPath, reportFilelName, timeStr);
SaveToDisk(pathname, modelResponse);
string fileName = model.name + model.Id;
archive.CreateEntryFromFile(filePath, fileName + ".xml");
}
archive.Dispose();
}
return new FileInfo(archivePath);
}
private string MakeFileName(string path ,string filename, string tStamp)
{
string reportFilelName = fileName + "_" + timeStr + ".xml";
string filePath = Path.Combine(_reportFolderPath, reportFilelName);
return filePath;
}
private void SaveToDisk(string filePath, string content)
{
using (var file = new StreamWriter(filePath))
{
file.Write(processedTemplate);
}
}
public static string ProcessTemplate(object model, string template, templateKey)
{
var result = templateService.RunCompile(template, templateKey, null, model);
return result;
}
}
I want to upload the excel file of record 2500. This process takes time more than 5 minutes approximate. I want to optimize it to less than a minute maximum.
Find the best way of optimization of that code. I am using Dbgeography for location storing. File is uploaded and save the data properly. Everything is working find but I need optimization.
public ActionResult Upload(HttpPostedFileBase FileUpload)
{
if (FileUpload.ContentLength > 0)
{
string fileName = Path.GetFileName(FileUpload.FileName);
string ext = fileName.Substring(fileName.LastIndexOf('.'));
Random r = new Random();
int ran = r.Next(1, 13);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), DateTime.Now.Ticks + "_" + ran + ext);
try
{
FileUpload.SaveAs(path);
ProcessCSV(path);
ViewData["Feedback"] = "Upload Complete";
}
catch (Exception ex)
{
ViewData["Feedback"] = ex.Message;
}
}
return View("Upload", ViewData["Feedback"]);
}
Here is other method from where the file is uploaded and save it to the database..
private void ProcessCSV(string filename)
{
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
StreamReader sr = new StreamReader(filename);
string line = null;
string[] strArray;
int iteration = 0;
while ((line = sr.ReadLine()) != null)
{
if (iteration == 0)
{
iteration++;
continue; //Because Its Heading
}
strArray = r.Split(line);
StoreLocation store = new StoreLocation();
store.Name = strArray[0];
store.StoreName = strArray[1];
store.Street = strArray[2];
store.Street2 = strArray[3];
store.St_City = strArray[4];
store.St_St = strArray[5];
store.St_Zip = strArray[6];
store.St_Phone = strArray[7];
store.Office_Phone = strArray[8];
store.Fax = strArray[9];
store.Ownership = strArray[10];
store.website = strArray[11];
store.Retailer = check(strArray[12]);
store.WarehouseDistributor = check(strArray[13]);
store.OnlineRetailer = check(strArray[14]);
string temp_Add = store.Street + "," + store.St_City;
try
{
var point = new GoogleLocationService().GetLatLongFromAddress(temp_Add);
string points = string.Format("POINT({0} {1})", point.Latitude, point.Longitude);
store.Location = DbGeography.FromText(points);//lat_long
}
catch (Exception e)
{
continue;
}
db.StoreLocations.Add(store);
db.SaveChanges();
}
The obvious place to start would be your external call to the Geo Location service, which it looks like you are doing for each iteration of the loop. I don't know that service, but is there any way you can build up a list of addresses in memory, and then hit it once with multiple addresses, then go back and amend all the records you need to update?
The call to db.SaveChanges() which updates the database, this is happening for every line.
while (...)
{
...
db.StoreLocations.Add(store);
db.SaveChanges(); // Many database updates
}
Instead, just call it once at the end:
while (...)
{
...
db.StoreLocations.Add(store);
}
db.SaveChanges(); // One combined database update
This should speed up your code nicely.
I am trying to upload a file using devexpress save as function which works exact same as the standard asp.net uploader but i am getting the following error
Could not find a part of the path 'C:\Projects\fhs\fhs\Uploads\documents\VX00150\Barry Allen\Aperture - Signature Template.docx'.
UploadDirectory refers to a virutal directory setup in the web config which im getting via the property.
string UploadDirectory = WebConfigurationManager.AppSettings["uploadDirectory"].ToString();
Which contains the directory
<add key="uploadDirectory" value="~\Uploads\" />
But for the live of me I cannot see why the file is not saving to the server
protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
{
UploadControl.Enabled = false;
string id = Request.QueryString["Case"];
if (id != null)
{
CaseId = Guid.Parse(id);
OpenCase = _dal.GetCaseById(Guid.Parse(id));
}
string PersonId = Session["CurrentPersonalMainID"].ToString();
Personal = _dal.GetPersonalByPersonalId(new Guid(PersonId));
e.CallbackData = SavePostedFile(e.UploadedFile, OpenCase.CaseReference, Personal.firstName, Personal.lastName);
}
The below saved postedfile is called from above
public string SavePostedFile(UploadedFile uploadedFile,string IVACaseRef, string firstName ,string lastName)
{
try
{
if (!uploadedFile.IsValid)
return string.Empty;
string fileName = uploadedFile.FileName;
FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
string fullFileName = CombinePath(fileName);
string docsPath = UploadDirectory + #"documents\" + IVACaseRef + #"\" + firstName + " " +
lastName + #"\";
string resFileName =docsPath + fileInfo.Name;
bool exists = System.IO.Directory.Exists(resFileName);
if (!exists)
System.IO.Directory.CreateDirectory(docsPath);
uploadedFile.SaveAs(Server.MapPath(resFileName), true);
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(resFileName.ToString());
// we need to reget this as issue with postback and the fileuplaod
FormsIdentity _identity = (FormsIdentity)Context.User.Identity;
_identity = (FormsIdentity)Context.User.Identity;
return fileName;
}
catch (Exception ex)
{
string inner = string.Empty;
if (ex.InnerException != null)
{
inner = ex.InnerException.ToString();
}
// logger.Error("Error in GetNotificationById function aperturenetdal " + ex.ToString() + " " + inner);
return "";
I've noticed that a lot of file manipulation methods and classes differ in how they handle spaces, sometimes in ways that are not well documented. For example, I've seen situations where testing for the existence of a file with a space in the filename succeeds but opening it does not.
It's just a hunch, but it seems likely.
I Make Upload Image In Asp.Net And I Really Save The Image In The Data Base But When i Want To Make A Query To Select The Image It Return The Source Of The Image With No Image Please I Want Any One Know The Solution Please Help Me.`enter code here This Is The Controller Code:
public ActionResult UpLoadImage(HttpPostedFileBase file)
{
if (file != null)
{
UpLoadDBEntities context = new UpLoadDBEntities();
file = Request.Files[0];
string filename = file.FileName;
string contenttype = file.ContentType;
string full = filename + " " + contenttype;
//string path = System.IO.Path.Combine(
// Server.MapPath("~/images/") + file.FileName);
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
Image_table it = new Image_table();
it.Image_Path = filename;
context.Image_table.Add(it);
context.SaveChanges();
}
return View();
}
public JsonResult ShowImage()
{
UpLoadDBEntities context = new UpLoadDBEntities();
Image_table it = new Image_table();
var showimage = (from itbl in context.Image_table
where itbl.ID == 8
select new { itbl.Image_Path });
return Json(showimage , JsonRequestBehavior.AllowGet);
}
You are setting the path as
it.Image_Path = filename;
Yet it gets store on the server as
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
I hope you can see it needs to be it.Image_Path = "~/Images/" + filename;. Also, make sure folks can actually access the path through IIS.