public SelectDocTemplateDialog(Window owner, IEnumerable <FileBlobViewModel> templates, FileBlobViewModel defaultTemplate)
        {
            InitializeComponent();
            Owner = owner;

            _templates = new BindingList <FileBlobViewModel>();
            foreach (var item in templates)
            {
                _templates.Add(item);
            }

            // Add a no-template option.
            FileBlob noTemplate = new FileBlob(templates.First().Model.Connection);

            noTemplate.id   = -1;
            noTemplate.Name = "NONE";

            FileBlobViewModel noVm = new FileBlobViewModel(noTemplate, null);

            _templates.Insert(0, noVm);
            if (defaultTemplate == null)
            {
                _selectedTemplate = noVm;
            }
            else
            {
                _selectedTemplate = defaultTemplate;
            }
        }
Пример #2
0
        public void FileBlobTests_FailedWrite()
        {
            var      testFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            FileBlob blob     = new FileBlob(testFile.FullName);

            Assert.Null(blob.Write(null));
        }
Пример #3
0
        public async Task <IHttpActionResult> PostFileBlob()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new Exception();
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            HttpContent content  = provider.Contents.First();
            var         fileName = content.Headers.ContentDisposition.FileName.Trim('\"');
            var         buffer   = await content.ReadAsByteArrayAsync();

            var fileBlob = new FileBlob()
            {
                Id   = Guid.NewGuid(),
                Name = fileName,
                File = buffer
            };

            _db.FileBlobs.Add(fileBlob);
            await _db.SaveChangesAsync();

            return(Ok(fileBlob.Id));
        }
Пример #4
0
        public override Stream Open(FileMode mode)
        {
            if (_blobStream != null)
            {
                return(_blobStream);
            }

            switch (mode)
            {
            case FileMode.Create:
            case FileMode.CreateNew:
            case FileMode.Truncate:
                var b = FileBlob;
                if (b == null)
                {
                    //CloudContainer.GetBlockBlobReference();
                }
                return(_blobStream = FileBlob.OpenWrite());

            case FileMode.Open:
                if (!Exists || !IsFile)
                {
                    throw new ClrPlusException("Path not found '{0}'".format(AbsolutePath));
                }
                return(_blobStream = FileBlob.OpenRead());
            }
            throw new ClrPlusException("Unsupported File Mode.");
        }
Пример #5
0
        //Return Blob list in specifyed container.
        static public List <FileBlob> EnumBlobs(string containerName)
        {
            CloudBlobContainer container = GetContainerInstance(containerName);
            List <FileBlob>    files     = new List <FileBlob>();

            foreach (IListBlobItem item in container.ListBlobs(null, false))
            {
                FileBlob fileBlob = new FileBlob();
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    fileBlob.length = (int)blob.Properties.Length;
                }
                else if (item.GetType() == typeof(CloudPageBlob))
                {
                    CloudPageBlob pageBlob = (CloudPageBlob)item;
                    fileBlob.length = (int)pageBlob.Properties.Length;
                }

                string url = item.Uri.ToString();
                fileBlob.name = Helper.FileService.getFileName(url, '/');
                fileBlob.url  = url;
                fileBlob.type = getFileName(item.GetType().ToString(), '.');
                files.Add(fileBlob);
            }
            return(files);
        }
        private static void InsertBlob(DSModel db, KeyBinder key, FileBlobModel model)
        {
            key.AddRollback(model.BlobID, model, model.GetName(p => p.BlobID));
            FileBlob poco = new FileBlob();

            model.Map(poco);
            db.Add(poco);

            key.AddKey(poco, model, model.GetName(p => p.BlobID));
        }
        private void Delete(MediaData mediaData)
        {
            FileBlob blob = (FileBlob)mediaData.BinaryData;
            string   path = Path.GetDirectoryName(blob.FilePath);

            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
        }
Пример #8
0
        public void FileBlobTests_Delete()
        {
            var      testFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            FileBlob blob     = new FileBlob(testFile.FullName);

            blob.Delete();

            // Assert
            Assert.False(testFile.Exists);
        }
        private static void UpdateBlob(DSModel db, KeyBinder key, FileBlobModel model)
        {
            FileBlob poco = db.FileBlobs.Where(b => b.BlobID == model.BlobID).FirstOrDefault();

            if (poco == null)
            {
                throw new ArgumentException("File does not exist!", "BlobID");
            }
            model.Map(poco);
        }
