Пример #1
0
        public static FileEntity[] GetDirectoryFiles(string strPathBase)
        {
            if (!strPathBase.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                strPathBase += Path.DirectorySeparatorChar;
            }
            var targetFolder = new DirectoryInfo(strPathBase);
            if ((targetFolder.Exists == false))
            {
                return new FileEntity[0];
            }

            var objArrayFileEntity = new FileEntity[targetFolder.GetFiles().Length];
            FileEntity objFileEntity;

            for (int i = 0; i < targetFolder.GetFiles().Length; i++)
            {
                objFileEntity = new FileEntity();
                objFileEntity.Name = targetFolder.GetFiles()[i].Name;
                objFileEntity.IsReadOnly = targetFolder.GetFiles()[i].IsReadOnly;
                objFileEntity.DirectoryName = strPathBase;
                objFileEntity.Extension = targetFolder.GetFiles()[i].Extension;

                objArrayFileEntity[i] = objFileEntity;
            }

            return objArrayFileEntity;
        }
 private void moveFileToArchive(FileEntity file)
 {
     if (!Directory.Exists(file.ContainingFolder + @"\Archive\"))
         Directory.CreateDirectory(file.ContainingFolder + @"\Archive\");
     var destPath = file.ContainingFolder + @"\Archive\" + file.FileName;
     _fileUtil.MoveFileWithOverwrite(file.FullPath, destPath);
     File.Move(destPath, getNewPath(file, @"\Archive\"));
 }
Пример #3
0
        public void file_entity_can_handle_full_path()
        {
            var fe = new FileEntity();
            Assert.That(fe.FileName == "");
            Assert.That(fe.ContainingFolder == "");
            fe.FullPath = @"c:\pagefile.sys";

            Assert.That(fe.FileName == "pagefile.sys");
            Assert.That(fe.ContainingFolder == @"c:\");
        }
Пример #4
0
        public void Load_ReadRealAttribute()
        {
            var entity = new FileEntity("test")
                         .SetAttribute(new Attribute("attr", new RealValue(3.1415), AttributeSource.Custom));

            var result = _storage.Load("test");

            Assert.IsNull(result);

            _storage.Store(entity);
            _storage.ApplyChanges();

            result = _storage.Load("test");
            Assert.IsNotNull(result);
            Assert.AreEqual(3.1415, result.GetValue <RealValue>("attr").Value);
        }
Пример #5
0
        public async Task LoadNativeThumbnailAsync_ProcessCanceledRequest()
        {
            var cancellation = new CancellationTokenSource();

            cancellation.Cancel();
            var entity = new FileEntity("test");

            var tasks = new Task[100];

            for (var i = 0; i < tasks.Length; ++i)
            {
                tasks[i] = _loader.LoadNativeThumbnailAsync(entity, new Size(1, 1), cancellation.Token);
            }

            await Task.WhenAll(tasks);
        }
Пример #6
0
        public FileEntity CreateFileEntity(byte[] stream, string fileName, bool isPublic, Guid ownerId, long size, string filePath)
        {
            var file = new FileEntity()
            {
                // Id = Guid.NewGuid(),
                Data       = stream,
                Name       = fileName,
                IsPublic   = isPublic,
                OwnerId    = ownerId,
                Path       = filePath,
                Size       = size,
                UploadDate = DateTime.Now
            };

            return(file);
        }
Пример #7
0
        private bool SaveFileInfo(int entityId, string fileName, EditionFileType editionFileType, string extension, string langCode)
        {
            var fileEntity = new FileEntity
            {
                FileName          = fileName,
                FileExtension     = extension,
                EntityId          = entityId,
                EntityType        = EntityType.Edition.GetDescription(),
                EditionFileType   = editionFileType,
                LanguageCode      = langCode,
                CreatedByFullName = CurrentCedUser.CurrentUser.FullName,
                CreatedByEmail    = CurrentCedUser.CurrentUser.Email
            };

            return(FileServices.CreateFile(fileEntity, 1));
        }
Пример #8
0
        /// <summary>
        /// Метод CreateSubFolder добавляет в базу данных информацию о подкаталоге каталога root с именем name
        /// </summary>
        /// <param name="root"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool CreateSubFolder(FileEntity root, string name)
        {
            if (GetFileId(root.FullName + '\\' + name) != -1)
            {
                throw new ArgumentException("Существующее имя каталога.", "Name");
            }
            bool r = true;

            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("INSERT INTO MegaFileStorage.Files (OwnerID, FileName, Extension,"
                                                    + " UploadDate, FullName, AccessType, Size) VALUES(@oid, @n, @e, @ud, @fn, @at, @s)");
                command.Connection = connection;
                command.Parameters.AddWithValue("@oid", root.Owner.ID);
                command.Parameters.AddWithValue("@n", name);
                command.Parameters.AddWithValue("@e", "folder");
                command.Parameters.AddWithValue("@ud", DateTime.Now);
                command.Parameters.AddWithValue("@fn", root.FullName + '\\' + name);
                command.Parameters.AddWithValue("@at", 0);
                command.Parameters.AddWithValue("@s", 0);

                connection.Open();

                r &= command.ExecuteNonQuery() == 1;
            }

            if (!r)
            {
                return(r);
            }

            int chid = GetFileId(root.FullName + '\\' + name);

            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("INSERT INTO MegaFileStorage.Folders (ChID, ParID) VALUES(@cd, @pd)");
                command.Connection = connection;
                command.Parameters.AddWithValue("@cd", chid);
                command.Parameters.AddWithValue("@pd", root.Id);

                connection.Open();

                r &= command.ExecuteNonQuery() == 1;
            }

            return(r);
        }
Пример #9
0
        /// <summary>
        /// Метод AddFile добавляет информацию о файле в базу данных
        /// </summary>
        /// <param name="parid"></param>
        /// <param name="file"></param>ww
        /// <returns></returns>
        public bool AddFile(int parid, FileEntity file)
        {
            bool r;

            if (GetFileByFullName(file.FullName) != null)
            {
                throw new ArgumentException("Файл с таким именем уже существует.", "UploadedFile");
            }
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("INSERT INTO MegaFileStorage.Files (OwnerID, FileName, Extension, "
                                                    + "Size, UploadDate, Downloads, FullName, AccessType, ContentType) VALUES(@oid, @n, @e, @s, @ud, "
                                                    + "@d, @fn, @at, @ct)");
                command.Connection = connection;
                command.Parameters.AddWithValue("@oid", file.Owner.ID);
                command.Parameters.AddWithValue("@n", file.Name);
                command.Parameters.AddWithValue("@e", file.Extension);
                command.Parameters.AddWithValue("@s", file.Size);
                command.Parameters.AddWithValue("@ud", file.UploadDate);
                command.Parameters.AddWithValue("@d", file.Downloads);
                command.Parameters.AddWithValue("@fn", file.FullName);
                command.Parameters.AddWithValue("@at", file.Access);
                command.Parameters.AddWithValue("@ct", file.ContentType);

                connection.Open();

                r = command.ExecuteNonQuery() == 1;
                if (!r)
                {
                    return(r);
                }
            }

            int chid = GetFileByFullName(file.FullName).Id;

            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("INSERT INTO MegaFileStorage.Folders (ChID, ParID) VALUES(@c, @p)");
                command.Connection = connection;
                command.Parameters.AddWithValue("@c", chid);
                command.Parameters.AddWithValue("@p", parid);

                connection.Open();

                return(command.ExecuteNonQuery() == 1);
            }
        }
Пример #10
0
        //主子表保存
        public void SubmitForm(ProductEntity productEntity, string keyValue, List <ProductSubEntity> listProductSub)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                productEntity.Modify(keyValue);
            }
            else
            {
                productEntity.Create();
            }
            List <ProductSubEntity> listProductSubUpdate = new List <ProductSubEntity>();
            List <FileEntity>       listFile             = new List <FileEntity>();

            foreach (var itemId in listProductSub)
            {
                ProductSubEntity productSubEntity = new ProductSubEntity();
                productSubEntity.F_ParentId      = productEntity.F_Id;
                productSubEntity.Attribute       = itemId.Attribute;
                productSubEntity.PictureGuId     = itemId.PictureGuId;
                productSubEntity.SKU             = itemId.SKU;
                productSubEntity.Supplier        = itemId.Supplier;
                productSubEntity.PurchaseAddress = itemId.PurchaseAddress;
                productSubEntity.HWeight         = itemId.HWeight;
                productSubEntity.GWeight         = itemId.GWeight;
                productSubEntity.SWeight         = itemId.SWeight;
                productSubEntity.Long            = itemId.Long;
                productSubEntity.Wide            = itemId.Wide;
                productSubEntity.High            = itemId.High;
                productSubEntity.PurchaseCost    = itemId.PurchaseCost;
                productSubEntity.TransportCost   = itemId.TransportCost;
                productSubEntity.OtherCost       = itemId.OtherCost;
                productSubEntity.F_Description   = itemId.F_Description;
                productSubEntity.Create();
                var      guid  = productSubEntity.F_Id;
                string[] files = itemId.PictureGuId.Split(',');
                foreach (string f in files)
                {
                    FileEntity file = new FileEntity();
                    file.F_ParentId = guid;
                    file.F_File     = f;
                    file.Create();
                    listFile.Add(file);
                }
                listProductSubUpdate.Add(productSubEntity);
            }
            service.SubmitForm(productEntity, listProductSubUpdate, keyValue);
        }
        public void Execute_SelectedEntitiesHasTwoRsaFiles()
        {
            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(x => x.Exists).Returns(true);
            fileInfo.Setup(x => x.Extension).Returns(".rsa");

            var fileEntity         = new FileEntity(fileInfo.Object);
            var fileSystemEntities = new ReadOnlyCollection <FileSystemEntity>(new[] { fileEntity, fileEntity });

            filesView.Setup(x => x.SelectedEntities).Returns(fileSystemEntities);

            command.Execute();

            Assert.IsTrue(cryptoView.Object.CipherEnabled);
            Assert.IsFalse(cryptoView.Object.DecipherEnabled);
        }
