public async Task <string> SavePlaceAsync(PlaceSave resource) { var used = 0; var user = await _unitOfWork.Users.FindByIdAsync(resource.OwnerId); if (user == null) { return("Owner not found"); } var categories = _unitOfWork.Category.Find(e => e.Name.ToLower() == resource.Category).ToList(); var newCategory = categories.Count == 0 ? Category.Create(resource.Category) : categories.First(); var location = Place.Create(user, resource.Name, resource.Description, newCategory, Convert.ToSingle(resource.TicketPrice)); var guids = GeneratePaths(resource.PhotosContentStreams.Count); foreach (var stream in resource.PhotosContentStreams.Select(entry => new MemoryStream(entry.Value))) { FileService.SaveStreamAsFile(Directory.GetCurrentDirectory(), stream, guids[used] + ".png"); location.Photos.Add(Photo.Create(Directory.GetCurrentDirectory() + guids[used] + ".png")); used++; } _unitOfWork.Locations.AddAsync(location); return("Success"); }
public (Photo, ImportError) ReadPhoto(string filePath, bool readMetaData, bool readDateTimeFromFile) { ImportError readError = null; Photo photo = null; try { photo = Photo.Create(filePath); if (readMetaData) { photo.ImageMetaData = ReadPhotoMetaData(filePath); } if (readDateTimeFromFile) { photo.ReadDateTimeFromFile(); } } catch (Exception exception) { readError = new ImportError(filePath, ImportErrorType.Read, exception); } return(photo, readError); }
private void SeedData(ModelBuilder modelBuilder) { // NOTE: We use ".HasData" here, this means this data will ONLY be seeded IF the table // is completley empty. const string usernameAdmin = "admin"; var passwordAdmin = SecurePasswordHasherHelperService.Hash("admin"); const string emailAdmin = "*****@*****.**"; const string lastNameAdmin = "Gigica"; const string firstNameAdmin = "Comanel"; var allowedRolesAdmin = new[] { "admin" }; var birthDate = DateTime.Now; var defaultProfileImageAdmin = Photo.Create("/StaticFiles/Images/ProfileImages/DefaultProfileImage.png"); var userAdmin = User.Create(usernameAdmin, passwordAdmin, emailAdmin, lastNameAdmin, firstNameAdmin, birthDate, allowedRolesAdmin); //userAdmin.SetProfileImage(defaultProfileImageAdmin); const string usernameModerator = "moderator"; var passwordModerator = SecurePasswordHasherHelperService.Hash("moderator"); const string emailModerator = "*****@*****.**"; const string lastNameModerator = "Jhony"; const string firstNameModerator = "Comanel"; var allowedRolesModerator = new[] { "moderator" }; var defaultProfileImageModerator = Photo.Create("/StaticFiles/Images/ProfileImages/DefaultProfileImage.png"); var userModerator = User.Create(usernameModerator, passwordModerator, emailModerator, lastNameModerator, firstNameModerator, birthDate, allowedRolesModerator); //userModerator.SetProfileImage(defaultProfileImageModerator); const string usernameNormalUser = "******"; var passwordNormalUser = SecurePasswordHasherHelperService.Hash("user"); const string emailNormalUser = "******"; const string lastNameNormalUser = "******"; const string firstNameNormalUser = "******"; var allowedRolesNormalUser = new[] { "user" }; var defaultProfileImageNormalUser = Photo.Create("/StaticFiles/Images/ProfileImages/DefaultProfileImage.png"); var userNormalUser = User.Create(usernameNormalUser, passwordNormalUser, emailNormalUser, lastNameNormalUser, firstNameNormalUser, birthDate, allowedRolesNormalUser); //userNormalUser.SetProfileImage(defaultProfileImageNormalUser); modelBuilder.Entity <Photo>() .HasData( defaultProfileImageAdmin, defaultProfileImageModerator, defaultProfileImageNormalUser ); modelBuilder.Entity <User>() .HasData( userAdmin, userModerator, userNormalUser ); }
public Response <PlaceSave> SaveAsync(PlaceSave resource) { var user = _unitOfWork.Users.Find(e => e.UserId == resource.OwnerId).ToList(); var category = _unitOfWork.Category.Find(e => e.Name == resource.Category).ToList(); if (user.Count != 1) { return(new Response <PlaceSave>("User not found")); } Category newCategory; if (category.Count != 1) { newCategory = Category.Create(resource.Category); _unitOfWork.Category.Add(newCategory); } else { newCategory = category.First(); } var place = Place.Create(user.First(), resource.Name, resource.Description, newCategory, Convert.ToSingle(resource.TicketPrice), resource.Address, resource.Lat, resource.Ltn); var used = 0; var guids = GeneratePaths(resource.PhotosContentStreams.Count); foreach (var stream in resource.PhotosContentStreams.Select(entry => new MemoryStream(entry.Value))) { FileService.SaveStreamAsFile(Path.Combine(Directory.GetCurrentDirectory(), PathFolder), stream, guids[used] + ".png"); // place.Photos.Add(Photo.Create(Directory.GetCurrentDirectory() + guids[used] + ".png")); var photo = Photo.Create(Path.Combine(PathFolder, guids[used] + ".png")); place.Photos.Add(photo); _unitOfWork.Photo.Add(photo); used++; } _unitOfWork.Locations.Add(place); _unitOfWork.Complete(); return(new Response <PlaceSave>(resource)); }
public Response <AttractionsResource> SaveAttraction(Guid id, SaveAttractionResource resource) { var name = $"{GeneratePath()}.png"; FileService.SaveStreamAsFile(Path.Combine(Directory.GetCurrentDirectory(), PathFolder), new MemoryStream(resource.Photo), name); var attraction = Attraction.Create(resource.Name, resource.Description, Photo.Create(Path.Combine(PathFolder, name))); var place = _unitOfWork.Locations.GetById(id); if (place == null) { return(new Response <AttractionsResource>("Place is not found")); } place.Attractions.Add(attraction); _unitOfWork.Locations.Update(place); _unitOfWork.Attraction.Add(attraction); _unitOfWork.Complete(); return(new Response <AttractionsResource>(AttractionsResource.CreateResource(attraction))); }
public void Update(PlaceSave value, Guid id) { var place = _unitOfWork.Locations.GetById(id); place.Update(value); var used = 0; var guids = GeneratePaths(value.PhotosContentStreams.Count); foreach (var stream in value.PhotosContentStreams.Select(entry => new MemoryStream(entry.Value))) { FileService.SaveStreamAsFile(Path.Combine(Directory.GetCurrentDirectory(), PathFolder), stream, guids[used] + ".png"); var photo = Photo.Create(Path.Combine(PathFolder, guids[used] + ".png")); place.Photos.Add(photo); _unitOfWork.Photo.Add(photo); used++; } _unitOfWork.Locations.Update(place); _unitOfWork.Complete(); }
public async Task <UserResponse> SaveAsync(User user) { var existingUser = await _unitOfWork.Users.FindByUsernameAsync(user.Username); if (existingUser != null) { return(new UserResponse("Username is already used.")); } try { user.SetProfileImage(Photo.Create("/StaticFiles/Images/ProfileImages/DefaultProfileImage.png")); await _unitOfWork.Users.AddAsync(user); await _unitOfWork.CompleteAsync(); return(new UserResponse(user)); } catch (Exception ex) { return(new UserResponse($"An error occurred when saving the user: {ex.Message}")); } }
public static AjaxCallResult CreatePhoto(string sourceUrl, string description, string personName, string photoCredit) { AuthenticationData authData = GetAuthenticationDataAndCulture(); sourceUrl = sourceUrl.Replace("https://", "http://"); // because of damn broken Mono cert store string guidString = Guid.NewGuid().ToString("N"); string fileNameBase = guidString + "-" + authData.CurrentUser.Identity.ToString("X8").ToLowerInvariant() + "-" + authData.CurrentOrganization.Identity.ToString("X4").ToLowerInvariant(); DateTime utcNow = DateTime.UtcNow; string fileFolder = utcNow.Year.ToString("0000") + Path.DirectorySeparatorChar + utcNow.Month.ToString("00") + Path.DirectorySeparatorChar + utcNow.Day.ToString("00"); string storageRoot = "/var/lib/swarmops/upload/"; if (!Directory.Exists("/var/lib/swarmops/upload/" + fileFolder)) { Directory.CreateDirectory(storageRoot + fileFolder); } int fileCounter = 0; string fileName = string.Empty; do { fileCounter++; fileName = fileNameBase + "-" + fileCounter.ToString("X2").ToLowerInvariant(); } while (File.Exists(storageRoot + fileFolder + Path.DirectorySeparatorChar + fileName) && fileCounter < 512); if (fileCounter >= 512) { return(new AjaxCallResult { Success = false, DisplayMessage = "Unable to determine filename" }); } long fileLength = 0; using (WebClient client = new WebClient()) { try { byte[] newImage = client.DownloadData(sourceUrl); fileLength = newImage.LongLength; File.WriteAllBytes(storageRoot + fileFolder + Path.DirectorySeparatorChar + fileName, newImage); } catch (Exception e) { return(new AjaxCallResult { Success = false, DisplayMessage = "Exception thrown:<br/><br/>" + e.ToString() }); } } try { Document document = Document.Create(fileFolder + Path.DirectorySeparatorChar + fileName, sourceUrl, fileLength, guidString, null, authData.CurrentUser); Photo photo = Photo.Create(document, description, personName, photoCredit, sourceUrl); return(new AjaxCallResult { Success = true, DisplayMessage = photo.Identity.ToString() }); } catch (Exception e) { return(new AjaxCallResult { Success = false, DisplayMessage = "Exception thrown:<br/><br/>" + e.ToString() }); } }
public ActionResult UploadPhoto(int id, HttpPostedFileBase file) { var path = string.Format ("~/Photos/{0:000000}", id); var filename = string.Format ("{0}/{1}.jpg", path, Guid.NewGuid ()); if (file == null || !file.ContentType.StartsWith ("image")) { Product item; ModelState.AddModelError ("", "Archivo inválido, no es una imagen."); using (var session = new SessionScope()) { item = Product.TryFind (id); item.Photos.ToList (); } return View ("Details", item); } Photo photo = new Photo { Product = Product.TryFind (id), Path = filename }; SavePhotoAsJpeg (photo.Path, file); photo.Create (); return RedirectToAction ("Details", new { id = id }); }