Пример #10
0
 public void Map(FileBlob poco)
 {
     poco.BlobID          = this.BlobID;
     poco.BlobName        = this.BlobName;
     poco.BlobDescription = this.BlobDescription;
     poco.BlobExtension   = this.BlobExtension;
     poco.BlobData        = this.BlobData;
     poco.DriverID        = this.DriverID;
     poco.UserID          = this.UserID;
     poco.LastUpdateTime  = this.LastUpdateTime;
 }
Пример #11
0
        public void CheckIfDateTimeIsUpdatedOnCreate()
        {
            var item = new FileBlob {
                Id = Guid.NewGuid()
            };

            this.repo.Create(item);

            Assert.IsTrue(item.DateCreated != new DateTime());
            Assert.IsTrue(item.DateModified != new DateTime());
        }
Пример #12
0
        public void CheckIfDateTimeIsUpdatedOnUpdate()
        {
            var createTime = DateTime.Now;
            var item       = new FileBlob {
                Id = Guid.NewGuid(), DateCreated = createTime, DateModified = createTime
            };

            this.repo.Edit(item);

            Assert.IsTrue(item.DateModified != createTime);
        }
Пример #13
0
        public void ChangeFile(FileBlob file)
        {
            if (file == null)
            {
                throw new CustomArgumentException("FileBlob should be specified for Material!");
            }

            this.File = file;

            DomainEvents.Raise(new MaterialFileChangedEvent(this));
        }
        public async Task <Guid> SaveFileDataAsync(byte[] bytes, string contentType, string fileName)
        {
            var fileBlobEntity = new FileBlob(bytes, contentType, fileName);

            _unitOfWork.Repository <FileBlob>().Add(fileBlobEntity);

            await _unitOfWork.SaveChanges();

            _loggingService.Info(string.Format("Saved file {0} to persistence store", fileName));

            return(fileBlobEntity.BlobGuid);
        }
Пример #15
0
        public async Task <IActionResult> FileUpLoadAPI(IFormFile fileAPI)
        {
            var uploads = Path.Combine(_environment.WebRootPath, "/Temp/");

            uploads = @"C:\Projekt\tinkerMyCloud\src\tinkerMyCloud\Temp"; //TODO: relativ sökväg
            if (fileAPI == null)
            {
                throw new NotImplementedException();
            }
            else if (fileAPI.Length > 0)
            {
                byte[] array = new byte[0];
                using (var fileStream = new FileStream(Path.Combine(uploads, fileAPI.FileName), FileMode.Create))
                {
                    await fileAPI.CopyToAsync(fileStream);

                    // Skapa array
                    byte[] fileArray = new byte[fileStream.Length];

                    // konventera stream till array
                    fileStream.Read(fileArray, 0, System.Convert.ToInt32(fileStream.Length));

                    // sätt array utanför scope
                    array = fileArray;
                }

                // skicka api..
                var myfile = new FileBlob();
                myfile.Id       = 0;
                myfile.FileName = "testNshit";
                myfile.MimeType = "kgbShitTypeOfFile";
                myfile.FileData = array;

                var jsondata = JsonConvert.SerializeObject(myfile);

                var uri = new Uri("http://localhost:1729/api/Rest");

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpContent contentPost = new System.Net.Http.StringContent(jsondata, System.Text.Encoding.UTF8, "application/json");
                try
                {
                    var response = client.PostAsync(uri, contentPost);
                }
                catch (Exception)
                {
                    throw new NotImplementedException();
                }

                //TODO: tabort temp fil som sparas till stream..
            }
            return(View("Index"));
        }
Пример #16
0
 public FileBlobModel(FileBlob poco)
 {
     this.BlobID          = poco.BlobID;
     this.BlobName        = poco.BlobName;
     this.BlobDescription = poco.BlobDescription;
     this.BlobExtension   = poco.BlobExtension;
     this.BlobData        = poco.BlobData;
     this.DriverID        = poco.DriverID;
     this.UserID          = poco.UserID;
     this.LastUpdateTime  = poco.LastUpdateTime;
     this.IsChanged       = false;
 }
Пример #17
0
        private async void UpdateConvertedVideoMaterialAsync(long materialID, string processUrl)
        {
            if (_converter == null)
            {
                return;
            }

            // get Material from DataBase
            var material = _unitOfWork.MaterialRepository.Get(materialID);

            if (material == null || material.File == null)
            {
                return;
            }

            // get current path of the current Blob
            var sourcePath = _infrastructure.GetMaterialPath(material);

            // get the status of the convetsion
            var status = await _converter.GetStatusAsync(processUrl);

            if (status == null || !status.IsFinished || status.Output == null)
            {
                return;
            }

            // download conveted file
            var data = await _converter.DownloadAsync(processUrl);

            if (data == null)
            {
                return;
            }

            // change the filename with new extension
            string filename = material.File.FileName.Name.Replace(material.File.FileName.Extension, "." + status.Output.Extension);

            // create new Blob and attach it to the material
            material.ChangeFile(FileBlob.Create(material.Article.Code + "/", filename, "", data.Length));

            // get new path of the new Blob (where to update converted file)
            var convertedPath = _infrastructure.GetMaterialPath(material);

            // update converted file
            _infrastructure.StorageService.SaveFile(convertedPath, data);

            // save changes to DataBase
            _unitOfWork.MaterialRepository.Update(material);
            _unitOfWork.SaveChanges();

            // delete old file from Storage
            _infrastructure.StorageService.DeleteFile(sourcePath);
        }