Пример #12
0
        public async Task <int> CreateFile(string fileName, DateTime time)
        {
            if (time == null)
            {
                throw new ArgumentNullException(nameof(time));
            }

            FileEntity entity = new FileEntity {
                Name = fileName, SaveTime = time
            };

            _context.Files.Add(entity);

            await _context.SaveChangesAsync();

            return(entity.Id);
        }
        private FileEntity CreateFileEntity(FileDto fileData, int locationId)
        {
            var entity = new FileEntity
            {
                TripId      = fileData.TripId,
                Uri         = fileData.Uri,
                Type        = (int)fileData.Type,
                Description = fileData.Description,
                IsPrivate   = fileData.IsPrivate,
                UserId      = fileData.UserId,
                FileName    = fileData.FileName
            };

            // TODO: Lab 9, Exercise 2, Task 1.4: Set the entity's partition key and row key

            return(entity);
        }
Пример #14
0
        public void Load_NonCachedEntity()
        {
            var entity = new FileEntity("test");

            _cacheStorage
            .Setup(mock => mock.Load("test"))
            .Returns((IEntity)null);
            _persistentStorage
            .Setup(mock => mock.Load("test"))
            .Returns(entity);

            var result = _storage.Load("test");

            Assert.AreEqual(result, entity);

            _cacheStorage.Verify(mock => mock.Store(entity), Times.Once);
        }
