public IList <IStorageLocation> CreateMedia(DicomFile data) { if (null != MediaStorage) { string key = null; int framesCount = 1; List <IStorageLocation> locations = new List <IStorageLocation> ( ); if (StoreMultiFrames) { DicomPixelData pd; pd = DicomPixelData.CreateFrom(data); framesCount = pd.NumberOfFrames; } for (int frame = 1; frame <= framesCount; frame++) { var storeLocation = MediaStorage.GetLocation(new DicomMediaId(data.DataSet, frame, MediaType)); Upload(data, frame, storeLocation); locations.Add(storeLocation); } return(locations); } throw new InvalidOperationException("No MediaStorage service found"); }
private MediaStorage GetMedia(Type mediaType) { MediaStorage md = null; mediaStorage.TryGetValue(mediaType.GetType(), out md); return(md); }
public MediaStorage Open(Type type) { lock (openLock) { MediaStorage md = null; bool alreadyCreated = mediaStorage.TryGetValue(type.GetType(), out md); //has never been created. if (md == null) { md = (MediaStorage)Activator.CreateInstance(type, true); mediaStorage.Add(type.GetType(), md); } //created or pulled from the dictionary, let's try to to get the object lock. try { md.OpenLock.WaitOne(-1); } catch (AbandonedMutexException ex) { ex.Data.Clear(); } //success, object obtained, don't forget everyone is blocked trying to get it, //release as soon as possible. return(md); } }
private void InitMedia() { if (_media == null) { _media = new MediaStorageManagerFactory().GetManager("http"); _media.Init(_url); } }
public void Close(MediaStorage media) { lock (closeLock) { if (media.OpenLock.SafeWaitHandle.IsClosed) { return; } media.OpenLock.ReleaseMutex(); } }
public bool Save(MediaStorage media) { if (media.Id > 0) { return(mediaRepository.Update(media)); } else { return(mediaRepository.Insert(media)); } }
public void WriteData(Type type, string data) { //i assume the media is never removed if it's please protect this //call with lock mechanism. MediaStorage media = GetMedia(type); lock (media.AccessLock) { //simulate some delay Thread.Sleep(1000); media.Data.AppendFormat( "thread:{0},data:{1}|\n", Thread.CurrentThread.ManagedThreadId, data); } }
/// <summary> /// Builds the current clips stored into a single stream, then removes the clips. /// </summary> /// <param name="sessionUid">UID of the session to proces</param> /// <returns></returns> public async Task <bool> FinishClipAsync(string userUid, DomainModels.BlobUpload upload) { var session = await DbContext.Sessions.Include(x => x.Clips).ThenInclude(x => x.Media) .Include(x => x.Podcast).FirstOrDefaultAsync(x => x.UID == upload.SessionUid); if (session == null) { return(false); } using (var stream = upload.Data.OpenReadStream()) { var url = await MediaStorage.UploadStreamAsync(userUid, upload.SessionUid, upload.ClipUid, stream); var clip = session.Clips.FirstOrDefault(c => c.UID == upload.ClipUid); if (clip == null) { var id = CreateClip(url, session.ID, upload.ClipUid, upload.Name); clip = await DbContext.Clips.FindAsync(id); } var media = new Db.Media { ClipID = clip.ID, MediaUrl = url, UserUID = userUid, UID = Guid.NewGuid() }; DbContext.Media.Add(media); var mediaList = new List <Stream>(); foreach (var entry in clip.Media) { mediaList.Add(await StreamBuilder.GetStreamFromUrlAsync(entry.MediaUrl)); } if (mediaList.Count() > 1) { var concatStream = Audio.AudioConcatUtils.ConcatAudioStreams(mediaList); var concatUrl = await MediaStorage.UploadStreamAsync("concat", upload.SessionUid, upload.ClipUid, stream); clip.MediaUrl = concatUrl; } } await DbContext.SaveChangesAsync(); return(true); }
public void Run() { MediaStorage myMediaStorage = new MediaStorage(); // instantiate the two media players AudioPlayer myAudioPlayer = new AudioPlayer(); // instantiate the delegates MediaStorage.PlayMedia audioPlayerDelegate = new MediaStorage.PlayMedia(myAudioPlayer.PlayAudioFile); // call the delegates myMediaStorage.ReportResult(audioPlayerDelegate); }
/// <summary> /// Updates the stream belonging to the edit. /// </summary> /// <param name="edit">Edit to update.</param> /// <returns></returns> private async Task UpdateStreamAsync(Guid sessionUid, int editId) { var edit = await DbContext.Edits.Include(c => c.Clip).ThenInclude(c => c.Media).ThenInclude(c => c.Stream).FirstOrDefaultAsync(c => c.ID == editId); foreach (var entry in edit.Clip.Media) { var stream = await StreamBuilder.GetStreamFromUrlAsync(entry.MediaUrl); var file = await Audio.AudioEditUtils.TrimFile(stream, edit.StartTrim, edit.EndTrim); await MediaStorage.UploadStreamAsync(entry.UserUID, sessionUid, entry.Clip.UID, file); } await DbContext.SaveChangesAsync(); }
public string ReadData(Type type) { //i assume the media is never removed if it's please protect //this call with lock mechanism. MediaStorage media = GetMedia(type); string data; lock (media.AccessLock) { //simulate some delay Thread.Sleep(new Random(Convert.ToInt32(DateTime.Now.Ticks)).Next(2000)); data = media.Data.ToString(); } return(data); }
public IActionResult StorageAccounts() { List <MediaStorage> storageAccounts = new List <MediaStorage>(); string authToken = HomeController.GetAuthToken(Request, Response); using (MediaClient mediaClient = new MediaClient(authToken)) { foreach (StorageAccount storageAccount in mediaClient.StorageAccounts) { MediaStorage mediaStorage = new MediaStorage(authToken, storageAccount); storageAccounts.Add(mediaStorage); } ViewData["storageAccounts"] = storageAccounts.ToArray(); } return(View()); }
protected override WadoResponse DoProcess(IWadoUriRequest request, string mimeType) { var dcmLocation = MediaStorage.GetLocation(MediaFactory.Create(request, new DicomMediaProperties { MediaType = MimeMediaTypes.DICOM, TransferSyntax = (request.ImageRequestInfo != null) ? request.ImageRequestInfo.TransferSyntax : "" })); if (!dcmLocation.Exists( )) { throw new ApplicationException("Object Not Found - return proper wado error "); } //if (string.Compare(mimeType, MimeMediaTypes.DICOM, true) == 0) { return(new WadoResponse(Location.GetReadStream( ), mimeType)); } }
// in Main we use the higher-order function public static void Main() { // instantiate the storage class var ms = new MediaStorage(); // instantiate the player classes var aPlayer = new AudioPlayer(); var vPlayer = new VideoPlayer(); // instantiate the delegate var aDelegate = new MediaStorage.PlayMedia(aPlayer.PlayAudioFile); var vDelegate = new MediaStorage.PlayMedia(vPlayer.PlayVideoFile); // provide instances to the method using the delegate ms.ReportResult(aDelegate); ms.ReportResult(vDelegate); }
public ActionResult UploadFiles(string entityId, string entityName) { try { string uploadPath = Server.MapPath("~/Uploads/"); foreach (string _file in Request.Files) { var file = Request.Files[_file]; if (file != null && file.ContentLength > 0) { string guid = Guid.NewGuid().ToString(); entityId = entityId.HasValue() ? entityId : string.Empty; entityName = entityName.HasValue() ? entityName : string.Empty; string fileExtension = Path.GetExtension(file.FileName); string fileName = string.Format("{0}-{1}_{2}{3}", entityName, entityId, guid, fileExtension); var path = Path.Combine(uploadPath, fileName); file.SaveAs(path); string filePath = string.Concat("/Uploads/", fileName); var media = new MediaStorage() { FilePath = filePath, FileName = fileName, MimeType = MimeMapping.GetMimeMapping(fileName), EntityName = entityName, CreateDateUtc = DateTime.UtcNow, UpdateDateUtc = DateTime.UtcNow, }; mediaStorageService.Save(media); return(Json(new { success = true, pictureId = media.Id, imageUrl = filePath })); } } } catch (Exception) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { success = false, message = "Upload failed" })); } return(Json(new { success = true, message = "File uploaded successfully" })); }
public void Save(MediaItem media, byte[] data) { Guard.NotNull(media, nameof(media)); if (data == null || data.LongLength == 0) { // remove media storage if any if ((media.Entity.MediaStorageId ?? 0) != 0 && media.Entity != null && media.Entity.MediaStorage != null) { _mediaStorageRepository.Delete(media.Entity.MediaStorage); } } else { if (media.Entity.MediaStorage == null) { // entity has no media storage -> insert var newStorage = new MediaStorage { Data = data }; _mediaStorageRepository.Insert(newStorage); if (newStorage.Id == 0) { // actually we should never get here _dbContext.SaveChanges(); } media.Entity.MediaStorageId = newStorage.Id; // Required because during import the ChangeTracker doesn't treat media.Entity as changed entry. _dbContext.ChangeState((BaseEntity)media.Entity, System.Data.Entity.EntityState.Modified); _dbContext.SaveChanges(); } else { // update existing media storage media.Entity.MediaStorage.Data = data; _mediaStorageRepository.Update(media.Entity.MediaStorage); } } }
public virtual IWadoRsResponse Process(IWadoUriRequest request, string mimeType) { Location = MediaStorage.GetLocation(MediaFactory.Create(request, GetMediaProperties(request, mimeType, GetTransferSyntax(request)))); if (Location != null && Location.Exists( )) { WadoResponse response = new WadoResponse(Location.GetReadStream( ), mimeType); return(response); } else { //TODO: in case mime not storedmethod to create on return(DoProcess(request, mimeType)); } }
public void UploadFile(HttpPostedFile file) { MediaStorage storage = MediaStorage.Default; var template = this.StepDataObject.DataItem.TemplateFileInfo; var uploadFileName = DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "--Final--" + template.Name; string fullPath = Path.Combine(storage.Path, uploadFileName); file.SaveAs(fullPath); this.UploadedFileUrl = $"{MediaStorage.Default.Url}/{uploadFileName}"; // this.ExecuteAutofill(fullPath, true); this.Save(); }
public static void process(String template, String tmpdir, String targetname) { if (!PosixEmulation.FileIsDirectory(tmpdir)) { PosixEmulation.MakeDirectory(tmpdir); } String filename = tmpdir + "/" + targetname; PosixEmulation.RemoveFile(filename); try { copyFile(template, filename); } catch (IOException ex) { Console.WriteLine("Error copying: " + template + " to " + filename); throw ex; } Reader reader = new Reader(); Console.WriteLine("Reading: " + filename); reader.SetFileName(filename); if (!reader.Read()) { throw new Exception("Could not read: " + filename); } String reference = Testing.GetMediaStorageFromFile(template); if (reference == null || reference == "") { throw new Exception("Missing ref for: " + template); } MediaStorage ms = new MediaStorage(); ms.SetFromFile(reader.GetFile()); if (ms.IsUndefined()) { throw new Exception("ref is undefined for: " + filename + " should be " + reference); } MediaStorage.MSType ref_mstype = MediaStorage.GetMSType(reference); if (ms.GetMSType() != ref_mstype) { throw new Exception("incompatible type: " + reference + " vs " + ms.GetString() + " for " + filename); } }
static void Main(string[] args) { var MediaStorage = new MediaStorage(new List <IPlayable>(), new List <IMediaList>()); var Directory = Environment.CurrentDirectory; //аудио Guid id = Guid.NewGuid(); IPlayable element = new AudioElement(id, "AudioElement", null, new System.IO.FileInfo(Directory + "\\Баста.mp3")); MediaStorage.AddPlayable(element); Player player = new Player(new PlayableAdapterFactory()); player.Play(MediaStorage.IPlayableFindById(id)); //видео id = Guid.NewGuid(); element = new VideoElement(id, "VideoElement", null, new System.IO.FileInfo(Directory + "\\Баста.mp4")); MediaStorage.AddPlayable(element); player.Play(MediaStorage.IPlayableFindById(id)); //список Guid idMediaList = Guid.NewGuid(); IMediaList UserList = new AudioUserList(idMediaList, "AudioUserList", (ICollection <IPlayable>)MediaStorage.IPlayablesFindByName("AudioElement")); MediaStorage.AddMediaList(UserList); id = Guid.NewGuid(); element = new AudioElement(id, "AudioElement2", null, new System.IO.FileInfo(Directory + "\\Баста.mp3")); MediaStorage.AddPlayableFromMediaList(UserList, element); IMediaList mls = MediaStorage.IMediaListFindById(idMediaList); player.Play(mls.Items); Console.ReadLine(); }
/// <summary> /// Compiles the edit files into one streamable file and sends it to the publisher. /// </summary> /// <param name="sessionUid">UID of the session.</param> /// <param name="userUid">User requesting the action.</param> /// <returns></returns> public async Task <bool> FinishEditingAsync(Guid sessionUid, string userUid) { var session = await DbContext.Sessions.Include(c => c.Podcast).Include(c => c.TimelineEntries).ThenInclude(c => c.Clip) .ThenInclude(c => c.Media) .FirstOrDefaultAsync(x => x.UID == sessionUid && x.Podcast.Members.Any(c => c.UserUID == userUid && c.IsAdmin)); if (session == null) { return(false); } session.IsFinishedEditing = true; await DbContext.SaveChangesAsync(); var combinedStreams = new List <string>(); foreach (var entry in session.TimelineEntries.OrderBy(c => c.Position)) { var streams = new List <System.IO.Stream>(); foreach (var stream in entry.Clip.Media) { streams.Add(await StreamBuilder.GetStreamFromUrlAsync(stream.MediaUrl)); } var combinedStream = Audio.AudioConcatUtils.ConcatAudioStreams(streams); var url = await MediaStorage.UploadStreamAsync(Guid.NewGuid().ToString(), sessionUid, Guid.NewGuid(), combinedStream); combinedStreams.Add(url); } await TimelineBus.SendAsync(new Vocalia.ServiceBus.Types.Publishing.Timeline { PodcastUID = session.Podcast.UID, Date = session.Date, UID = session.UID, TimelineEntries = combinedStreams }); return(true); }
private void GenerateZipPozos() { MediaStorage storage = MediaStorage.Default; var zipFileName = DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss--") + "carpetas.pozos.cnih.zip"; string fullZipPath = Path.Combine(storage.Path, zipFileName); var sourceZip = this.StepDataObject.DataItem.TemplateFileInfo; ZipFile.CreateFromDirectory(sourceZip.FullName, fullZipPath); //using (var zip = ZipFile.Open(sourceZip.FullName, ZipArchiveMode.Update)) { //} this.AutofillFileUrl = $"{MediaStorage.Default.Url}/{fullZipPath}"; this.Save(); return; }
/// <summary> /// Creates a new episode from the stored unassigned episode. /// </summary> /// <param name="userUid">UserUID of the current user.</param> /// <param name="episode">Episode to create.</param> /// <returns></returns> private async Task <Db.Episode> CreateNewEpisode(string userUid, DomainModels.Episode episode) { var dbPodcast = await DbContext.Podcasts.FirstOrDefaultAsync(c => c.UID == episode.PodcastUID && c.Members.Any(x => x.UserUID == userUid)); var dbUnassignedEpisode = await DbContext.UnassignedEpisodes.Include(c => c.Clips).FirstOrDefaultAsync(c => c.UID == episode.UID); if (dbUnassignedEpisode == null) { return(null); } var clipStreams = new List <Stream>(); foreach (var clip in dbUnassignedEpisode.Clips) { clipStreams.Add(await StreamBuilder.GetStreamFromUrlAsync(clip.MediaUrl)); } var compiledStream = Audio.AudioConcatUtils.SequenceAudioStreams(clipStreams); var url = await MediaStorage.UploadStreamAsync("rss", dbPodcast.UID, Guid.NewGuid(), compiledStream); var dbEpisode = new Db.Episode { UID = Guid.NewGuid(), Title = episode.Title, Description = episode.Description, RssUrl = string.Concat(Config["RssPath"], dbPodcast.UID, "/", episode.UID), MediaUrl = url, PublishDate = DateTime.Now, PodcastID = dbPodcast.ID }; DbContext.Episodes.Add(dbEpisode); dbUnassignedEpisode.IsCompleted = true; await DbContext.SaveChangesAsync(); return(dbEpisode); }
private void LoadArchives(string[] files) { ctrlStatusLabel.Text = "Loading..."; //TODO(adm244): put into a separate thread for (int i = 0; i < files.Length; ++i) { MediaStorage storage = MediaStorage.ReadFromFile(files[i]); if (storage != null) { Archives.Add(storage); } } ctrlStatusLabel.Text = string.Format("{0} archives loaded.", Archives.Count); if (Archives.Count > 0) { clearArchivesToolStripMenuItem.Enabled = true; } FillTreeView(); FillPaletteSelector(); }
public static int Main(string[] args) { string file1 = args[0]; Mpeg2VideoInfo info = new Mpeg2VideoInfo(file1); System.Console.WriteLine(info.StartTime); System.Console.WriteLine(info.EndTime); System.Console.WriteLine(info.Duration); System.Console.WriteLine(info.AspectRatio); System.Console.WriteLine(info.FrameRate); System.Console.WriteLine(info.PictureWidth); System.Console.WriteLine(info.PictureHeight); ImageReader r = new ImageReader(); //Image image = new Image(); Image image = r.GetImage(); image.SetNumberOfDimensions(3); DataElement pixeldata = new DataElement(new gdcm.Tag(0x7fe0, 0x0010)); System.IO.FileStream infile = new System.IO.FileStream(file1, System.IO.FileMode.Open, System.IO.FileAccess.Read); uint fsize = gdcm.PosixEmulation.FileSize(file1); byte[] jstream = new byte[fsize]; infile.Read(jstream, 0, jstream.Length); SmartPtrFrag sq = SequenceOfFragments.New(); Fragment frag = new Fragment(); frag.SetByteValue(jstream, new gdcm.VL((uint)jstream.Length)); sq.AddFragment(frag); pixeldata.SetValue(sq.__ref__()); // insert: image.SetDataElement(pixeldata); PhotometricInterpretation pi = new PhotometricInterpretation(PhotometricInterpretation.PIType.YBR_PARTIAL_420); image.SetPhotometricInterpretation(pi); // FIXME hardcoded: PixelFormat pixeltype = new PixelFormat(3, 8, 8, 7); image.SetPixelFormat(pixeltype); // FIXME hardcoded: TransferSyntax ts = new TransferSyntax(TransferSyntax.TSType.MPEG2MainProfile); image.SetTransferSyntax(ts); image.SetDimension(0, (uint)info.PictureWidth); image.SetDimension(1, (uint)info.PictureHeight); image.SetDimension(2, 721); ImageWriter writer = new ImageWriter(); gdcm.File file = writer.GetFile(); file.GetHeader().SetDataSetTransferSyntax(ts); Anonymizer anon = new Anonymizer(); anon.SetFile(file); MediaStorage ms = new MediaStorage(MediaStorage.MSType.VideoEndoscopicImageStorage); UIDGenerator gen = new UIDGenerator(); anon.Replace(new Tag(0x0008, 0x16), ms.GetString()); anon.Replace(new Tag(0x0018, 0x40), "25"); anon.Replace(new Tag(0x0018, 0x1063), "40.000000"); anon.Replace(new Tag(0x0028, 0x34), "4\\3"); anon.Replace(new Tag(0x0028, 0x2110), "01"); writer.SetImage(image); writer.SetFileName("dummy.dcm"); if (!writer.Write()) { System.Console.WriteLine("Could not write"); return(1); } return(0); }
public static int Main(string[] args) { string file1 = args[0]; Mpeg2VideoInfo info = new Mpeg2VideoInfo(file1); System.Console.WriteLine( info.StartTime ); System.Console.WriteLine( info.EndTime ); System.Console.WriteLine( info.Duration ); System.Console.WriteLine( info.AspectRatio ); System.Console.WriteLine( info.FrameRate ); System.Console.WriteLine( info.PictureWidth ); System.Console.WriteLine( info.PictureHeight ); ImageReader r = new ImageReader(); //Image image = new Image(); Image image = r.GetImage(); image.SetNumberOfDimensions( 3 ); DataElement pixeldata = new DataElement( new gdcm.Tag(0x7fe0,0x0010) ); System.IO.FileStream infile = new System.IO.FileStream(file1, System.IO.FileMode.Open, System.IO.FileAccess.Read); uint fsize = gdcm.PosixEmulation.FileSize(file1); byte[] jstream = new byte[fsize]; infile.Read(jstream, 0 , jstream.Length); SmartPtrFrag sq = SequenceOfFragments.New(); Fragment frag = new Fragment(); frag.SetByteValue( jstream, new gdcm.VL( (uint)jstream.Length) ); sq.AddFragment( frag ); pixeldata.SetValue( sq.__ref__() ); // insert: image.SetDataElement( pixeldata ); PhotometricInterpretation pi = new PhotometricInterpretation( PhotometricInterpretation.PIType.YBR_PARTIAL_420 ); image.SetPhotometricInterpretation( pi ); // FIXME hardcoded: PixelFormat pixeltype = new PixelFormat(3,8,8,7); image.SetPixelFormat( pixeltype ); // FIXME hardcoded: TransferSyntax ts = new TransferSyntax( TransferSyntax.TSType.MPEG2MainProfile); image.SetTransferSyntax( ts ); image.SetDimension(0, (uint)info.PictureWidth); image.SetDimension(1, (uint)info.PictureHeight); image.SetDimension(2, 721); ImageWriter writer = new ImageWriter(); gdcm.File file = writer.GetFile(); file.GetHeader().SetDataSetTransferSyntax( ts ); Anonymizer anon = new Anonymizer(); anon.SetFile( file ); MediaStorage ms = new MediaStorage( MediaStorage.MSType.VideoEndoscopicImageStorage); UIDGenerator gen = new UIDGenerator(); anon.Replace( new Tag(0x0008,0x16), ms.GetString() ); anon.Replace( new Tag(0x0018,0x40), "25" ); anon.Replace( new Tag(0x0018,0x1063), "40.000000" ); anon.Replace( new Tag(0x0028,0x34), "4\\3" ); anon.Replace( new Tag(0x0028,0x2110), "01" ); writer.SetImage( image ); writer.SetFileName( "dummy.dcm" ); if( !writer.Write() ) { System.Console.WriteLine( "Could not write" ); return 1; } return 0; }
//public async Task<IEnumerable<Item>> Post(int id) public async Task PostMedia(int id) { int itemId = id; string username = User.Identity.Name.Split('\\')[1]; User user = _repository.Context.Users.Find(username); // Verify we have a multipart payload if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string uploadDir = HttpContext.Current.Server.MapPath("~/App_Data"); MultipartFormDataEncryptedStreamProvider provider = new MultipartFormDataEncryptedStreamProvider(uploadDir); try { Item item = _repository.Context.Items.Find(itemId); // Only the user who created the Item can attach media to it if (item.CreatedByUsername != username) { throw new HttpResponseException(HttpStatusCode.Forbidden); } if (null == item) { throw new UnauthorizedAccessException("Access denied"); } // Find the specified folder, create a new Item record, and attach it to the folder //Folder folder = _repository.Context.Folders.Find(folderId); //Item item = _repository.Context.Items.Add(new Item()); //if ( (null == folder) || (null == item) ) //{ // throw new UnauthorizedAccessException("Access denied"); //} //else //{ // item.Type = "File"; // TODO: push this property from Item down to Media // // It's really stupid that I have to supply values for these, because // // _repository won't trust them anyway. // item.CreatedTime = DateTime.UtcNow; // item.ModifiedTime = DateTime.UtcNow; // item.CreatedBy = user; // folder.Items.Add(item); //} // Wait for form data to finish loading await Request.Content.ReadAsMultipartAsync(provider); // Process file data foreach (var file in provider.FileData) { FileInfo fileInfo = new FileInfo(file.LocalFileName); // Create new Media record, attach it to its parent Item, and set media metadata Media media = _repository.Context.Media.Add(new Media()); //media.Item = item; item.Media.Add(media); //media.FileName = fileInfo.Name; media.FileName = (null == file.Headers.ContentDisposition.FileName) ? fileInfo.Name : UnquoteToken(file.Headers.ContentDisposition.FileName); media.MimeType = file.Headers.ContentType.ToString(); media.Bytes = fileInfo.Length; media.CreatedTime = (null == file.Headers.ContentDisposition.CreationDate) ? DateTime.UtcNow : ((DateTimeOffset)file.Headers.ContentDisposition.CreationDate).UtcDateTime; media.ModifiedTime = (null == file.Headers.ContentDisposition.ModificationDate) ? DateTime.UtcNow : ((DateTimeOffset)file.Headers.ContentDisposition.ModificationDate).UtcDateTime; media.SubmittedBy = user; // Create new MediaStorage record to save media storage/encryption details to DB MediaStorage mediaStorage = _repository.Context.MediaStorage.Add(new MediaStorage()); media.MediaStorage = mediaStorage; //mediaStorage.LocalFileName = file.LocalFileName; mediaStorage.LocalFileName = fileInfo.Name; // *** TODO: get the initialization vector from the stream provider mediaStorage.IV = Enumerable.Repeat((byte)0x00, 32).ToArray(); // Save changes to the database _repository.Context.SaveChanges(); } // Will this work, or should I just return item.Id as int and leave it up to the client // to fetch the new item in a separate request? //return _repository.Context.Items // .Include("Media") // .Where(i => i.Id == item.Id); //return item.Id; } catch (Exception e) { throw new HttpResponseException(HttpStatusCode.InternalServerError); } }
public void Seed(SmartObjectContext context) { context.MigrateLocaleResources(MigrateLocaleResources); var mediaStorages = context.Set <MediaStorage>(); var fileSystem = new LocalFileSystem(); var storeMediaInDb = true; { var settings = context.Set <Setting>(); // be careful, this setting does not necessarily exist var storeInDbSetting = settings.FirstOrDefault(x => x.Name == "Media.Images.StoreInDB"); if (storeInDbSetting != null) { storeMediaInDb = storeInDbSetting.Value.ToBool(true); // remove old bool StoreInDB because it's not used anymore settings.Remove(storeInDbSetting); } // set current media storage provider system name settings.AddOrUpdate(x => x.Name, new Setting { Name = "Media.Storage.Provider", Value = (storeMediaInDb ? "MediaStorage.SmartStoreDatabase" : "MediaStorage.SmartStoreFileSystem") }); } #region Pictures if (storeMediaInDb) { PageEntities(context, mediaStorages, context.Set <Picture>().OrderBy(x => x.Id), picture => { #pragma warning disable 612, 618 if (picture.PictureBinary != null && picture.PictureBinary.LongLength > 0) { var mediaStorage = new MediaStorage { Data = picture.PictureBinary }; picture.MediaStorage = mediaStorage; picture.PictureBinary = null; } #pragma warning restore 612, 618 }); } #endregion #region Downloads PageEntities(context, mediaStorages, context.Set <Download>().OrderBy(x => x.Id), download => { #pragma warning disable 612, 618 if (download.DownloadBinary != null && download.DownloadBinary.LongLength > 0) { if (storeMediaInDb) { // move binary data var mediaStorage = new MediaStorage { Data = download.DownloadBinary }; download.MediaStorage = mediaStorage; } else { // move to file system. it's necessary because from now on DownloadService depends on current storage provider // and it would not find the binary data anymore if do not move it. var fileName = GetFileName(download.Id, download.Extension, download.ContentType); var path = fileSystem.Combine(@"Media\Downloads", fileName); fileSystem.WriteAllBytes(path, download.DownloadBinary); } download.DownloadBinary = null; } #pragma warning restore 612, 618 }); #endregion #region Queued email attachments var attachmentQuery = context.Set <QueuedEmailAttachment>() .Where(x => x.StorageLocation == EmailAttachmentStorageLocation.Blob) .OrderBy(x => x.Id); PageEntities(context, mediaStorages, attachmentQuery, attachment => { #pragma warning disable 612, 618 if (attachment.Data != null && attachment.Data.LongLength > 0) { if (storeMediaInDb) { // move binary data var mediaStorage = new MediaStorage { Data = attachment.Data }; attachment.MediaStorage = mediaStorage; } else { // move to file system. it's necessary because from now on QueuedEmailService depends on current storage provider // and it would not find the binary data anymore if do not move it. var fileName = GetFileName(attachment.Id, Path.GetExtension(attachment.Name.EmptyNull()), attachment.MimeType); var path = fileSystem.Combine(@"Media\QueuedEmailAttachment", fileName); fileSystem.WriteAllBytes(path, attachment.Data); } attachment.Data = null; } #pragma warning restore 612, 618 }); #endregion }
//private ICollection<Media> _media; public async Task <HttpResponseMessage> SaveMedia(HttpRequestMessage Request) { // if (!_repository.VerifyItemWritePermission(itemid)) { throw security exception } string uploadDir = HttpContext.Current.Server.MapPath("~/App_Data"); MultipartFormDataEncryptedStreamProvider provider = new MultipartFormDataEncryptedStreamProvider(uploadDir); try { //HttpResponseMessage response = new HttpResponseMessage(); StringBuilder sb = new StringBuilder(); // Holds the response body // We *COULD* accept a Note field (and exclude itemid from the URI) and create the Item here, // saving an HTTP request. Return value would be the newly-created ItemId, which the client // could then fetch and refresh the view. await Request.Content.ReadAsMultipartAsync(provider); // Process file data foreach (var file in provider.FileData) { FileInfo fileInfo = new FileInfo(file.LocalFileName); sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length)); // Create new Media record to save media details to DB Media media = _repository.Context.Media.Add(new Media()); media.FileName = fileInfo.Name; media.MimeType = file.Headers.ContentType.ToString(); media.Bytes = fileInfo.Length; // Attach new media record to its parent item Item item = _repository.Context.Items.Find(_itemId); if (null == item) { // throw security exception } else { media.Item = item; } // Create new MediaStorage record to save media storage/encryption details to DB MediaStorage mediaStorage = _repository.Context.MediaStorage.Add(new MediaStorage()); mediaStorage.LocalFileName = file.LocalFileName; // TODO: get the initialization vector from the stream provider mediaStorage.IV = Enumerable.Repeat((byte)0x00, 32).ToArray(); // Attach MediaStorage record to Media record media.MediaStorage = mediaStorage; // Save changes to the database _repository.Context.SaveChanges(); } return(new HttpResponseMessage() { Content = new StringContent(sb.ToString()) }); } catch (System.Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
//TODO: I should be able to replace this with the media readers now protected override WadoResponse DoProcess(IWadoUriRequest request, string mimeType) { var dcmLocation = MediaStorage.GetLocation(new DicomMediaId(request, MimeMediaTypes.DICOM)); //var dcmLocation = RetrieveService.RetrieveSopInstances ( request, mimeType ).FirstOrDefault(); if (!dcmLocation.Exists( )) { throw new ApplicationException("Object Not Found - return proper wado error "); } //if (string.Compare(mimeType, MimeMediaTypes.DICOM, true) == 0) { return(new WadoResponse(Location, mimeType)); } DicomFile file = new DicomFile( ); var frameIndex = request.ImageRequestInfo.FrameNumber - 1 ?? 0; frameIndex = Math.Max(frameIndex, 0); file.Load(dcmLocation.GetReadStream()); if (string.Compare(mimeType, MimeMediaTypes.Jpeg, true) == 0) { WadoResponse response = new WadoResponse(); if (file.TransferSyntax == TransferSyntax.JpegBaselineProcess1) { //ClearCanvas.Dicom.Codec.Jpeg.Jpeg8Codec codec = new ClearCanvas.Dicom.Codec.Jpeg.Jpeg8Codec (ClearCanvas.Dicom.Codec.Jpeg.JpegMode.Baseline, 0, 0 ) //codec.Encode () DicomCompressedPixelData pd = DicomPixelData.CreateFrom(file) as DicomCompressedPixelData; byte[] buffer = pd.GetFrameFragmentData(frameIndex); response.Content = new MemoryStream(buffer); response.MimeType = mimeType; return(response); } else { } } if (string.Compare(mimeType, MimeMediaTypes.UncompressedData) == 0) { WadoResponse response = null; DicomPixelData pd = null; byte[] buffer = null; response = new WadoResponse( ); pd = DicomPixelData.CreateFrom(file); buffer = pd.GetFrame(frameIndex); //********* TEST CODE*************** //System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap (pd.ImageWidth, pd.ImageHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed ) ; //System.Drawing.Imaging.ColorPalette ncp = bitmap.Palette; // for (int i = 0; i < 256; i++) // ncp.Entries[i] = System.Drawing.Color.FromArgb(255, i, i, i); // bitmap.Palette = ncp; // System.Drawing.Imaging.BitmapData data = bitmap.LockBits (new System.Drawing.Rectangle ( 0,0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); //IntPtr ptr = data.Scan0 ; //System.Runtime.InteropServices.Marshal.Copy (buffer, 0, ptr, buffer.Length ) ; //string fileName = @"C:\Users\zalsafadi_p.SPX\Downloads\libwebp-master\Output\release-static\x86\bin\Samples\uncompressed.raw" ; //bitmap.UnlockBits (data); //bitmap.Save ( fileName); //File.WriteAllBytes(fileName, buffer) ; //********* TEST CODE*************** response.Content = new MemoryStream(buffer); response.MimeType = mimeType; return(response); } //if ( string.Compare(mimeType, MimeMediaTypes.WebP) == 0) //{ // WadoResponse response = new WadoResponse ( ) ; // byte[] buffer = File.ReadAllBytes(Location) ; // response.Content = new MemoryStream(buffer); // response.MimeType = mimeType ; // return response ; //} return(null); }