public async Task <PhotoModel> GetPhotoInfoById(string photoId) { try { Flickr flickrManager = _flickrManager.GetInstance(); string getInfoUrl = string.Format(Constants.GetInfoUrlBase, flickrManager.ApiKey, photoId); HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(getInfoUrl); timeLineRequest.Method = "Get"; WebResponse timeLineResponse = await timeLineRequest.GetResponseAsync(); var timeLineJson = string.Empty; PhotoModel photo = new PhotoModel(); using (timeLineResponse) { using (var reader = new StreamReader(timeLineResponse.GetResponseStream())) { timeLineJson = await reader.ReadToEndAsync(); XmlSerializer serializer = new XmlSerializer(typeof(GreenFluxApi.Domain.Models.PhotoModel)); MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(timeLineJson)); photo = (PhotoModel)serializer.Deserialize(memStream); } } return(photo); } catch (Exception ex) { throw new Exception(string.Format(Constants.ErrorMessage, ex.Message)); } }
/// <summary> /// Saves an entity to Azure table storage /// </summary> /// <param name="tableName">The name of the table to save to</param> /// <param name="model">The PhotoModel object to be saved</param> /// <returns>System.String - the HTTP status code of the save operation</returns> public async Task <string> SaveToTableStorageAsync( string tableName, PhotoModel model) { //We use the DateAdded field for cross-partition queries DateTime now = System.DateTime.Now; model.DateAdded = now; PhotoEntity entity = new PhotoEntity(model); //These properties are used in a full table scan to populate //all photos for all users. Needed as some way to get the //items for a single day for all users. entity.DayAdded = now.Day; entity.MonthAdded = now.Month; entity.YearAdded = now.Year; var client = _account.CreateCloudTableClient(); var table = client.GetTableReference(tableName); var operation = TableOperation.InsertOrReplace(entity); var result = await table.ExecuteAsync(operation); //TODO: Do we need to check the HTTP status code here? return(result.HttpStatusCode.ToString()); }
public List <Comentarios> getComentarioPhoto(PhotoModel request) { List <Comentarios> ComentarioInfo = new List <Comentarios>(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //Sending request to find web api REST service resource GetAllEmployees using HttpClient var Res = client.GetAsync("https://jsonplaceholder.typicode.com/comments").Result; //Checking the response is successful or not which is sent using HttpClient if (Res.IsSuccessStatusCode) { //Storing the response details recieved from web api var Response = Res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the Employee list ComentarioInfo = JsonConvert.DeserializeObject <List <Comentarios> >(Response); } //returning the employee list to view return(ComentarioInfo.Where(x => x.id == request.id).ToList()); } }
public ResponseItem Put(PhotoModel value) { var _Entity = DB.yy_Photo.Find(value.Photo.ID); if (_Entity != null) { _Entity.IsShow = value.Photo.IsShow; _Entity.ShowIndex = value.Photo.ShowIndex; _Entity.Title = value.Photo.Title; _Entity.KeyWords = value.Photo.KeyWords; _Entity.Summary = value.Photo.Summary; _Entity.TypeIDs = value.Photo.TypeIDs; _Entity.Recommend = value.Photo.Recommend; _Entity.TargetPlatforms = value.Photo.TargetPlatforms; _Entity.CanReply = value.Photo.CanReply; _Entity.CreateDate = value.Photo.CreateDate; DB.SaveChanges(); DB.Database.ExecuteSqlCommand("DELETE FROM yy_Photo_Item WHERE PhotoID = " + value.Photo.ID); foreach (var v in value.Items) { v.PhotoID = value.Photo.ID; } DB.yy_Photo_Item.AddRange(value.Items); DB.SaveChanges(); return(new ResponseItem(0, "")); } return(new ResponseItem(1, "不存在的相册。")); }
public ActionResult Edit(int?id) { if (id.HasValue) { Photo photo = _photoManager.Get(id.Value, true); var userId = Request.IsAuthenticated ? CurrentUser.Id : 0; var rating = _ratingManager.Get(new Rating { PhotoId = id.Value, UserId = userId }); var photoModel = new PhotoModel { PhotoId = photo.PhotoId, UserId = photo.UserId, Description = photo.Description, Title = photo.Title, FileName = photo.FileName, Tags = _tagManager.Get(photo.PhotoId), Width = "" + photo.Width + "px", Height = "" + photo.Height + "px", Rating = rating }; photoModel.TagString = string.Join(", ", photoModel.Tags); return(PartialView("_Edit", photoModel)); } return(View("Error", new ErrorModel { ErrorMessage = "No photo Id was Provided" })); }
private void FillPhotosFromPath(string path) { var di = new DirectoryInfo(path); var files = di.GetFiles("*.*", SearchOption.AllDirectories); var list = new List <PhotoModel>(files.Length); foreach (var f in files) { //if (list.Count > 100) // break; var ext = f.Extension.ToLowerInvariant(); switch (ext) { case ".png": case ".jpg": var item = new PhotoModel { LocalPath = f.FullName }; list.Add(item); break; } } Application.Current.Dispatcher.Invoke(() => { var col = new ObservableCollection <PhotoModel>(list); Photos = col; }); }
private void FillPhotosFromPath(DirectoryInfo di, HashSet <PhotoModel> list, int prefixLen) { Console.Write($"Scanning {di.FullName.Substring(prefixLen)}... "); var files = di.GetFiles(); var added = 0; foreach (var f in files) { var ext = f.Extension.ToLowerInvariant().Substring(1); //remove . if (FileTypes.Any(t => t.Equals(ext, StringComparison.InvariantCultureIgnoreCase))) { var item = new PhotoModel { LocalPath = f.FullName }; if (!list.Contains(item)) { list.Add(item); added++; } } } Console.WriteLine($"{added} files queued"); var dirs = di.GetDirectories(); foreach (var dir in dirs) { FillPhotosFromPath(dir, list, prefixLen); } }
public static void AddPhoto(PhotoModel model) { using (var context = DatabaseContext.Create()) { context.AddPhoto(model); } }
public PhotoModel detail(int photo_id, int user_id) { PhotoModel mod = new PhotoModel(); string query = "select * from public.rm_cart_item where useralbumphoto_id=@useralbumphoto_id and user_id=@user_id"; con.Open(); cmd = new NpgsqlCommand(query, con); cmd.Parameters.AddWithValue("@useralbumphoto_id", photo_id); cmd.Parameters.AddWithValue("@user_id", user_id); try { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { mod.cart_itemquantity = Convert.ToInt32(dr["cart_itemquantity"]); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { con.Close(); } return(mod); }
public List <PhotoModel> cartItem(string user_email) { List <PhotoModel> photo = new List <PhotoModel>(); string query = "SELECT rm_useralbumphoto.useralbumphoto_id,rm_useralbumphoto.useralbumphoto_photo,rm_useralbumphoto.useralbumphoto_name,rm_useralbumphoto.useralbumphoto_prise,rm_cart_item.cart_itemquantity FROM public.rm_useralbumphoto FULL OUTER JOIN public.rm_cart_item ON rm_useralbumphoto.useralbumphoto_id=rm_cart_item.useralbumphoto_id WHERE user_id=(select user_id from public.rm_userdetail where user_email=@user_email)"; con.Open(); cmd = new NpgsqlCommand(query, con); cmd.Parameters.AddWithValue("@user_email", user_email); try { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { PhotoModel mod = new PhotoModel(); mod.useralbumphoto_id = Convert.ToInt32(dr["useralbumphoto_id"]); mod.useralbumphoto_photo = dr["useralbumphoto_photo"].ToString(); mod.useralbumphoto_name = dr["useralbumphoto_name"].ToString(); mod.useralbumphoto_prise = Convert.ToInt32(dr["useralbumphoto_prise"]); mod.cart_itemquantity = Convert.ToInt32(dr["cart_itemquantity"]); photo.Add(mod); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { con.Close(); } return(photo); }
public ActionResult Files(IEnumerable <HttpPostedFileBase> files) { // TODO: foreach (var file in files) { using (var stream = file.InputStream) { using (var destination = new MemoryStream()) { stream.CopyTo(destination); var bytes = destination.ToArray(); var model = new PhotoModel { Name = file.FileName, Data = Convert.ToBase64String(bytes), Id = Guid.NewGuid() }; _adminData.SavePhoto(model); } } } return(Json("All files have been successfully stored.")); }
public int totalPrise(int user_id, int photo_id) { PhotoModel mod = new PhotoModel(); string query = "select sum(rm_useralbumphoto.useralbumphoto_prise*rm_cart_item.cart_itemquantity) as total_prise from rm_useralbumphoto left outer join rm_cart_item on rm_useralbumphoto.useralbumphoto_id=rm_cart_item.useralbumphoto_id where user_id=@user_id"; con.Open(); cmd = new NpgsqlCommand(query, con); cmd.Parameters.AddWithValue("@user_id", user_id); cmd.Parameters.AddWithValue("@useralbumphoto_id", photo_id); try { NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { mod.useralbumphoto_prise = Convert.ToInt32(dr["total_prise"]); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { con.Close(); } return(mod.useralbumphoto_prise); }
public async Task <IEnumerable <PhotoModel> > InsertPhotoList(IEnumerable <PhotoModel> photos) { var user = await userRepository.GetUser(); List <PhotoModel> photoList = new List <PhotoModel>(); foreach (var photo in photos) { var photoVar = new PhotoModel { RepoId = photo.RepoId, SyncId = photo.SyncId, PlaceId = photo.PlaceId, ScheduleId = photo.ScheduleId, Note = photo.Note, PictureUrl = photo.PictureUrl, AddedDate = DateTime.Now, TenantId = user.TenantId, CreatorUserId = requestIdentityProvider.UserId, LastModifierUserId = requestIdentityProvider.UserId }; photoList.Add(photoVar); } var newPhotoList = photoRepository.InsertPhotoList(mapper.Map <IEnumerable <Photo> >(photoList)); await photoRepository.SaveChangesAsync(); return(photoList); }
async void ArtUploader_Clicked(object sender, EventArgs args) { ArtUploader.IsEnabled = false; ArtUploader.Text = "Uploading..."; PhotoModel model = new PhotoModel { PhotoRowguid = Guid.NewGuid() }; await _restService.PostAuthUserAsync(); var account = CloudStorageAccount.Parse(_restService.User.BlobAzureKey); var client = account.CreateCloudBlobClient(); var container = client.GetContainerReference("photomapcontainer"); await container.CreateIfNotExistsAsync(); var blockBlob = container.GetBlockBlobReference($"{model.PhotoRowguid}.png"); await blockBlob.UploadFromStreamAsync(_photoFile.GetStream()); model.Latitude = _location.Latitude.ToString(); model.Title = NameText.Text; model.Description = DescText.Text; model.Longitude = _location.Longitude.ToString(); model.PhotoPath = blockBlob.Uri.OriginalString; model.UserRowguid = _restService.User.UserROWGUID; await _restService.PostPhotoAsync(model); ArtUploader.Text = "Done!"; await Navigation.PopAsync(true); }
public async Task <PhotoModel> CreatePhoto(UserId userId, string userName, string fileName, string text) { logWriter.LogInformation($"{nameof(CreatePhoto)}({nameof(userId)} = '{userId}', {nameof(fileName)} = '{fileName}')"); try { Guid photoId = Guid.NewGuid(); DateTime utcNow = DateTime.UtcNow; var photo = new PhotoModel { CreatedTime = utcNow, Filename = fileName, UserId = userId, UserName = userName, PhotoId = photoId, ObjectKey = $"{userId}/{photoId}", State = PhotoState.Created, Sizes = new Size[] { }, RawText = text, Hashtags = GetHashtags(photoId, text, utcNow) }; photo.UploadUri = await remoteFileRepository.GetUploadUri($"{photo.ObjectKey}{Path.GetExtension(fileName)}"); return(await dataRepository.CreatePhoto(photo)); } catch (Exception ex) { logWriter.LogError(ex, $"Error in {nameof(CreatePhoto)}({nameof(userId)} = '{userId}', {nameof(fileName)} = '{fileName}')"); throw new Exception("Error when creating photo.", ex); } }
public void Photo_Update_Valid_Data_Good_Should_Pass() { // Arrange var myData = new PhotoModel { Device = "Device" }; var myDataNew = new PhotoModel { Device = "Device", Status = (int)PhotoStatusEnum.Error, Note = "Photo is too blurry", Score = 20, ID = myData.ID }; // Act myData.Update(myDataNew); myData.Date = myData.Date.AddSeconds(-5); // Assert // Add an Assert for each attribute that should change Assert.AreEqual(1, myData.Status); Assert.AreEqual("Photo is too blurry", myData.Note); Assert.AreEqual(20, myData.Score); Assert.AreNotEqual(myData.Date, myDataNew.Date); // Add an Assert for each attribute that thould Not change Assert.AreEqual("Device", myData.Device); }
internal static async Task ReplicateBlobAsync(PhotoModel model, TextWriter log) { //The source connection string needs to be in AppSettings using the //storage account name. var sourceConnectionString = ConfigurationManager.AppSettings[model.StorageAccountName]; //The target connection string is the local region's storage account var targetConnectionString = SettingsHelper.LocalStorageConnectionString; //Copy from the upload container to the photos container, // potentially across storage accounts await log.WriteLineAsync("sourceConnectionString: " + sourceConnectionString); await log.WriteLineAsync("targetConnectionString: " + targetConnectionString); var storageRepo = new StorageRepository(sourceConnectionString); var container = await storageRepo.ReplicateBlobAsync( targetConnectionString, StorageConfig.UserUploadBlobContainerName, StorageConfig.PhotosBlobContainerName, model.ServerFileName, log); //Monitor the copy operation and wait for it to finish //before proceeding await storageRepo.MonitorCopy(container, model.ServerFileName, log); }
public ActionResult Photos(int?id, List <HttpPostedFileBase> files) { foreach (var file in files) { if (file != null && file.ContentLength > 0) { var extension = Path.GetExtension(file.FileName); var fileExtension = extension.ToLower(); if (allowedExtensions.Contains(fileExtension)) { var uniqe = Guid.NewGuid(); string path = Path.Combine(Server.MapPath("~/Uploads"), uniqe + extension); file.SaveAs(path); var photoModel = new PhotoModel(); photoModel.Name = uniqe + extension; photoModel.Type = PhotoType.Property; photoModel.ItemId = (int)id; var photo = Mapper.Map <Photo>(photoModel); unitOfWork.PhotoRepository.Insert(photo); unitOfWork.Save(); } } } return(RedirectToAction("Photos", new { id = id })); }
public async Task <PhotoModel> CreatePhoto(PhotoModel photo) { photo.Score = scoreCalculator.GetPhotoScore(photo); logWriter.LogInformation($"{nameof(CreatePhoto)}({nameof(photo.Filename)} = '{photo.Filename}')"); try { var item = Mappers.PhotoModel.ToDbItem(photo); var request = new PutItemRequest(tableName, item); BatchWriteItemRequest hashtagsRequests = GetHashtagsRequests(photo.RawText, photo.Hashtags, photo, HashtagUpdateMode.CreateOnly); await dynamoDbCore.PutItem(request); if (hashtagsRequests != null) { await dynamoDbCore.BatchWriteItem(hashtagsRequests); } logWriter.LogInformation($"Photo record created for '{photo.Filename}'"); return(photo); } catch (Exception ex) { logWriter.LogError(ex, $"Error in {nameof(CreatePhoto)}(photo.Id = '{photo.PhotoId}'):\n{ex.ToString()}"); throw new Exception("Error when creating photo.", ex); } }
internal static async Task SaveToRedisAsync(PhotoModel p, TextWriter log) { //Use repository to add to all caches IDatabase cache = RedisCache.Connection.GetDatabase(); RedisRepository repo = new RedisRepository(cache); await repo.AddPhotoToCachesAsync(p); }
public async Task <Result <IEnumerable <PhotoModel>, Error> > Get(Guid activityId) { var activityExists = (await _activitiesRepository.GetById(activityId)) != null; if (!activityExists) { return(Result.Failure <IEnumerable <PhotoModel>, Error>(ErrorsList.UnavailableActivity)); } var activity = await _activitiesRepository.GetByIdWithPhotos(activityId); var photos = activity.Photos; var photosModel = new List <PhotoModel>(); foreach (var photo in photos) { var user = await _userRepository.GetById(photo.UserId); photosModel.Add(PhotoModel.Create(photo.Id, photo.ActivityId, photo.UserId, user.Username, photo.Image)); } return(Result.Success <IEnumerable <PhotoModel>, Error>(photosModel)); }
public async Task <Result <PhotoModel, Error> > Add(Guid activityId, CreatePhotoModel model) { model.UserId = Guid.Parse(_accessor.HttpContext.User.Claims.First(c => c.Type == "userId").Value); using var stream = new MemoryStream(); await model.Image.CopyToAsync(stream); var activity = await _activitiesRepository.GetById(activityId); if (activity == null) { return(Result.Failure <PhotoModel, Error>(ErrorsList.UnavailableActivity)); } var photo = new Photo(activityId, model.UserId, stream.ToArray()); activity.AddPhoto(photo); var user = await _userRepository.GetById(photo.UserId); var notification = new Notification(activityId, DateTime.Now, $"{user.Username} has added a new photo to activity {activity.Name}." ); activity.AddNotification(notification); _activitiesRepository.Update(activity); await _activitiesRepository.SaveChanges(); return(Result.Success <PhotoModel, Error>(PhotoModel.Create( photo.Id, photo.ActivityId, photo.UserId, user.Username, photo.Image))); }
public ActionResult Create(PhotoModel photo, HttpPostedFileBase[] filesToBeUploaded) { //why is the photo id and album id same? int albumId = photo.PhotoModelId; AlbumModel album = EntityModelMapper.EntityToModel(AlbumRepo.Get(albumId)); foreach (var file in filesToBeUploaded) { //set important properties of the new photo object PhotoModel currentPhoto = new PhotoModel() { //PhotoId = Guid.NewGuid(), Name = photo.Name, FileName = file.FileName, DateCreated = DateTime.Now, Description = "[no description set]", UploadedBy = album.User.Username, Comments = new List <CommentModel>(), }; //physically saves copie(s) of the photos to the path specified file.SaveAs(Server.MapPath("~/UsersData/" + album.User.Username + "/" + album.Name + "/" + file.FileName)); //saves the photo object to the album object //todo: should not this be saved to the static list of a users album photos immediately? album.Photos.Add(currentPhoto); } ; return(RedirectToAction("Index", "Home")); //return PartialView("_Photos",/*allphotos*/); }
public PhotoDetailsPage(PhotoModel selectedPhoto) { ViewModel.SetPhotoCommand?.Execute(selectedPhoto); var photoTitleLabel = new PhotoDetailLabel(AutomationIdConstants.PhotoTitleLabel); photoTitleLabel.SetBinding(Label.TextProperty, nameof(ViewModel.PhotoTitle)); var photoImage = new CachedImage { AutomationId = AutomationIdConstants.PhotoImage }; photoImage.SetBinding(CachedImage.SourceProperty, nameof(ViewModel.PhotoImageSource)); Title = PageTitles.PhotoListPage; Padding = new Thickness(20); Content = new StackLayout { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, Spacing = 20, Children = { photoImage, photoTitleLabel } }; }
public IActionResult UpdatePhotoModel([FromBody] PhotoModel photoModel) { if (photoModel == null) { return(BadRequest()); } //if (photoModel.Voornaam == string.Empty || photoModel.Achternaam == string.Empty) //{ // ModelState.AddModelError("Naam/Voornaam", "De naam kan niet leeg zijn"); //} if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var PhotoModelToUpdate = _photoModelRepository.GetPhotoModelById(photoModel.PhotoModelID); if (PhotoModelToUpdate == null) { return(NotFound()); } _photoModelRepository.UpdatePhotoModel(photoModel); return(NoContent()); }
public async Task <IActionResult> UplaodUserPhoto(PhotoModel photoModel) { try { if (!ModelState.IsValid) { ViewBag.PhotoUploadError = "Please upload a photo"; return(View(photoModel)); } var result = await _photoInterface.AddUserPhoto(photoModel.PhotoFile, (Request.Cookies[_configuration["ZumbaCookies:ZumbaJwt"]]).ToString()); if (result.Code != 200) { return(RedirectToAction("Index", "Error")); } if (HttpContext.Request.Cookies.ContainsKey("AvatarReference")) { Response.Cookies.Delete(_configuration["ZumbaCookies:UserAvatar"]); } Response.Cookies.Append(_configuration["ZumbaCookies:UserAvatar"], result.Url); return(RedirectToAction("UserSetting", "User")); } catch (Exception ex) { _logger.LogError($"Error encountered in PhotosController||UplaodUserPhoto ErrorMessage: {ex.Message}"); throw; } }
/// <summary> /// 增加一条数据 /// </summary> public int Add(PhotoModel model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into tb_Photo("); strSql.Append("ProductId,PhotoUrl)"); strSql.Append(" values ("); strSql.Append("@ProductId,@PhotoUrl)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@ProductId", SqlDbType.Int, 4), new SqlParameter("@PhotoUrl", SqlDbType.NVarChar, 200) }; parameters[0].Value = model.ProductId; parameters[1].Value = model.PhotoUrl; object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters); if (obj == null) { return(0); } else { return(Convert.ToInt32(obj)); } }
/// <summary> /// 更新一条数据 /// </summary> public bool Update(PhotoModel model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update tb_Photo set "); strSql.Append("ProductId=@ProductId,"); strSql.Append("PhotoUrl=@PhotoUrl"); strSql.Append(" where PhotoId=@PhotoId"); SqlParameter[] parameters = { new SqlParameter("@ProductId", SqlDbType.Int, 4), new SqlParameter("@PhotoUrl", SqlDbType.NVarChar, 200), new SqlParameter("@PhotoId", SqlDbType.Int, 4) }; parameters[0].Value = model.ProductId; parameters[1].Value = model.PhotoUrl; parameters[2].Value = model.PhotoId; int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return(true); } else { return(false); } }
public IHttpActionResult Create([FromBody] PhotoModel model) { var userId = Request.GetUserId(); if (userId < 0) { return(Unauthorized()); } if (model == null) { return(BadRequest("Model cannot be null")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var photo = Mapper.Map <Photo>(model); photo.RowState = RowState.Created; photo.UploadedBy = userId; photo.UploadedAt = DateTime.Now; _photoManager.Add(photo); return(Created($"/{photo.Id}", Mapper.Map <PhotoViewModel>(photo))); }
protected void btn_add_Click(object sender, EventArgs e) { //上传商品图片 //判断是否存在上传的文件 if (this.txtPhotoUrl.HasFile == false) { ClientScript.RegisterStartupScript( this.GetType(), "error", "alert('未选择任何文件!');", true); return; } //获取文件的后缀名 string temp = this.txtPhotoUrl.FileName.Substring(this.txtPhotoUrl.FileName.LastIndexOf('.') + 1).ToLower(); //判断是否为图片文件 if (temp != "bmp" && temp != "jpg" && temp != "png") { ClientScript.RegisterStartupScript( this.GetType(), "error", "alert('只能上传图片文件!');", true); return; } //为了防止不同用户上传图片重名,为文件进行重命名 string newFileName = DateTime.Now.Ticks + "." + temp; //保存文件 this.txtPhotoUrl.SaveAs(Server.MapPath("/") + "UploadFiles/" + newFileName); PhotoModel model = new PhotoModel(); PhotoBll bll = new PhotoBll(); model.ProductId = (int)Session["ProductId"]; model.PhotoUrl = "UploadFiles/" + newFileName; if (bll.Add(model) > 0) { Response.Redirect(Request.Url.ToString()); } }
public ActionResult UploadNew(API.Models.NewPhotoModel photo) { if ( !User.Identity.IsAuthenticated ) throw new Exception( "user not authenticated" ); UserModel authUser = new UserRepository().GetByUsername( User.Identity.Name ); // # Validate request // photo.AlbumID: album has to exist, has to be owned by authenticated user AlbumRepository albums = new AlbumRepository(); AlbumModel album = albums.GetById( photo.AlbumID, withUser: true, withFollowers: true ); if ( album == null ) throw new Exception( "album with specified ID not found" ); if ( album.User != authUser ) throw new Exception( "authenticated user is not the owner of the specified album" ); // photo.Date: can't be set in the future if ( photo.Date == null ) throw new Exception( "date of the photo hasn't been specified" ); if ( photo.Date > DateTime.Now ) throw new Exception( "date of the photo can't be set in the future" ); // photo.Description: can't be longer than 1000 characters if ( photo.Description != null && photo.Description.Length > 1000 ) throw new Exception( "description of the photo can't be longer that 1000 characters" ); // photo.Image: has to be valid base-64 encoded binary file, has to be valid image Image image; try { image = ApiHelpers.Base64ToImage( photo.Image.Replace("\n", "") ); } catch (System.Exception ex) { throw new Exception( "provided image file is invalid: " + ex.Message ); } string path; double? locLatitude; double? locLongitude; using ( image ) { // photo.Image: has to be a valid JPEG if ( !image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg) ) throw new Exception( "provided image file is not of JPEG format" ); // # New photo successfully validated - process // generate path for the image string photoName = "photo_" + DateTime.Now.ToString( "yyyyMMddHHmmssff" ); path = FileHelper.getPhotoPathWithoutExtension( album, photoName ) + ".jpg"; if ( string.IsNullOrEmpty( path ) ) throw new Exception( "failed to generate path for the image" ); // save the photo to the file system try { path = FileHelper.SavePhoto( image, album, photoName ); } catch ( System.Exception ex ) { throw new Exception( "failed to save the image to the file system: " + ex.Message ); } if ( string.IsNullOrEmpty( path ) ) throw new Exception( "failed to save the image to the file system" ); // try to read GPS localization data if (photo.LocationLatitude.HasValue && photo.LocationLongitude.HasValue) { locLatitude = photo.LocationLatitude; locLongitude = photo.LocationLongitude; } else { locLatitude = image.GPSLatitude(); locLongitude = image.GPSLongitude(); } } // create photo entity PhotoModel newPhoto = new PhotoModel() { Path = path, Date = photo.Date, Description = photo.Description, Album = album }; if ( locLatitude.HasValue && locLongitude.HasValue ) { newPhoto.LocationLatitude = locLatitude.Value; newPhoto.LocationLongitude = locLongitude.Value; } // save the entity to the database try { new PhotoRepository().Create( newPhoto ); } catch (System.Exception ex) { // TODO: delete both the image and its thumbnail from the file system throw new Exception( "failed to save the photo to the database: " + ex.Message ); } Helpers.NotifyAlbumObservers(newPhoto.Album); // return result return Json( new { ok = true, data = new { photo = string.Format( "{0}/api/photos/{1}", Helpers.BaseURL(), newPhoto.Id ) } } ); }
private static void CreateAlbums() { UserRepository users = new UserRepository(); UserModel user = users.GetByUsername("Klocu"); AlbumRepository albums = new AlbumRepository(); CategoryModel category=null; using (var session = SessionProvider.SessionFactory.OpenSession()) { category=session.CreateQuery("from CategoryModel where Name =:name").SetParameter("name","People").UniqueResult<CategoryModel>(); } AlbumModel album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "Jak zmieniałem się w czasie", Name = "Moja twarz", Public = true, Rating = 0, User = user, Views = 1234 }; albums.Create(album); LinkedList<PhotoModel> list = new LinkedList<PhotoModel>(); PhotoModel photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 1, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/photo_2012051022444645.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011,4,30,22,33,5), Description = "Oto ja", Path = "/Static/photos/photo_2012051022450267.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2012, 2,28 , 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/photo_2012051022452109.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 8, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110108.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 15, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110115.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 22, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110122.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 29, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110129.jpg" }; list.AddLast(photo); album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "", Name = "Widok za moin oknem", Public = true, Rating = 0, User = user, Views = 2 }; albums.Create(album); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2011-12-29 06.48.45.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.20.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.35.jpg" }; list.AddLast(photo); album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "Zmieniający się rynek", Name = "Zmieniający się rynek", Public = true, Rating = 0, User = user, Views = 111 }; albums.Create(album); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2011-12-29 06.48.45.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.20.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.35.jpg" }; list.AddLast(photo); /* album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "Jak zmieniałem się w czasie", Name = "Moja twarz", Public = true, Rating = 0, User = user, Views = 1234 }; */ using(var session= SessionProvider.SessionFactory.OpenSession()) using (var trans = session.BeginTransaction()) { foreach (PhotoModel p in list) session.Save(p); trans.Commit(); } }
public static string PhotoThumbnail(PhotoModel photo) { return Path.GetDirectoryName(photo.Path).Replace("\\", "/") + "/" + Path.GetFileNameWithoutExtension(photo.Path) + "_mini.jpg"; }
public ResponseItem Put(PhotoModel value) { var _Entity = DB.yy_Photo.Find(value.Photo.ID); if (_Entity != null) { _Entity.IsShow = value.Photo.IsShow; _Entity.ShowIndex = value.Photo.ShowIndex; _Entity.Title = value.Photo.Title; _Entity.KeyWords = value.Photo.KeyWords; _Entity.Summary = value.Photo.Summary; _Entity.TypeIDs = value.Photo.TypeIDs; _Entity.Recommend = value.Photo.Recommend; _Entity.TargetPlatforms = value.Photo.TargetPlatforms; _Entity.CanReply = value.Photo.CanReply; _Entity.CreateDate = value.Photo.CreateDate; DB.SaveChanges(); DB.Database.ExecuteSqlCommand("DELETE FROM yy_Photo_Item WHERE PhotoID = " + value.Photo.ID); foreach (var v in value.Items) { v.PhotoID = value.Photo.ID; } DB.yy_Photo_Item.AddRange(value.Items); DB.SaveChanges(); return new ResponseItem(0, ""); } return new ResponseItem(1, "不存在的相册。"); }
public Photo CreatePhoto(PhotoModel photoModel) { try { var photo = new Photo() { PhotoId = photoModel.PhotoId, Image=photoModel.Image, PlaceId=photoModel.PlaceId, UserId=photoModel.UserId, UploadDate=photoModel.UploadDate }; return photo; } catch (Exception) { throw null; } }
public ResponseItem Post(PhotoModel value) { try { DB.yy_Photo.Add(value.Photo); DB.SaveChanges(); foreach (var v in value.Items) { v.PhotoID = value.Photo.ID; } DB.yy_Photo_Item.AddRange(value.Items); DB.SaveChanges(); return new ResponseItem(0, "添加相册成功"); } catch (Exception ex) { return new ResponseItem(2, ex.Message); } }
public ActionResult AddPhoto(NewPhotoModel photo) { UserModel user = new UserRepository().GetByUsernameWithAlbums(HttpContext.User.Identity.Name, withFollowers: true); ViewBag.Albums = user.Albums; if (photo.Source == "remote") photo.FileInput = null; else photo.PhotoURL = null; ITransaction transaction = null; ISession session = null; try { using (Image img = FileHelper.PrepareImageFromRemoteOrLocal(photo)) { if (img == null) throw new FileUploadException("Can't upload your photo. Please try again later."); if (ModelState.IsValid) { AlbumModel selectedAlbum = null; foreach (AlbumModel album in user.Albums) { if (album.Id == photo.AlbumId) { selectedAlbum = album; break; } } session = SessionProvider.SessionFactory.OpenSession(); transaction = session.BeginTransaction(); string photoName = "photo_" + DateTime.Now.ToString("yyyyMMddHHmmssff"); string path = FileHelper.getPhotoPathWithoutExtension(selectedAlbum, photoName) + ".jpg"; if (string.IsNullOrEmpty(path)) throw new Exception("Can't save image"); path = FileHelper.SavePhoto(img, selectedAlbum, photoName); if (string.IsNullOrEmpty(path)) throw new Exception("Returned path is empty"); PhotoRepository repo = new PhotoRepository(); PhotoModel newPhoto = new PhotoModel() { Path = path, Date = DateTime.Parse(photo.Date), Description = photo.Description, Album = selectedAlbum }; double? locLatitude = img.GPSLatitude(); double? locLongitude = img.GPSLongitude(); if (locLatitude.HasValue && locLongitude.HasValue) { newPhoto.LocationLatitude = locLatitude.Value; newPhoto.LocationLongitude = locLongitude.Value; } repo.Create(newPhoto); System.Diagnostics.Debug.WriteLine("Created db entry " + newPhoto.Id); transaction.Commit(); Helpers.NotifyAlbumObservers(newPhoto.Album); return RedirectToAction("Show", new { id = photo.AlbumId }); } } } catch (FileUploadException ex) { if (transaction != null) { transaction.Rollback(); transaction.Dispose(); } if (session != null) session.Dispose(); ModelState.AddModelError("FileInput", ex.Message); } catch (Exception) { if (transaction != null) { transaction.Rollback(); transaction.Dispose(); } if (session != null) session.Dispose(); ModelState.AddModelError("FileInput", "Can't upload your photo. Please try again later."); } return View(photo); }