Пример #15
0
        public void Load_ReadDateTimeAttribute()
        {
            var entity = new FileEntity("test")
                         .SetAttribute(new Attribute("attr", new DateTimeValue(new DateTime(2018, 8, 25)),
                                                     AttributeSource.Custom));

            var result = _storage.Load("test");

            Assert.IsNull(result);

            _storage.Store(entity);
            _storage.ApplyChanges();

            result = _storage.Load("test");
            Assert.IsNotNull(result);
            Assert.AreEqual(new DateTime(2018, 8, 25), result.GetValue <DateTimeValue>("attr").Value);
        }
        public void Constructor_CheckSetInputFileEntities()
        {
            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(x => x.Exists).Returns(true);
            fileInfo.Setup(x => x.Length).Returns(100);
            fileInfo.Setup(x => x.FullName).Returns("file.jpg");
            fileInfo.Setup(x => x.Extension).Returns(".jpg");

            var fileEntity = new FileEntity(fileInfo.Object);

            cipherForm.SetupProperty(x => x.InputFileEntities, new FileSystemEntity[0]);
            CreatePresenter(new[] { fileEntity });

            Assert.AreEqual(1, cipherForm.Object.InputFileEntities.Count());
            Assert.AreEqual(fileEntity, cipherForm.Object.InputFileEntities.ElementAt(0));
        }
