Allow a user to add picture to web site - c#

I have an existing web site that allows the user (normally me) to upload pictures and then to display the image on the appropriate page. I am now trying to add this functionality to a new web site.
In visual studio I opened the new web site and did an ‘add existing item’ to copy the model/view/controller from the old web site. Made a few changes to remove unneeded functionality from the code and a few other minor things.
In both I store the image in a folder named /data/Images. When I execute the code for the new site (Lat34North) and add an image, the image gets added, and the everything appears to work (no errors).
Problem:
If I look at the folder (new solution) using “File Explorer”, the jpg appears, in this case, on my hard drive and in the correct folder.
If I try and access the folder (~/Data/Images) via Visual Studio, the jpg does not show up.
When I try and display the image from the web site, I just get that funny little icon you get when the image is not found.
Photo Controller
//
[Authorize]
public ActionResult PhotoCreate(string CallingState, string masterMarkerID, string markerTitle)
{
ViewBag.photoCallingState = CallingState;
ViewBag.photoMarkerID = masterMarkerID;
ViewBag.photomarkerTitle = markerTitle;
return View();
}
//
// POST: /Photo/Create
[AcceptVerbs(HttpVerbs.Post)]
[Authorize]
public ActionResult PhotoCreate(Photo photo, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
photo.PhotoLinkRecID = photo.savePhotoState + photo.saveMarkerID;
if (photo.PhotoSequence == 0)
{
var no_Photo = from s in db.Photo
where s.PhotoLinkRecID == photo.PhotoLinkRecID
select s;
int noPhoto = no_Photo.Count();
int Sequence = (noPhoto * 20);
photo.PhotoSequence = Sequence;
}
photo.PhotoDateCreated = DateTime.Now;
photo.PhotoCreatedBy = #User.Identity.Name;
if (photo.fileUpload != null && photo.fileUpload.ContentLength > 0)
{
// get the file extension
photo.PhotoLinkRecID = photo.savePhotoState + photo.saveMarkerID; // Create key to link photo to the approiate marker -- // unique record identifier
photo.PhotoState = photo.savePhotoState;
photo.PhotoMarkerID = photo.saveMarkerID;
var fileName = Path.GetFileName(photo.fileUpload.FileName);
var FileExtension = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
photo.PhotoFileType = FileExtension;
db.Photo.Add(photo); // add new photo record to the DB
db.SaveChanges();
photo.PhotoRecID = "Photo" + photo.PhotoID.ToString(); // unique record identifier
var saveFile = photo.savePhotoState + photo.PhotoRecID + "." + photo.PhotoFileType; // new file name
var path = Path.Combine(Server.MapPath("~/Data/Images"), saveFile); // save the file
HttpPostedFileBase hpf = photo.fileUpload as HttpPostedFileBase;
hpf.SaveAs(path);
Image image = Image.FromFile(path);
photo.PhotoHeight = image.Height;
photo.PhotoWidth = image.Width;
try
{
//get the date taken from the files metadata
PropertyItem pi = image.GetPropertyItem(0x9003);
string sdate = Encoding.UTF8.GetString(pi.Value).Replace("\0", String.Empty).Trim();
string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" ")));
string firsthalf = sdate.Substring(0, 10);
firsthalf = firsthalf.Replace(":", "/");
sdate = firsthalf + secondhalf;
photo.PhotoDateTaken = sdate;
}
catch { }
try
{
double? lat = ImageExtensions.GetLatitude(image);
double? lon = ImageExtensions.GetLongitude(image);
if (lat > 1)
{
photo.PhotoLatDirection = "N";
string latString = lat.ToString();
//photo.PhotoLat = latString.Substring(0, 10);
if (latString.Length < 10)
{
photo.PhotoLat = latString;
}
else
{
photo.PhotoLat = latString.Substring(0, 10);
}
//photo.PhotoLat = lat.ToString();
photo.PhotoLongDirection = "W";
string longString = lon.ToString();
if (longString.Length < 10)
{
photo.PhotoLong = longString;
}
else
{
photo.PhotoLong = longString.Substring(0, 10);
}
//photo.PhotoLong = lon.ToString();
}
}
catch { }
}
db.SaveChanges();
return RedirectToAction("PhotoEdit", new { id=photo.PhotoID });
}
return View(photo);
The old web site uses EntityFramework, Version=5.0.0.0
The new web site uses EntityFramework, Version=6.0.0.0
The other difference between the two are the packages I have installed. Could I be missing one?

Related

Is it possible to download a .txt file and manipulate said file in one endpoint using ASP.NET MVC controller?

