Пример #1
0
        /// <summary>
        /// Осуществляет получение файлового свойства из файла, расположенного по заданному пути.
        /// </summary>
        /// <param name="filePath">Путь к файлу.</param>
        /// <returns>Значение файлового свойства объекта данных, соответствующее типу <see cref="File"/>.</returns>
        public override object GetFileProperty(string filePath)
        {
            if (!System.IO.File.Exists(filePath))
            {
                throw new FileNotFoundException($"File \"{filePath}\" not found.");
            }

            var  fileInfo     = new FileInfo(filePath);
            File fileProperty = new File {
                Name = fileInfo.Name, Size = fileInfo.Length
            };

            fileProperty.FromNormalToZip(filePath);

            return(fileProperty);
        }
Пример #2
0
        /// <summary>
        /// Осуществляет проверку того, что для файлов, связанных с объектами данных, корректно скачиваются их preview-изображения.
        /// </summary>
        //[Test]
        public void TestPreviewDownloadFromDataObjectSuccess()
        {
            string fileBaseUrl = "http://localhost/api/File";

            using (DataServiceWrapper dataServiceWrapper = new DataServiceWrapper())
            {
                foreach (IDataService dataService in dataServiceWrapper.AllowedDataServices)
                {
                    foreach (string srcFilePath in new List <string> {
                        _srcImageFilePath, _srcTextFilePath
                    })
                    {
                        FileInfo fileInfo = new FileInfo(srcFilePath);

                        string fileUploadKey = Guid.NewGuid().ToString("D");
                        string fileName      = fileInfo.Name;
                        string fileMimeType  = MimeMapping.GetMimeMapping(fileName);
                        long   fileSize      = fileInfo.Length;

                        // Копируем тестовый файл в каталог, предназначенный для загруженных на сервер файлов.
                        // Тем самым имитируем ситуацию как будто файл был ранее загружен на сервер через файловый контроллер.
                        string uploadedFileDirectoryPath = CreateUploadsSubDirectory(fileUploadKey);
                        string uploadedFilePath          = string.Concat(uploadedFileDirectoryPath, "\\", fileName);
                        System.IO.File.Copy(srcFilePath, uploadedFilePath, true);

                        // Описание загруженного файла, содержащее URL для скачивания файла с сервера.
                        FileDescription uploadedFileDescription = new FileDescription(fileBaseUrl, uploadedFilePath);

                        // Загруженный файл в виде Base64String.
                        string uploadedFileBase64String = FileController.GetBase64StringFileData(uploadedFilePath);

                        // Свойство объекта данных типа File, связывающее загруженный файл с объектом данных.
                        string entityFilePropertyName = nameof(КлассСМножествомТипов.PropertyStormnetFile);
                        File   entityFileProperty     = new File {
                            Name = fileName, Size = fileSize
                        };
                        entityFileProperty.FromNormalToZip(uploadedFilePath);

                        // Свойство объекта данных типа WebFile, связывающее загруженный файл с объектом данных.
                        string  entityWebFilePropertyName = nameof(КлассСМножествомТипов.PropertyStormnetWebFile);
                        WebFile entityWebFileProperty     = new WebFile {
                            Name = fileName, Size = (int)fileSize, Url = uploadedFileDescription.FileUrl
                        };

                        // Объект данных, с которым связан загруженный файл.
                        DataObject entity = new КлассСМножествомТипов
                        {
                            // Файловые свойства объекта данных.
                            PropertyStormnetFile    = entityFileProperty,
                            PropertyStormnetWebFile = entityWebFileProperty,

                            // DateTime-свойство объекта данных.
                            // На работу с файловыми свойствами никак не влияет,
                            // но если оставить его незаполненным, сервис данных будет ругаться при сохранении.
                            PropertyDateTime = new DateTimeOffset(DateTime.Now).UtcDateTime
                        };

                        // Свойства необходимые для описания файла, связанного с объектом данных.
                        string        entityTypeName        = entity.GetType().AssemblyQualifiedName;
                        string        entityPrimaryKey      = entity.__PrimaryKey.ToString();
                        List <string> entityPropertiesnames = new List <string> {
                            entityFilePropertyName, entityWebFilePropertyName
                        };

                        // Сохраняем объект данных в БД (используя подменный сервис данных).
                        dataService.UpdateObject(entity);

                        // Перебираем разнотипные файловые свойства объекта данных.
                        foreach (string entityPropertyName in entityPropertiesnames)
                        {
                            // Описание файла, связанного с объектом данных, которое содержит ссылку на скачивание файла.
                            FileDescription entityRelatedFileDescription = new FileDescription(fileBaseUrl)
                            {
                                FileName           = fileName,
                                FileSize           = fileSize,
                                FileMimeType       = fileMimeType,
                                EntityTypeName     = entityTypeName,
                                EntityPrimaryKey   = entityPrimaryKey,
                                EntityPropertyName = entityPropertyName
                            };

                            // Конфигурируем HttpServer, файловый контроллер, и обращаемся к серверу для скачивания файла.
                            using (var config = new HttpConfiguration())
                            {
                                config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
                                config.MapODataServiceFileRoute("File", "api/File", _uploadsDirectoryPath, dataService);

                                using (var server = new HttpServer(config))
                                    using (var client = new HttpClient(server, false))
                                        using (HttpResponseMessage response = client.GetAsync(entityRelatedFileDescription.PreviewUrl).Result)
                                        {
                                            //Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

                                            // Получаем Base64String, содержащую preview скачанного файла.
                                            string downloadedFileBase64String = response.Content.ReadAsStringAsync().Result;

                                            if (fileMimeType.StartsWith("image"))
                                            {
                                                // Для файлов являющихся изображениями, должна возвращаться Base64String с указанием MIME-типа.
                                                //Assert.AreEqual(uploadedFileBase64String, downloadedFileBase64String);
                                                //Assert.AreEqual(true, downloadedFileBase64String.ToLower().StartsWith($"data:{fileMimeType}"));
                                            }
                                            else
                                            {
                                                // Для файлов не являющихся изображениями, должна возвращаться пустая строка.
                                                //Assert.AreEqual(true, downloadedFileBase64String == string.Empty);
                                                //Assert.AreEqual(0.ToString(), response.Content.Headers.GetValues("Content-Length").FirstOrDefault());
                                            }
                                        }
                            }
                        }
                    }
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Осуществляет проверку того, что файлы, связанные с объектами данных, корректно скачиваются с сервера.
        /// </summary>
        //[Test]
        public void TestFileDownloadFromDataObjectSuccess()
        {
            string fileBaseUrl = "http://localhost/api/File";

            using (DataServiceWrapper dataServiceWrapper = new DataServiceWrapper())
            {
                foreach (IDataService dataService in dataServiceWrapper.AllowedDataServices)
                {
                    foreach (string srcFilePath in new List <string> {
                        _srcImageFilePath, _srcTextFilePath
                    })
                    {
                        FileInfo fileInfo = new FileInfo(srcFilePath);

                        string fileUploadKey          = Guid.NewGuid().ToString("D");
                        string fileName               = fileInfo.Name;
                        string fileMimeType           = MimeMapping.GetMimeMapping(fileName);
                        long   fileSize               = fileInfo.Length;
                        string fileContentDisposition = string.Format("attachment; filename=\"{0}\"; filename*=UTF-8''{1}; size={2}", fileName, Uri.EscapeDataString(fileName), fileSize);

                        // Копируем тестовый файл в каталог, предназначенный для загруженных на сервер файлов.
                        // Тем самым имитируем ситуацию как будто файл был ранее загружен на сервер через файловый контроллер.
                        string uploadedFileDirectoryPath = CreateUploadsSubDirectory(fileUploadKey);
                        string uploadedFilePath          = string.Concat(uploadedFileDirectoryPath, "\\", fileName);
                        System.IO.File.Copy(srcFilePath, uploadedFilePath, true);

                        // Описание загруженного файла, содержащее URL для скачивания файла с сервера.
                        FileDescription uploadedFileDescription = new FileDescription(fileBaseUrl, uploadedFilePath);

                        // Свойство объекта данных типа File, связывающее загруженный файл с объектом данных.
                        string entityFilePropertyName = nameof(КлассСМножествомТипов.PropertyStormnetFile);
                        File   entityFileProperty     = new File {
                            Name = fileName, Size = fileSize
                        };
                        entityFileProperty.FromNormalToZip(uploadedFilePath);

                        // Свойство объекта данных типа WebFile, связывающее загруженный файл с объектом данных.
                        string  entityWebFilePropertyName = nameof(КлассСМножествомТипов.PropertyStormnetWebFile);
                        WebFile entityWebFileProperty     = new WebFile {
                            Name = fileName, Size = (int)fileSize, Url = uploadedFileDescription.FileUrl
                        };

                        // Объект данных, с которым связан загруженный файл.
                        DataObject entity = new КлассСМножествомТипов
                        {
                            // Файловые свойства объекта данных.
                            PropertyStormnetFile    = entityFileProperty,
                            PropertyStormnetWebFile = entityWebFileProperty,

                            // DateTime-свойство объекта данных.
                            // На работу с файловыми свойствами никак не влияет,
                            // но если оставить его незаполненным, сервис данных будет ругаться при сохранении.
                            PropertyDateTime = new DateTimeOffset(DateTime.Now).UtcDateTime
                        };

                        // Свойства необходимые для описания файла, связанного с объектом данных.
                        string        entityTypeName        = entity.GetType().AssemblyQualifiedName;
                        string        entityPrimaryKey      = entity.__PrimaryKey.ToString();
                        List <string> entityPropertiesnames = new List <string> {
                            entityFilePropertyName, entityWebFilePropertyName
                        };

                        // Сохраняем объект данных в БД (используя подменный сервис данных).
                        dataService.UpdateObject(entity);

                        // Перебираем разнотипные файловые свойства объекта данных.
                        foreach (string entityPropertyName in entityPropertiesnames)
                        {
                            // Описание файла, связанного с объектом данных, которое содержит ссылку на скачивание файла.
                            var entityRelatedFileDescription = new FileDescription(fileBaseUrl)
                            {
                                FileName           = fileName,
                                FileSize           = fileSize,
                                FileMimeType       = fileMimeType,
                                EntityTypeName     = entityTypeName,
                                EntityPrimaryKey   = entityPrimaryKey,
                                EntityPropertyName = entityPropertyName
                            };

                            // Конфигурируем HttpServer, файловый контроллер, и обращаемся к серверу для скачивания файла.
                            using (var config = new HttpConfiguration())
                            {
                                config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
                                config.MapODataServiceFileRoute("File", "api/File", _uploadsDirectoryPath, dataService);

                                using (var server = new HttpServer(config))
                                    using (var client = new HttpClient(server, false))
                                        using (HttpResponseMessage response = client.GetAsync(entityRelatedFileDescription.FileUrl).Result)
                                        {
                                            //Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

                                            // Проверяем, что в ответе правильно указаны: длина, тип файла, и content-disposition.
                                            //Assert.AreEqual(fileSize.ToString(), response.Content.Headers.GetValues("Content-Length").FirstOrDefault());
                                            //Assert.AreEqual(fileMimeType, response.Content.Headers.GetValues("Content-Type").FirstOrDefault());
                                            //Assert.AreEqual(fileContentDisposition, response.Content.Headers.GetValues("Content-Disposition").FirstOrDefault());

                                            // Получаем поток байтов, скачиваемого файла.
                                            using (Stream stream = response.Content.ReadAsStreamAsync().Result)
                                            {
                                                // Вычитываем поток в буфер.
                                                byte[] bytes = new byte[stream.Length];
                                                stream.Read(bytes, 0, (int)stream.Length);

                                                // Сохраняем поток в виде файла (в каталог, предназначенный для скачанных с сервера файлов).
                                                // Тем самым имитируем ситуацию как будто файл был скачан.
                                                string downloadedFileDirectoryPath = CreateDownloadsSubDirectory(fileUploadKey);
                                                string downloadedFilePath          = $"{downloadedFileDirectoryPath}\\{fileName}";
                                                using (var fileStream = new FileStream(downloadedFilePath, FileMode.Create, FileAccess.Write))
                                                {
                                                    fileStream.Write(bytes, 0, (int)stream.Length);
                                                    fileStream.Close();

                                                    // Проверяем, что загруженный на сервер, и скачанный с сервера файлы - одинаковы.
                                                    //Assert.AreEqual(true, FilesComparer.FilesAreEqual(uploadedFilePath, downloadedFilePath));
                                                }
                                            }
                                        }
                            }
                        }
                    }
                }
            }
        }