Пример #17
0
        public FileEntity UploadImageThumbnailByWidth
            (HttpPostedFile fileData, string fileFolder, string physicalpath, int width, int height, string prefix = "")
        {
            ThumnailMode mode     = ThumnailMode.EqualW;
            string       fileType = "jpg";

            FileEntity file = new FileEntity();

            if (fileData != null)
            {
                try
                {
                    string filePath = physicalpath + "/";
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    file.DisplayName = Path.GetFileName(fileData.FileName);
                    file.Extension   = Path.GetExtension(file.DisplayName);
                    file.Size        = fileData.ContentLength;
                    file.ContentType = fileData.ContentType;
                    file.CreateTime  = DateTime.Now;
                    file.DbName      = GetFileDBName(file.Extension);
                    file.FilePath    = "/" + fileFolder + "/" + file.DbName;

                    Image image     = Image.FromStream(fileData.InputStream);
                    int   outWidth  = 0;
                    int   outHeight = 0;
                    ThumbnailHelper.CreateOutWAndH(image, filePath + file.DbName, width, height, mode, fileType, out outWidth, out outHeight);

                    file.ImageWidth  = outWidth;
                    file.ImageHeight = outHeight;

                    return(file);
                }
                catch (Exception ex)
                {
                    WebLogAgent.Write(ex);
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Пример #18
0
 public async Task DeleteFile(int id)
 {
     try
     {
         FileEntity file = new FileEntity()
         {
             FileId = id
         };
         this.context.Files.Attach(file);
         this.context.Remove(file);
         await this.context.SaveChangesAsync();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Пример #19
0
        private void StartCopy()
        {
            FileEntity entity = new FileEntity();

            if (entity != null)
            {
                cbFrom.Invoke(new Action(() => entity.From = cbFrom.Text));
                cbTo.Invoke(new Action(() => entity.To     = cbTo.Text));

                Console.WriteLine(entity.From);
                fileManager.Initialize(entity.From, entity.To);
            }
            else
            {
                MessageBox.Show("Do not blank");
            }
        }
Пример #20
0
        public async Task <IEnumerable <FileEntity> > SaveAsync(IEnumerable <IFormFile> files, CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new ContentDeveloperRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            var list = new List <FileEntity>();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var filePath = $"{_options.LocalDirectory}{formFile.FileName}";
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        // write file
                        await formFile.CopyToAsync(stream);

                        // not a zip? zip it!
                        if (!Path.GetExtension(formFile.FileName).Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            filePath = this.Zip(filePath, formFile.FileName);
                        }

                        //build return obj
                        var item = new FileEntity();
                        item.Name        = formFile.Name;
                        item.Length      = formFile.Length;
                        item.DateCreated = DateTime.UtcNow;
                        item.StoragePath = filePath;
                        list.Add(item);
                    }
                }
            }

            //save to db
            if (list.Count > 0)
            {
                _context.Files.AddRange(list);
                await _context.SaveChangesAsync(ct);
            }

            return(list);
        }
Пример #21
0
        /// <inheritdoc />
        /// <summary>
        /// Load attributes from given file.
        /// Read algorithm:
        /// <list type="number">
        ///     <item>
        ///         <description>
        ///         read all JPEG segments to memory (using reaader returned by
        ///         <see cref="IJpegSegmentReaderFactory"/>)
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <description>
        ///         decode data in JPEG segments (using readers returned by all
        ///         <see cref="IAttributeReaderFactory"/>) to attributes
        ///         </description>
        ///     </item>
        /// </list>
        /// </summary>
        /// <param name="path">Path to a file</param>
        /// <returns>Collection of attributes read from the file</returns>
        public IEntity Load(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            try
            {
                if (_fileSystem.DirectoryExists(path))
                {
                    return(new DirectoryEntity(path));
                }

                // read all JPEG segments to memory
                IEntity entity   = new FileEntity(path);
                var     fileInfo = new FileInfo(path);
                var     segments = ReadJpegSegments(path);

                // read attributes from all sources and add them to the collection
                foreach (var factory in _attrReaderFactories)
                {
                    var attrReader = factory.CreateFromSegments(fileInfo, segments);
                    for (;;)
                    {
                        var attr = attrReader.Read();
                        if (attr == null)
                        {
                            break;
                        }
                        entity = entity.SetAttribute(attr);
                    }
                }

                return(entity);
            }
            catch (FileNotFoundException)
            {
                return(null);
            }
            catch (DirectoryNotFoundException)
            {
                return(null);
            }
        }
        public void Search(FileEntity selectedfileEntity = null)
        {
            string parentId = selectedfileEntity == null ? null : selectedfileEntity.ParentID + "/" + selectedfileEntity.FileName; //这里只认/方向的斜线,所有不能用Path.Comebine
            Thread th       = new Thread(() => {
                DropboxFileSearch dropboxFileSearch = new DropboxFileSearch();
                dropboxFileSearch.SearchFile(ServiceManager.Instence().DropboxClient,
                                             t => {
                    //防止重复加载已经请求的数据
                    if (selectedfileEntity != null && selectedfileEntity.ChildFileList != null)
                    {
                        if (selectedfileEntity.ChildFileList.FirstOrDefault(f => f.FileId == t.FileId) != null)
                        {
                            return;
                        }
                    }
                    FileEntity fileEntity = new FileEntity()
                    {
                        ParentID = t.ParentId,
                        FileId   = t.FileId,
                        FileName = t.FileName,
                        FileSize = t.FileSize,
                        IsFile   = t.IsFile
                    };
                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        //root目录
                        if (selectedfileEntity == null)
                        {
                            _detailVM.Add(fileEntity);
                        }
                        else
                        {
                            if (selectedfileEntity.ChildFileList == null)
                            {
                                selectedfileEntity.ChildFileList = new ObservableCollection <FileEntity>();
                            }
                            ((ObservableCollection <FileEntity>)selectedfileEntity.ChildFileList).Add(fileEntity);
                        }
                    }));
                }, parentId);
            });

            th.Name = "SearchDropboxFileThread";
            th.Start();
        }