My task is to download a .txt file, remove some of the data and save it as .json. Currently I use one interface to download a file as .txt file and another interface to read all lines of said file, make it into an object and remove what I don't need.
Currently what happens is, that I have to go to download endpoint to get my .txt then to edit endpoint to parse and save as .json.
This is the filter method:
public void FilterOutInvalidRates(string path)
{
try
{
var targetLocation = #"TargetLocation/";
var name = File.ReadAllLines(path).First();
var fileName = name.Substring(0,3);
var lines = File.ReadAllLines(path).Skip(2);
var model = lines.Select(p => new Rates
{
a = p.Split("|")[0],
b = p.Split("|")[1],
c = p.Split("|")[2],
d = p.Split("|")[3],
e = p.Split("|")[4],
});
List<Rates> rates = model.Where(model => IsTheCountryValid(model.Country)).ToList();
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(rates.ToArray(), Formatting.Indented);
System.IO.File.WriteAllText(targetLocation + fileName + ".json", jsonString);
System.IO.File.Delete(path);
}
catch (FileNotFoundException)
{
Console.WriteLine(#"Unable to read file:" + path.ToString());
}
}
And this is the download service:
public async void DownloadRatesTxtFile(string uri, string outputPath, int number)
{
var policy = BuildRetryPolicy();
var path = await policy.ExecuteAsync(() => uri
.DownloadFileAsync(outputPath, #"CurrencyRate" + number + ".txt"));
}
This is the controller implementation - I know it's not ideal, if I could do it all in one endpoint or a different architecture I could get rid of a ton of code. The issue is, that before the endpoint returns OK I am not able to manipulate the files in any way or read them.
[HttpGet("download")]
public async Task<IActionResult> Download()
{
var fileCounter = 1;
var outputPath2 = AppDomain.CurrentDomain.BaseDirectory + #"Data/";
var outputPath = #"TargetLocation/";
DateTime begindate = Convert.ToDateTime("01/07/2022");
DateTime enddate = Convert.ToDateTime("5/07/2022");
while (begindate < enddate)
{
if (begindate.DayOfWeek == DayOfWeek.Saturday)
{
begindate = begindate.AddDays(2);
}
_exchangeRateConnector.DownloadRatesTxtFile(_exchangeRateConnector.GenerateRatesUrl(begindate), outputPath2, fileCounter);
begindate = begindate.AddDays(1);
fileCounter++;
}
return Ok();
}
[HttpGet("edit")]
public async Task<IActionResult> Edit()
{
var outputPath2 = AppDomain.CurrentDomain.BaseDirectory + #"Data/";
var outputPath = #"TargetLocation/";
var fileCount = (from file in Directory.EnumerateFiles(outputPath2, "*.txt", SearchOption.TopDirectoryOnly)
select file).Count();
for (int i = 1; i <= fileCount; i++)
{
_exchangeRateRepository.FilterOutInvalidRates(outputPath2 + "CurrencyRate" + i + ".txt");
}
return Ok();
}
Thank you so much for any sort of advice.

How do i read response body of plain text from an api and covert or serialize into an object in .net core 2.0

Am trying to read a a returned tab plaint text from a wsdl service built with an xpath. How can i deserialize it into and object or convert it into an object in .net core 2.0. Am using the .net core inbuilt wcf service reference to talk to the wsdl service.
this is my code snippet from the controller level
[HttpPost]
public async Task<IActionResult> Index(DateModelVm date)
{
try
{
if (ModelState.IsValid)
{
if(date.PfaId == 21)
{
var depositVm = _DepositeModelPass.MapDepositeModelVmToModelVm(date, ICredentials._currentStanbicAccountNumber, ICredentials._currentStanbicCustomerId, ICredentials._currentzenithpasssowrd, ICredentials._currentzenithuserName);
var Mappedresult = _DepositeModelPass.MapDepositeModelVmToModel(depositVm);
//fetch deposit from Servce
var ReturnedResult = await _depositService.getDepositsAsync(Mappedresult);
if (!string.IsNullOrEmpty(ReturnedResult.Body.result))
{
// create folder path
string webRootPath = _hostingEnvironment.WebRootPath;
// create directory
var directoryname = ProcessFile.CreateDirectory(webRootPath);
//create write into text file
await ProcessFile.CreateAndWriteToTextFile(directoryname, ReturnedResult.Body.result);
List<DepositModel> processedDeposit = CsvMapper.DepositModelParser(directoryname);
}
this is the code for writing to text file
public static async Task CreateAndWriteToTextFile(string myCurrentDirectoryName, string body)
{
//check if file exist in the folder created
try
{
if (!System.IO.File.Exists(myCurrentDirectoryName))
{
await System.IO.File.WriteAllTextAsync(myCurrentDirectoryName + "//" + stanbicFile, body);
}
}
catch (Exception)
{
throw;
}
}
fetching from text file using csvhelper library to convert to an object
public static List<DepositModel> DepositModelParser(string directoryName)
{
string path = directoryName + "\\" + "xxxx.txt";
List<DepositModel> depositModels = new List<DepositModel>();
// read from file
using (StreamReader str = System.IO.File.OpenText(path))
using (CsvReader csvReader = new CsvReader(str))
{
IEnumerable<DepositModel> deposits = csvReader.GetRecords<DepositModel>();
csvReader.Configuration.Delimiter = "\t";
csvReader.Configuration.TrimOptions = TrimOptions.Trim;
csvReader.Configuration.RegisterClassMap<DepositeModelMap>();
csvReader.Configuration.MissingFieldFound = null;
foreach (var item in deposits)
{
var depo = new DepositModel()
{
AccountNumber = item.AccountNumber,
Amount = item.Amount,
Branch = item.Branch,
City = item.City,
Country = item.Country,
Currency = item.Currency,
DepositSlipNumber = item.DepositSlipNumber,
Description = item.Description,
FirstName = item.FirstName,
FundId = item.FundId,
LastName = item.LastName,
OtherName = item.OtherName,
PaymentMethod = item.PaymentMethod,
PFACode = item.PFACode,
PFAName = item.PFAName,
ReversalNumber = item.ReversalNumber,
RSAPin = item.RSAPin,
TransactionDate = item.TransactionDate,
TransactionNumber = item.TransactionNumber,
ValueDate = item.ValueDate
};
depositModels.Add(depo);
}
}
}
this is the the plain text result gotten from the wsdl after writing to text file
Transaction No. Transaction Date Value Date Description Amount Currency Branch City Country Reversal No. Payment Method Deposit Slip No RSA PIN First Name Last Name Other Name PFA Code PFA Name Fund ID Account No
68663XXX 2019-09-10 11:35:24 2019-09-10 XXXX110003XXXX/TEXXX/NYXXX/028/DS 76026 CD K INNOVATIVE 500.00 NGN Eagle Abuja NGR 0 76026 XXX110003XXXX TERKIMBI NYIEYEM 028 TRUSTXXX_XXXX 16 10163XXXX
d639164fe718df68c18aacbXXX​
returned result from service snap shot
Is there a way i can read this file directly and convert to an object without using csv helper library and without writing to textfile when gotten from the wsdl service...

Get image download url from firebase storage Xamarin

Im trying to get the image url from a photo I uploaded to firebase storage so I can store the reference to the image in another table which will allow me to be able to display the image elsewhere throughout the app.
I currently have
private void UploadPhoto()
{
if (filePAth != null)
{
progressDialog = new ProgressDialog(this);
progressDialog.SetTitle("Uploading...");
progressDialog.Window.SetType(Android.Views.WindowManagerTypes.SystemAlert);
progressDialog.Show();
var images = storageRef.Child("images/" + Guid.NewGuid().ToString());
images.PutFile(filePAth)
.AddOnProgressListener(this)
.AddOnSuccessListener(this)
.AddOnFailureListener(this);
}
}
public async void OnSuccess(Java.Lang.Object result)
{
try
{
var newImageDetails = storageRef.Child("images" + "/" + filePAth);
Photo photos = new Photo();
photos.categoryName = spinner.SelectedItem.ToString();
photos.photoId = newImageDetails.Name;
photos.ImageUrl = storageRef.DownloadUrl.ToString();
photos.tagName = addTag.Text;
if (user != null)
{
var uid = user.Uid;
//set the users id to the category
photos.uid = uid;
}
var firebase = new FirebaseClient(FirebaseURL);
var item = await firebase.Child("photos").PostAsync(photos);
}
}
The storageref.DownloadUrl does not give me the correct url
This is what I am looking for
I think that the trouble is Guid.NewGuid().
It generates a new code each time you insert a new image and your storageref points to it (image/GUID code).
In your OnSuccess you get image info from "images/" + filePath, that's different from upload path.
Why you use a new GUID? You can't determinate it, it will create a different path each time.
Consider then that your download url contains the media token too, it's not simply the clean path as you expect
I got a solution in debugging mode
i saw the downloadurl's properties and found the Scheme and SchemeSpecificPart
Scheme = "https"
SchemeSpecificPart = "//firebasestorage.googleapis.com/v0/b/maplog-e4ba5.appspot.com/o/-L0AMbihF23YKxsL1uss?alt=media&token=5c7ccef1-c857-4982-a288-fded2f0ff1aa"
so here is my code:
void IOnSuccessListener.OnSuccess(Java.Lang.Object result)
{
var snapShot = (UploadTask.TaskSnapshot)result;
string imgUrl = snapShot.DownloadUrl.Scheme
+ ":"
+ snapShot.DownloadUrl.SchemeSpecificPart;
}
and it works! i was looking for the solution :(( but i finally found it myself XD

Saving image path on db and images into folder asp .net mvc

I have issue in uploading images path into database and moving imagesg into folder, here is code:
public ActionResult UploadImages(
HttpPostedFileBase formFilled,
HttpPostedFileBase sixPics,
HttpPostedFileBase buyerCNIC,
HttpPostedFileBase sellerCNIC
)
{
if (Session["user"] == null)
{
return RedirectToAction("Login", "User");
}
CustomerDocumentImages dbCustomerDocs = new CustomerDocumentImages();
string recieverName = Request.Form["RecieverName"];
var allowedExtensions = new[] {
".Jpg", ".png", ".jpg", "jpeg"
};
dbCustomerDocs.FormFilledPhysicalPath = formFilled.ToString();
var _formFilled = Path.GetFileName(formFilled.FileName); //getting only file name(a.jpg)
var ext = Path.GetExtension(formFilled.FileName);
if (allowedExtensions.Contains(ext))
{
string name = Path.GetFileNameWithoutExtension(_formFilled); //getting file name without extension
string formImage = name + "_" + DateTime.Now + ext; //appending the name with id
// store the file inside ~/project folder(Img)
var path = Path.Combine(Server.MapPath("~/Images"), formImage);
dbCustomerDocs.FormFilledPhysicalPath = path;
dbCustomerDocs.FormFilled = _formFilled;
dbCustomerDocs.RecieverName = recieverName;
try
{
var currentAllotmentId = Convert.ToInt32(Request.Form["AllotmentId"]);
var dbAllotment = db.Allotments.SingleOrDefault(i => i.AllotmentId == currentAllotmentId);
dbCustomerDocs.AllotmentId = dbAllotment.AllotmentId;
dbAllotment.IsCustomerDocsUploaded = true;
}
catch (Exception)
{
ModelState.AddModelError("", "Please select valid allotment");
}
db.CustomerDocumentImagess.Add(dbCustomerDocs);
db.SaveChanges();
formFilled.SaveAs("~Images"+path);
return RedirectToAction("Index");
}
else
{
ViewBag.message = "Please choose only Image file";
}
return View();
}
I have also used server.mappath but it woking fine on localhost but giving error on windows live server( on save as method ) , in case of combine.mappath works fine but not moving image into folder. please guide me, thanks in advance.

How to redirect to specific error page in MVC FileDownloadResult

I enable my users to download files, some times the files are archived or do not exist at the location, I currently display a 404, I created a specific error page for this specific scenario but I am unable to display it because I have to return something in the FileDownload Result and I am unable to do a response redirect. Also I tried to return content with javascript but that is also not compatible with FileDownloadResult type. How do I route the user to the intended error page which I have will render from its own controller/action?
public DownloadFileResult Download(string file)
{
try
{
string loadLististFileName = file;
// get the displayed filename, extract the file name
string fileNamePath = loadLististFileName;
string fileName = Path.GetFileName(fileNamePath);
string dirName = Path.GetDirectoryName(fileNamePath);
string dirPath = dirName.Replace("\\", ",");
string[] dir = dirPath.Split(',');
int dirlength = dir.Length;
string year = dir[dirlength - 3];
string month = dir[dirlength - 2];
string day = dir[dirlength - 1];
var fileData = IOHelper.GetFileData(fileName, dirName);
fileName = IOHelper.GetPrimaryFileName(file);
return new DownloadFileResult(fileName, fileData);
}
catch (FileNotFoundException)
{
//return Content("<script language='javascript' type='text/javascript'>alert('Image not found!');</script>");
Response.Redirect("Exception/FileIndex");
}
}
try to return ActionResult instead, something like this:
public ActionResult DownLoadFile(int Id)
{
var model = new PreviewFileAttachmentViewModel(Id, _attachFileProvider);
if (model.FileExist)
return File(model.AbsFileNamePath, model.ContentType, model.FileName);
else
return RedirectToAction("FileNotFound");
}

Categories