/// <summary> /// One media from json /// </summary> public IMedia MapJsonToMedia(string json) { IMedia m = new Models.Media(); JObject jObject = JObject.Parse(json); JToken jMedia = jObject["data"]; m.CreatedBy = userJson.MapJsonToMinifiedUser(jMedia["user"]); m.ImageThumbnailUrl = jMedia["images"]["thumbnail"]["url"].ToString(); m.ImageLowResolutionUrl = jMedia["images"]["low_resolution"]["url"].ToString(); m.ImageStandardResolutionUrl = jMedia["images"]["standard_resolution"]["url"].ToString(); m.Id = jMedia["id"].ToString(); m.Text = jMedia["caption"]["text"].ToString(); m.CreatedTimeUnixMiliseconds = long.Parse(jMedia["caption"]["created_time"].ToString()) * 1000; m.LikesCount = int.Parse(jMedia["likes"]["count"].ToString()); m.Tags = new List <string>(); foreach (var token in jMedia["tags"]) { m.Tags.Add(token.ToString()); } m.CommentsCount = int.Parse(jMedia["comments"]["count"].ToString()); m.MediaUrl = jMedia["link"].ToString(); m.Location = new JsonLocationController().MapJsonToLocation(jMedia["location"]); m.UsersInPhoto = new List <IMinifiedUser>(); foreach (var token in jMedia["users_in_photo"].Children()) { m.UsersInPhoto.Add(userJson.MapJsonToMinifiedUser(token["user"])); } return(m); }
public static IMedia BuildEntity(ContentVersionDto dto, IMediaType contentType) { var media = new Models.Media(dto.ContentDto.NodeDto.Text, dto.ContentDto.NodeDto.ParentId, contentType); try { media.DisableChangeTracking(); media.Id = dto.NodeId; media.Key = dto.ContentDto.NodeDto.UniqueId; media.Path = dto.ContentDto.NodeDto.Path; media.CreatorId = dto.ContentDto.NodeDto.UserId.Value; media.Level = dto.ContentDto.NodeDto.Level; media.ParentId = dto.ContentDto.NodeDto.ParentId; media.SortOrder = dto.ContentDto.NodeDto.SortOrder; media.Trashed = dto.ContentDto.NodeDto.Trashed; media.CreateDate = dto.ContentDto.NodeDto.CreateDate; media.UpdateDate = dto.VersionDate; media.Version = dto.VersionId; //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 media.ResetDirtyProperties(false); return(media); } finally { media.EnableChangeTracking(); } }
public IMedia BuildEntity(ContentVersionDto dto) { var media = new Models.Media(dto.ContentDto.NodeDto.Text, dto.ContentDto.NodeDto.ParentId, _contentType) { Id = _id, Key = dto.ContentDto.NodeDto.UniqueId.HasValue ? dto.ContentDto.NodeDto.UniqueId.Value : _id.ToGuid(), Path = dto.ContentDto.NodeDto.Path, CreatorId = dto.ContentDto.NodeDto.UserId.Value, Level = dto.ContentDto.NodeDto.Level, ParentId = dto.ContentDto.NodeDto.ParentId, SortOrder = dto.ContentDto.NodeDto.SortOrder, Trashed = dto.ContentDto.NodeDto.Trashed, CreateDate = dto.ContentDto.NodeDto.CreateDate, UpdateDate = dto.VersionDate, Version = dto.VersionId }; //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 media.ResetDirtyProperties(false); return(media); }
/// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> public IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0) { var mediaType = FindMediaTypeByAlias(mediaTypeAlias); var media = new Models.Media(name, parent, mediaType); if (Creating.IsRaisedEventCancelled(new NewEventArgs <IMedia>(media, mediaTypeAlias, parent), this)) { media.WasCancelled = true; return(media); } using (new WriteLock(Locker)) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMediaRepository(uow)) { media.CreatorId = userId; repository.AddOrUpdate(media); uow.Commit(); var xml = media.ToXml(); CreateAndSaveMediaXml(xml, media.Id, uow.Database); } } Created.RaiseEvent(new NewEventArgs <IMedia>(media, false, mediaTypeAlias, parent), this); Audit.Add(AuditTypes.New, "", media.CreatorId, media.Id); return(media); }
/// <summary> /// Saves the given binary data for the given media object. /// </summary> /// <param name="media">The media object</param> /// <param name="bytes">The binary data</param> public void Put(Models.Media media, byte[] bytes) { if (!disabled) { using (var writer = new FileStream(Path.Combine(mediaMapped, media.Id.ToString()), FileMode.Create)) { writer.Write(bytes, 0, bytes.Length); } } }
/// <summary> /// Saves the binary data available in the stream in the /// given media object. /// </summary> /// <param name="media">The media object</param> /// <param name="stream">The stream</param> public async void Put(Models.Media media, Stream stream) { if (!disabled) { using (var writer = new FileStream(Path.Combine(mediaMapped, media.Id.ToString()), FileMode.Create)) { await stream.CopyToAsync(writer); } } }
/// <summary> /// Adds or updates the given model in the database /// depending on its state. /// </summary> /// <param name="content">The content to save</param> public async Task Save(Models.Media model) { var media = await _db.Media .Include(m => m.Versions) .FirstOrDefaultAsync(m => m.Id == model.Id) .ConfigureAwait(false); if (media == null) { media = new Media() { Id = model.Id, Created = DateTime.Now }; await _db.Media.AddAsync(media).ConfigureAwait(false); } media.Filename = model.Filename; media.FolderId = model.FolderId; media.Type = model.Type; media.Size = model.Size; media.Width = model.Width; media.Height = model.Height; media.ContentType = model.ContentType; media.LastModified = DateTime.Now; // Delete removed versions var current = model.Versions.Select(v => v.Id).ToArray(); var removed = media.Versions.Where(v => !current.Contains(v.Id)).ToArray(); if (removed.Length > 0) { _db.MediaVersions.RemoveRange(removed); } // Add new versions foreach (var version in model.Versions) { if (media.Versions.All(v => v.Id != version.Id)) { var mediaVersion = new MediaVersion { Id = version.Id, MediaId = media.Id, Size = version.Size, Width = version.Width, Height = version.Height, FileExtension = version.FileExtension }; _db.MediaVersions.Add(mediaVersion); media.Versions.Add(mediaVersion); } } // Save all changes await _db.SaveChangesAsync().ConfigureAwait(false); }
private Media MapEFToModel(EF.Models.Media m) { if (m != null) { var children = _dataService.GetChildren(m.MediaId); var comments = new List <Comment>(); if (m.Comment != null) { comments = _commentService.MapEFToModel(m.Comment).ToList(); } var media = new Models.Media { MediaId = m.MediaId, MediaGuid = m.MediaGuid, Filesize = m.Filesize, Name = m.Name, CreatedOn = m.CreatedOn, TimeStamp = m.TimeStamp, MediaTypeId = m.MediaTypeId, ExtensionTypeId = m.ExtensionTypeId, Path = StringHelper.ReversePath(m.Path, '\\'), Comments = comments }; if (children != null) { var list = new List <SMW.Models.Media>(); media.Children = list; foreach (var child in children) { media.Children.Add( new SMW.Models.Media { MediaId = child.MediaId, ParentId = child.ParentId, MediaGuid = child.MediaGuid, Name = child.Name, Filesize = child.Filesize, CreatedOn = child.CreatedOn, TimeStamp = child.TimeStamp, MediaTypeId = child.MediaTypeId, ExtensionTypeId = child.ExtensionTypeId, Path = StringHelper.ReversePath(child.Path, '\\') }); } } return(media); } else { return(null); } }
/// <summary> /// Moves the media to the folder with the specified id. /// </summary> /// <param name="media">The media</param> /// <param name="folderId">The folder id</param> public async Task Move(Models.Media model, Guid?folderId) { var media = await _db.Media .FirstOrDefaultAsync(m => m.Id == model.Id) .ConfigureAwait(false); if (media != null) { media.FolderId = folderId; await _db.SaveChangesAsync().ConfigureAwait(false); } }
private IEnumerable <IMedia> MapDtosToContent(List <ContentDto> dtos, bool withCache = false) { var temps = new List <TempContent <Models.Media> >(); var contentTypes = new Dictionary <int, IMediaType>(); var content = new Models.Media[dtos.Count]; for (var i = 0; i < dtos.Count; i++) { var dto = dtos[i]; if (withCache) { // if the cache contains the (proper version of the) item, use it var cached = IsolatedCache.GetCacheItem <IMedia>(RepositoryCacheKeys.GetKey <IMedia>(dto.NodeId)); if (cached != null && cached.VersionId == dto.ContentVersionDto.Id) { content[i] = (Models.Media)cached; continue; } } // else, need to build it // get the content type - the repository is full cache *but* still deep-clones // whatever comes out of it, so use our own local index here to avoid this var contentTypeId = dto.ContentTypeId; if (contentTypes.TryGetValue(contentTypeId, out IMediaType contentType) == false) { contentTypes[contentTypeId] = contentType = _mediaTypeRepository.Get(contentTypeId); } var c = content[i] = ContentBaseFactory.BuildEntity(dto, contentType); // need properties var versionId = dto.ContentVersionDto.Id; temps.Add(new TempContent <Models.Media>(dto.NodeId, versionId, 0, contentType, c)); } // load all properties for all documents from database in 1 query - indexed by version id var properties = GetPropertyCollections(temps); // assign properties foreach (var temp in temps) { temp.Content.Properties = properties[temp.VersionId]; // reset dirty initial properties (U4-1946) temp.Content.ResetDirtyProperties(false); } return(content); }
/// <summary> /// Gets the binary data for the given media object. /// </summary> /// <param name="media">The media object</param> /// <returns>The binary data</returns> public byte[] Get(Models.Media media) { if (!disabled) { var path = Path.Combine(mediaMapped, media.Id.ToString()); if (File.Exists(path)) { return(File.ReadAllBytes(path)); } } return(null); }
protected void btnXoa_Command(object sender, CommandEventArgs e) { int Id = Convert.ToInt32(e.CommandArgument); Models.NewsEntities db = new Models.NewsEntities(); Models.Media obj = db.Media.FirstOrDefault(x => x.Id == Id); if (obj != null) { db.Media.Remove(obj); db.SaveChanges(); getData(Convert.ToInt32(txtIdBV.Text)); } }
/// <summary> /// Initializes the field for client use. /// </summary> /// <param name="api">The current api</param> public virtual async Task Init(IApi api) { if (Id.HasValue) { Media = await api.Media .GetByIdAsync(Id.Value) .ConfigureAwait(false); if (Media == null) { // The image has been removed, remove the // missing id. Id = null; } } }
/// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media is based on. /// </summary> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> public IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0) { IMediaType mediaType; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow)) { var query = Query <IMediaType> .Builder.Where(x => x.Alias == mediaTypeAlias); var mediaTypes = repository.GetByQuery(query); if (!mediaTypes.Any()) { throw new Exception(string.Format("No MediaType matching the passed in Alias: '{0}' was found", mediaTypeAlias)); } mediaType = mediaTypes.First(); if (mediaType == null) { throw new Exception(string.Format("MediaType matching the passed in Alias: '{0}' was null", mediaTypeAlias)); } } var media = new Models.Media(name, parent, mediaType); if (Creating.IsRaisedEventCancelled(new NewEventArgs <IMedia>(media, mediaTypeAlias, parent), this)) { media.WasCancelled = true; return(media); } media.CreatorId = userId; Created.RaiseEvent(new NewEventArgs <IMedia>(media, false, mediaTypeAlias, parent), this); Audit.Add(AuditTypes.New, "", media.CreatorId, media.Id); return(media); }
/// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> public IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0) { var mediaType = FindMediaTypeByAlias(mediaTypeAlias); var media = new Models.Media(name, parentId, mediaType); if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parentId), this)) { media.WasCancelled = true; return media; } media.CreatorId = userId; Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parentId), this); Audit.Add(AuditTypes.New, string.Format("Media '{0}' was created", name), media.CreatorId, media.Id); return media; }
/// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// Note that using this method will simply return a new IMedia without any identity /// as it has not yet been persisted. It is intended as a shortcut to creating new media objects /// that does not invoke a save operation against the database. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> public IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0) { var mediaType = FindMediaTypeByAlias(mediaTypeAlias); var media = new Models.Media(name, parent, mediaType); if (Creating.IsRaisedEventCancelled(new NewEventArgs <IMedia>(media, mediaTypeAlias, parent), this)) { media.WasCancelled = true; return(media); } media.CreatorId = userId; Created.RaiseEvent(new NewEventArgs <IMedia>(media, false, mediaTypeAlias, parent), this); Audit.Add(AuditTypes.New, "", media.CreatorId, media.Id); return(media); }
/// <summary> /// Returns a media from a JToken /// </summary> public IMedia MapJsonToMedia(JToken jMedia) { if (!jMedia.HasValues) { return(null); } IMedia m = new Models.Media() { CreatedBy = userJson.MapJsonToMinifiedUser(jMedia["user"]), ImageThumbnailUrl = jMedia["images"]["thumbnail"]["url"].ToString(), ImageLowResolutionUrl = jMedia["images"]["low_resolution"]["url"].ToString(), ImageStandardResolutionUrl = jMedia["images"]["standard_resolution"]["url"].ToString(), Id = jMedia["id"].ToString(), Text = jMedia["caption"]["text"].ToString(), CreatedTimeUnixMiliseconds = long.Parse(jMedia["caption"]["created_time"].ToString()) * 1000, LikesCount = int.Parse(jMedia["likes"]["count"].ToString()), CommentsCount = int.Parse(jMedia["comments"]["count"].ToString()), MediaUrl = jMedia["link"].ToString(), Location = new JsonLocationController().MapJsonToLocation(jMedia["location"]), UsersInPhoto = new List <IMinifiedUser>() }; // Add tags m.Tags = new List <string>(); foreach (var token in jMedia["tags"].Children()) { m.Tags.Add(token.ToString()); } // Add users in photo m.UsersInPhoto = new List <IMinifiedUser>(); foreach (var token in jMedia["users_in_photo"].Children()) { m.UsersInPhoto.Add(userJson.MapJsonToMinifiedUser(token["user"])); } return(m); }
/// <summary> /// Builds an IMedia item from a dto and content type. /// </summary> public static Models.Media BuildEntity(ContentDto dto, IMediaType contentType) { var nodeDto = dto.NodeDto; var contentVersionDto = dto.ContentVersionDto; var content = new Models.Media(nodeDto.Text, nodeDto.ParentId, contentType); try { content.DisableChangeTracking(); content.Id = dto.NodeId; content.Key = nodeDto.UniqueId; content.VersionId = contentVersionDto.Id; // fixme missing names? content.Path = nodeDto.Path; content.Level = nodeDto.Level; content.ParentId = nodeDto.ParentId; content.SortOrder = nodeDto.SortOrder; content.Trashed = nodeDto.Trashed; content.CreatorId = nodeDto.UserId ?? Constants.Security.UnknownUserId; content.WriterId = contentVersionDto.UserId ?? Constants.Security.UnknownUserId; content.CreateDate = nodeDto.CreateDate; content.UpdateDate = contentVersionDto.VersionDate; // reset dirty initial properties (U4-1946) content.ResetDirtyProperties(false); return(content); } finally { content.EnableChangeTracking(); } }
/// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media is based on. /// </summary> /// <param name="name">Name of the Media object</param> /// <param name="parentId">Id of Parent for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> public IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0) { IMediaType mediaType; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow)) { var query = Query<IMediaType>.Builder.Where(x => x.Alias == mediaTypeAlias); var mediaTypes = repository.GetByQuery(query); if (!mediaTypes.Any()) throw new Exception(string.Format("No MediaType matching the passed in Alias: '{0}' was found", mediaTypeAlias)); mediaType = mediaTypes.First(); if (mediaType == null) throw new Exception(string.Format("MediaType matching the passed in Alias: '{0}' was null", mediaTypeAlias)); } var media = new Models.Media(name, parentId, mediaType); if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parentId), this)) { media.WasCancelled = true; return media; } media.CreatorId = userId; Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parentId), this); Audit.Add(AuditTypes.New, "", media.CreatorId, media.Id); return media; }
protected void btnUpload_Click(object sender, EventArgs e) { if (fuImg.HasFile == true) { // Bước 1: Tải file về server // Sinh tên file string filename = txtIdBV.Text + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff"); string[] arr = fuImg.FileName.Split('.'); string file_ext = arr[arr.Length - 1]; filename += '.' + file_ext; string folder = Server.MapPath("~/Uploads/AnhBaiViet/"); fuImg.SaveAs(folder + filename); // Bước 2: Thêm dữ liệu vào Database Models.NewsEntities db = new Models.NewsEntities(); Models.Media obj = new Models.Media(); obj.Id_Post = Convert.ToInt32(txtIdBV.Text); obj.Url = filename; db.Media.Add(obj); db.SaveChanges(); getData(Convert.ToInt32(txtIdBV.Text)); } }
/// <summary> /// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> /// that this Media should based on. /// </summary> /// <remarks> /// This method returns an <see cref="IMedia"/> object that has been persisted to the database /// and therefor has an identity. /// </remarks> /// <param name="name">Name of the Media object</param> /// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> /// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> /// <param name="userId">Optional id of the user creating the media item</param> /// <returns><see cref="IMedia"/></returns> public IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0) { var mediaType = FindMediaTypeByAlias(mediaTypeAlias); var media = new Models.Media(name, parent, mediaType); if (Creating.IsRaisedEventCancelled(new NewEventArgs<IMedia>(media, mediaTypeAlias, parent), this)) { media.WasCancelled = true; return media; } using (new WriteLock(Locker)) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMediaRepository(uow)) { media.CreatorId = userId; repository.AddOrUpdate(media); uow.Commit(); var xml = media.ToXml(); CreateAndSaveMediaXml(xml, media.Id, uow.Database); } } Created.RaiseEvent(new NewEventArgs<IMedia>(media, false, mediaTypeAlias, parent), this); Audit.Add(AuditTypes.New, string.Format("Media '{0}' was created with Id {1}", name, media.Id), media.CreatorId, media.Id); return media; }
public ActionResult Index(Models.Media mMedia, string date) { mMedia.MediaDate = GetMediaDate(); return(View(mMedia)); }
public void AddMedia(Models.Media media) { AllMediaDaoEF.Instance.Add(media); }
public void DeleteMedia(Models.Media media) { AllMediaDaoEF.Instance.Delete(media); }
/// <summary> /// Deletes the given media model. /// </summary> /// <param name="media">The media model</param> public void Delete(Models.Media media) { Delete(media.Id); }
/// <summary> /// Deletes the binary data for the given media object. /// </summary> /// <param name="media">The media object</param> public void Delete(Models.Media media) { File.Delete(Path.Combine(mediaMapped, media.Id.ToString())); }