Пример #18
0
        public bool UploadFileData(Guid id, byte[] data)
        {
            var blob = new FileBlob()
            {
                Data   = data,
                FileId = id
            };

            this.blobDataService.CreateItemWithNoReturn(blob);
            this.blobDataService.SaveChanges();

            return(true);
        }
Пример #19
0
        public void FileBlobTests_LeaseAfterDelete()
        {
            var             testFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            IPersistentBlob blob     = new FileBlob(testFile.FullName);

            var data = Encoding.UTF8.GetBytes("Hello, World!");

            blob.Write(data);
            blob.Delete();

            // Lease should return null
            Assert.Null(blob.Lease(1000));
        }
Пример #20
0
        // Saves the given file group to the database using the given connection.
        private void SaveFileGroup(FileGroup fileGroup, string xdaAddress, UserAccount userAccount)
        {
            fileGroup.ID = WebAPIHub.CreateRecord(xdaAddress, fileGroup, userAccount);

            foreach (DataFile dataFile in fileGroup.DataFiles)
            {
                dataFile.FileGroupID = fileGroup.ID;
                dataFile.ID          = WebAPIHub.CreateRecord(xdaAddress, dataFile, userAccount);

                FileBlob fileBlob = new FileBlob();
                fileBlob.DataFileID = dataFile.ID;
                fileBlob.Blob       = File.ReadAllBytes(dataFile.FilePath);
                WebAPIHub.CreateRecord(xdaAddress, fileBlob, userAccount);
            }
        }
Пример #21
0
        public Material AddMaterial(FileBlob file)
        {
            if (this.ID <= 0)
            {
                throw new CustomOperationException("Can't add material to unexisting article");
            }

            var material = Material.Create(this, file);

            this.Materials.Add(material);

            DomainEvents.Raise(new MaterialAddedToArticleEvent(this, material));

            return(material);
        }
Пример #22
0
        public void FileBlobTests_E2E_Test()
        {
            var             testFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            IPersistentBlob blob     = new FileBlob(testFile.FullName);

            var             data        = Encoding.UTF8.GetBytes("Hello, World!");
            IPersistentBlob blob1       = blob.Write(data);
            var             blobContent = blob.Read();

            Assert.Equal(testFile.FullName, ((FileBlob)blob1).FullPath);
            Assert.Equal(data, blobContent);

            blob1.Delete();
            Assert.False(testFile.Exists);
        }
Пример #23
0
        public void FileBlobTests_Lease()
        {
            var             testFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
            IPersistentBlob blob     = new FileBlob(testFile.FullName);

            var             data = Encoding.UTF8.GetBytes("Hello, World!");
            var             leasePeriodMilliseconds = 1000;
            IPersistentBlob blob1      = blob.Write(data);
            IPersistentBlob leasedBlob = blob1.Lease(leasePeriodMilliseconds);

            Assert.Contains(".lock", ((FileBlob)leasedBlob).FullPath);

            blob1.Delete();
            Assert.False(testFile.Exists);
        }
Пример #24
0
        static public FileBlobModel ToSerial(this FileBlob blob)
        {
            if (blob == null)
            {
                return(null);
            }

            return(new FileBlobModel()
            {
                //FileID = blob.ID,
                Code = blob.Code,
                FileName = blob.FileName,
                Size = blob.Size
            });
        }
Пример #25
0
        private void SyncFileBlobs(string address, int localDataFileId, int remoteDataFileId)
        {
            FileBlob local  = DataContext.Table <FileBlob>().QueryRecordWhere("DataFileID = {0}", localDataFileId);
            FileBlob remote = (FileBlob)WebAPIHub.GetRecordsWhere(address, "FileBlob", $"DataFileID = {remoteDataFileId}").FirstOrDefault();

            if (local != null && remote == null)
            {
                FileBlob record = new FileBlob()
                {
                    DataFileID = remoteDataFileId,
                    Blob       = local.Blob
                };
                WebAPIHub.CreateRecord(address, "FileBlob", JObject.FromObject(record));
            }
        }