Пример #23
0
        public FileEntity DESEncryptUploadFileReturnFileEntity(HttpPostedFile fileData, string fileFolder, string filePhysicalPath, string virtualDir = "")
        {
            FileEntity file = new FileEntity();

            if (fileData != null)
            {
                try
                {
                    string filePath = filePhysicalPath + "/";
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    file.DisplayName = Path.GetFileName(fileData.FileName);
                    file.Extension   = Path.GetExtension(file.DisplayName);
                    file.Size        = fileData.ContentLength;
                    file.ContentType = fileData.ContentType;
                    file.CreateTime  = DateTime.Now;
                    file.DbName      = GetFileDBName(file.Extension);
                    file.FilePath    = "/" + fileFolder + "/" + file.DbName;
                    file.FullPath    = virtualDir + file.FilePath;
                    string desKey = "sunneTUs";
                    string desIV  = "sunneT.U";
                    byte[] bytes  = new byte[fileData.InputStream.Length];
                    fileData.InputStream.Read(bytes, 0, bytes.Length);
                    fileData.InputStream.Close();
                    FileStream   fileStream   = new FileStream(filePath + file.DbName, FileMode.OpenOrCreate, FileAccess.Write);
                    DES          des          = new DESCryptoServiceProvider();
                    CryptoStream cryptoStream = new CryptoStream(fileStream, des.CreateEncryptor(Encoding.Default.GetBytes(desKey), Encoding.Default.GetBytes(desIV)), CryptoStreamMode.Write);
                    cryptoStream.Write(bytes, 0, bytes.Length);
                    cryptoStream.Close();
                    fileStream.Close();
                    return(file);
                }
                catch (Exception ex)
                {
                    WebLogAgent.Write(ex);
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Пример #24
0
        public void Read(string path)
        {
            FileEntity f = new FileEntity(path, "UTF-8");

            f.Read();
            Condition c_function = new Condition();

            c_function.Add(PATTERN_LABEL_FUNCTIONS, false);
            c_function.Add(PATTERN_LABEL, false);
            Condition c_packageBody = new Condition();

            c_packageBody.Add(PATTERN_LABEL_PACKAGEBODIES, false);
            c_packageBody.Add(PATTERN_LABEL, false);
            Condition c_package = new Condition();

            c_package.Add(PATTERN_LABEL_PACKAGES, false);
            c_package.Add(PATTERN_LABEL, false);
            Condition c_procedure = new Condition();

            c_procedure.Add(PATTERN_LABEL_PROCEDURES, false);
            c_procedure.Add(PATTERN_LABEL, false);
            Condition c_trigger = new Condition();

            c_trigger.Add(PATTERN_LABEL_TRIGGERS, false);
            c_trigger.Add(PATTERN_LABEL, false);
            Condition c_view = new Condition();

            c_view.Add(PATTERN_LABEL_VIEWS, false);
            c_view.Add(PATTERN_LABEL, false);
            for (int i = 0; f.RowCount > i; ++i)
            {
                c_function.Test(f.Get[i], i);
                c_packageBody.Test(f.Get[i], i);
                c_package.Test(f.Get[i], i);
                c_procedure.Test(f.Get[i], i);
                c_trigger.Test(f.Get[i], i);
                c_view.Test(f.Get[i], i);
            }
            Pick(Functions, c_function);
            Pick(PackageBodies, c_packageBody);
            Pick(Packages, c_package);
            Pick(Procedures, c_procedure);
            Pick(Triggers, c_trigger);
            Pick(Views, c_view);
        }
Пример #25
0
        public SiteEntity Site(Domain.Model.File.Type type)
        {
            var siteEntity = new SiteEntity();


            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_url);

            req.Method    = "GET";
            req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
            req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            string sourceTaken;

            using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                sourceTaken = reader.ReadToEnd();
            }

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(sourceTaken);

            Trace.WriteLine(doc.DocumentNode.ChildNodes.Descendants("video").Count());
            var descendantsList = type == File.Type.Image ? doc.DocumentNode.Descendants("img") : doc.DocumentNode.Descendants("video");

            // For every tag in the HTML containing the node img.
            foreach (var link in descendantsList
                     .Select(i => !string.IsNullOrEmpty(i.Attributes["src"].Value) ? i.Attributes["src"] : i.Attributes["source"]))
            {
                // Storing all links found in an array.
                // You can declare this however you want.
                var editedUrl = link.Value;
                if (!IsAbsoluteUrl(link.Value))
                {
                    var removeString = _url.Split("/")[_url.Split("/").Length - 1];
                    editedUrl  = _url;
                    editedUrl  = editedUrl.Replace(removeString, "");
                    editedUrl += link.Value;
                }

                var file = new FileEntity(editedUrl, null, type);
                siteEntity.FileEntitys.Add(file);
            }

            return(siteEntity);
        }
Пример #26
0
            protected void GetDirectoryFiles()
            {
                var targetFolder = new DirectoryInfo(FullPath);

                FileInfo[] strArrayFile = targetFolder.GetFiles();

                _files = new FileEntity[strArrayFile.Length];
                FileEntity objFileEntity;

                //SE CARGA SOLO LA EXTENSION DE BUSQUEDA
                if (_fileSearchExtension != null && _fileSearchExtension.Length > 0)
                {
                    int indice = 0;
                    for (int i = 0; i < strArrayFile.Length; i++)
                    {
                        if (IsValidExtension(strArrayFile[i].Extension))
                        {
                            objFileEntity               = new FileEntity();
                            objFileEntity.Name          = strArrayFile[i].Name;
                            objFileEntity.IsReadOnly    = strArrayFile[i].IsReadOnly;
                            objFileEntity.DirectoryName = FullPath;
                            objFileEntity.Extension     = strArrayFile[i].Extension;

                            _files[indice] = objFileEntity;
                            indice++;
                        }
                    }

                    Array.Resize(ref _files, indice);

                    return;
                }

                //SE CARGAN TODOS LOS TIPOS DE EXTENSIONES
                for (int i = 0; i < strArrayFile.Length; i++)
                {
                    objFileEntity               = new FileEntity();
                    objFileEntity.Name          = strArrayFile[i].Name;
                    objFileEntity.IsReadOnly    = strArrayFile[i].IsReadOnly;
                    objFileEntity.DirectoryName = FullPath;
                    objFileEntity.Extension     = strArrayFile[i].Extension;

                    _files[i] = objFileEntity;
                }
            }
Пример #27
0
        public void CompareTwoFiles()
        {
            var firstFileInfo = new Mock <IFileInfo>();

            firstFileInfo.Setup(x => x.Exists).Returns(true);
            firstFileInfo.Setup(x => x.Length).Returns(100);
            var firstFile = new FileEntity(firstFileInfo.Object);

            var secondFileInfo = new Mock <IFileInfo>();

            secondFileInfo.Setup(x => x.Exists).Returns(true);
            secondFileInfo.Setup(x => x.Length).Returns(50);
            var secondFile = new FileEntity(secondFileInfo.Object);

            var compareResult = comparer.Compare(firstFile, secondFile);

            Assert.AreEqual(1, compareResult);
        }
        public void CancelCipher_ProcessIsNotStarting()
        {
            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(x => x.Exists).Returns(true);
            fileInfo.Setup(x => x.FullName).Returns("hello.rsa");
            fileInfo.Setup(x => x.Extension).Returns(".rsa");

            var fileEntity = new FileEntity(fileInfo.Object);

            decipherForm.SetupProperty(x => x.DialogResult, DialogResult.None);

            CreatePresenter(fileEntity);

            decipherForm.Raise(x => x.CancelDecipher += null, EventArgs.Empty);

            Assert.AreEqual(DialogResult.Cancel, decipherForm.Object.DialogResult);
        }
        public void Constructor_CheckSetOutputDirectoryPath()
        {
            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(x => x.Exists).Returns(true);
            fileInfo.Setup(x => x.Extension).Returns(".rsa");
            fileInfo.Setup(x => x.FullName).Returns("c:\\file.rsa");

            var initialFile = new FileEntity(fileInfo.Object);

            decipherForm.SetupProperty(x => x.OutputDirectoryPath);
            var rsaFileDecipher = new Mock <IRsaFileDecipher>();

            rsaFactory.Setup(x => x.CreateRsaFileDecipher(initialFile.FullName)).Returns(rsaFileDecipher.Object);
            CreatePresenter(initialFile);

            Assert.AreEqual("c:\\file", decipherForm.Object.OutputDirectoryPath);
        }
        public void Union_FileEntityDoesNotExist()
        {
            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(x => x.Exists).Returns(true);
            var fileName = Path.Combine(testFolder, "file.exe");

            fileInfo.Setup(x => x.FullName).Returns(fileName);

            var fileEntity = new FileEntity(fileInfo.Object);

            fileInfo.Setup(x => x.Exists).Returns(false);
            var fileSystemEntities = new[] { fileEntity };

            var destinationFileName = Path.Combine(testFolder, "destination.zip");

            Assert.Throws(typeof(FileNotFoundException), () => unifier.Union(fileSystemEntities, destinationFileName));
        }
        public ActionResult NewFolder(Models.NewFolderModel newfolder)
        {
            if (ModelState.IsValid)
            {
                FileEntity ParentFolder = Logic.GetFileById(newfolder.ParentId);
                try
                {
                    Logic.CreateSubfolder(ParentFolder, newfolder.Name);
                    return(Redirect("~/Account/Storage?id=" + ParentFolder.Id));
                }
                catch (ArgumentException e)
                {
                    ModelState.AddModelError(e.ParamName, e.Message);
                }
            }

            return(View(newfolder));
        }
Пример #32
0
        private FileEntity CreateFileEntity(FileDto fileData, int locationId)
        {
            var entity = new FileEntity
            {
                TripId      = fileData.TripId,
                Uri         = fileData.Uri,
                Type        = (int)fileData.Type,
                Description = fileData.Description,
                IsPrivate   = fileData.IsPrivate,
                UserId      = fileData.UserId,
                FileName    = fileData.FileName
            };

            // TODO: Lab 9, Exercise 2, Task 1.4: Set the entity's partition key and row key
            entity.PartitionKey = locationId.ToString();
            entity.RowKey       = HttpUtility.UrlEncode(fileData.Uri.ToString());
            return(entity);
        }
        private FileEntity CreateFileEntity(FileDto fileData)
        {
            // TODO: Exercise 1: Task 5d: create a new FileEntity based on the file data
            var entity = new FileEntity
            {
                RowKey       = HttpUtility.UrlEncode(fileData.Uri.ToString()),
                PartitionKey = fileData.LocationId.ToString(),
                TripId       = fileData.TripId,
                Uri          = fileData.Uri,
                Type         = (int)fileData.Type,
                Description  = fileData.Description,
                IsPrivate    = fileData.IsPrivate,
                UserId       = fileData.UserId,
                FileName     = fileData.FileName
            };

            return(entity);
        }
Пример #34
0
        public void AddImage(Stream input, File file)
        {
            // validate image
            Image.FromStream(input);

            var fileName = GenerateFileName(file.CreatedBy.Id, input.Length);

            input.SaveToFile(fileName);

            var entity = new FileEntity
            {
                FileName = fileName,
                Description = file.Description,
                ContentLength = file.ContentLength,
                ContentType = file.ContentType,
                UserId = file.CreatedBy.Id,
                InsertDate = DateTime.Now,
            };

            _context.Files.AddObject(entity);
            _context.SaveChanges();

            file.Id = entity.Id;
        }
Пример #35
0
            protected void GetDirectoryFiles()
            {
                var targetFolder = new DirectoryInfo(FullPath);
                FileInfo[] strArrayFile = targetFolder.GetFiles();

                _files = new FileEntity[strArrayFile.Length];
                FileEntity objFileEntity;

                //SE CARGA SOLO LA EXTENSION DE BUSQUEDA
                if (_fileSearchExtension != null && _fileSearchExtension.Length > 0)
                {
                    int indice = 0;
                    for (int i = 0; i < strArrayFile.Length; i++)
                    {
                        if (IsValidExtension(strArrayFile[i].Extension))
                        {
                            objFileEntity = new FileEntity();
                            objFileEntity.Name = strArrayFile[i].Name;
                            objFileEntity.IsReadOnly = strArrayFile[i].IsReadOnly;
                            objFileEntity.DirectoryName = FullPath;
                            objFileEntity.Extension = strArrayFile[i].Extension;

                            _files[indice] = objFileEntity;
                            indice++;
                        }
                    }

                    Array.Resize(ref _files, indice);

                    return;
                }

                //SE CARGAN TODOS LOS TIPOS DE EXTENSIONES
                for (int i = 0; i < strArrayFile.Length; i++)
                {
                    objFileEntity = new FileEntity();
                    objFileEntity.Name = strArrayFile[i].Name;
                    objFileEntity.IsReadOnly = strArrayFile[i].IsReadOnly;
                    objFileEntity.DirectoryName = FullPath;
                    objFileEntity.Extension = strArrayFile[i].Extension;

                    _files[i] = objFileEntity;
                }
            }
 public DocumentFile(FileEntity f, EdiSegmentCollection segs)
 {
     Segments = segs;
     File = f;
 }
        public DocumentEntity ParseEdrmDocumentXml(string sDocumentEntity)
        {
            DocumentEntity documentEntity = new DocumentEntity();
            XmlReader xmlReader = XmlReader.Create(new StringReader(sDocumentEntity));

            while (xmlReader.Read())
            {
                // set these values only if they were not already set.
                if (string.IsNullOrEmpty(documentEntity.MIMEType)) documentEntity.MIMEType = xmlReader.SafeGetAttribute("MimeType");
                if (string.IsNullOrEmpty(documentEntity.DocumentID)) documentEntity.DocumentID = xmlReader.SafeGetAttribute("DocID");

                if (xmlReader.Name.Equals("tag", StringComparison.InvariantCultureIgnoreCase))
                {
                    #region Parse all Tag elements
                    documentEntity.Tags.Add(new TagEntity()
                    {
                        TagName = xmlReader.SafeGetAttribute("TagName"),
                        TagDataType = xmlReader.SafeGetAttribute("TagDataType"),
                        TagValue = xmlReader.SafeGetAttribute("TagValue")
                    });
                    #endregion Parse all Tag elements
                }
                else if (xmlReader.Name.Equals("file", StringComparison.InvariantCultureIgnoreCase))
                {
                    #region Parse File elements

                    FileEntity fileEntity = new FileEntity { FileType = xmlReader.SafeGetAttribute("FileType") };

                    XmlReader xmlReaderForExternalFile = XmlReader.Create(new StringReader(xmlReader.ReadOuterXml()));

                    while (xmlReaderForExternalFile.Read())
                    {
                        #region Parse external file elements
                        if (xmlReaderForExternalFile.Name.Equals("ExternalFile", StringComparison.InvariantCultureIgnoreCase))
                        {
                            fileEntity.ExternalFile.Add(new ExternalFileEntity()
                            {
                                FileName = xmlReaderForExternalFile.SafeGetAttribute("FileName"),
                                FilePath = xmlReaderForExternalFile.SafeGetAttribute("FilePath"),
                                FileSize = xmlReaderForExternalFile.SafeGetAttribute("FileSize"),
                                Hash = xmlReaderForExternalFile.SafeGetAttribute("Hash")
                            });
                        }
                        #endregion Parse external file elements
                    }
                    documentEntity.Files.Add(fileEntity);
                    #endregion Parse File elements
                }
            }

            return documentEntity;
        }
Пример #38
0
 public void AddLocalFile(FileEntity file)
 {
     _locallist.Add(file);
 }
Пример #39
0
 public static FileEntity CreateFileEntity(global::System.Guid id, string name, string host, string path)
 {
     FileEntity fileEntity = new FileEntity();
     fileEntity.Id = id;
     fileEntity.Name = name;
     fileEntity.Host = host;
     fileEntity.Path = path;
     return fileEntity;
 }
Пример #40
0
 public void AddToFiles(FileEntity fileEntity)
 {
     base.AddObject("Files", fileEntity);
 }
 private EdiSegmentCollection get_segments(FileEntity file)
 {
     var contents = FileUtilitiesExtensions.QuickFileText(file.FullPath);
     contents = contents.Replace("\r\n", "");
     return _segmentSplitter.Split(contents);
 }
 private static string getNewPath(FileEntity file, string folder)
 {
     return file.ContainingFolder + folder + Path.GetFileNameWithoutExtension(file.FileName) +
            DateTime.Now.ToString("yyyyMMddhhmmss") + Path.GetExtension(file.FileName);
 }