Пример #26
0
        public static GenericFolder Open(string path)
        {
            var file   = File.OpenRead(path);
            var header = new ByteBuffer(file.Read(36));

            if (header.GetU32() != Signature)
            {
                Program.LogWarning("File is not an IFS file.");
                return(null);
            }

            var version = header.GetU16();

            if ((header.GetU16() ^ version) != 0xFFFF)
            {
                Program.LogWarning("File version check failed.");
                return(null);
            }

            header.GetU32();             // time
            header.GetU32();             // ifs size
            var manifestEnd = header.GetU32();
            var dataBlob    = new FileBlob(file, manifestEnd);

            if (version > 1)
            {
                header.Offset += 16;
            }

            file.Seek(header.Offset, SeekOrigin.Begin);
            var manifest = new XDocument();

            try {
                manifest = new KBinReader(file.Read((int)(manifestEnd - header.Offset))).Document;
            } catch (Exception ex) {
                Program.LogWarning($"Error during manifest decoding: {ex}");
            }

            var root = new GenericFolder(dataBlob, manifest, null, path, Path.GetFileName(path));

            try {
                root.FromXml();
            } catch (Exception ex) {
                Program.LogWarning("Exception during ifs unpack: {0}", ex);
            }

            return(root);
        }
Пример #27
0
        public async Task RemoveFileDataAsyncCallsCorrectUnitOfWorkMethodsTest()
        {
            var entity = new FileBlob();

            var mockUnitOfWork    = new Mock <IUnitOfWork>();
            var mockLoggerService = new Mock <ILoggerService>();

            mockUnitOfWork.Setup(x => x.Repository <FileBlob>().GetAsync(It.IsAny <Expression <Func <FileBlob, bool> > >()))
            .Returns(() => Task.FromResult(entity));

            var persistenceService = new FilesPersistenceService(mockUnitOfWork.Object, mockLoggerService.Object);
            await persistenceService.DeleteFileDataAsync(It.IsAny <Guid>());

            mockUnitOfWork.Verify(m => m.Repository <FileBlob>().Remove(entity), Times.Once);
            mockUnitOfWork.Verify(m => m.SaveChanges(), Times.Once);
        }
Пример #28
0
        private void BtnUpload_Click(object sender, EventArgs e)
        {
            var uploads = LvLocalList.SelectedItems
                          .OfType <ListViewItem>().Select(x => x.Tag)
                          .OfType <IWMPMedia>().Select(x => x.sourceURL);

            foreach (var path in uploads)
            {
                var file = new FileBlob()
                {
                    Name = Path.GetFileName(path),
                    Body = File.ReadAllBytes(path)
                };
                WriteQueues.Enqueue(file);
            }
        }
Пример #29
0
        public async Task <IActionResult> UploadFileSet([FromBody] FileBlob item)
        {
            if (item == null)
            {
                return(BadRequest());
            }
            bool add = await _businessLayer.AddFileUsingExAPI(item);

            if (add)
            {
                return(new ObjectResult("Sucess"));
            }
            else
            {
                return(new ObjectResult("Api error - when trying to add object."));
            }
        }
Пример #30
0
        public void AddFile()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog().Value)
            {
                NameItemDialog nameDialog   = new NameItemDialog(DialogOwner, "New File");
                bool?          dialogResult = nameDialog.ShowDialog();
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    FileBlob file = new FileBlob(UniverseVm.Model.Connection);
                    file.Name       = nameDialog.UserInput;
                    file.FileName   = Path.GetFileName(openFileDialog.FileName);
                    file.UniverseId = UniverseVm.Model.id;

                    string extension = Path.GetExtension(openFileDialog.FileName).ToLower();

                    if (extension == ".png")
                    {
                        file.FileType = FileBlob.FILE_TYPE_PNG;
                    }
                    else if (extension == ".jpg" || extension == ".jpeg")
                    {
                        file.FileType = FileBlob.FILE_TYPE_JPEG;
                    }
                    else if (extension == ".dotx")
                    {
                        file.FileType = FileBlob.FILE_TYPE_TEMPLATE;
                    }
                    else
                    {
                        file.FileType = FileBlob.FILE_TYPE_OTHER;
                    }

                    if (Files.Count > 0)
                    {
                        file.SortIndex = Files.Max(i => i.Model.SortIndex) + 1;
                    }
                    file.Create();
                    file.LoadFile(openFileDialog.FileName);

                    FileBlobViewModel vm = new FileBlobViewModel(file, this);
                    Files.Add(vm);
                }
            }
        }