Beispiel #1
0
        private void inspection_button_result_Click(object sender, EventArgs e)
        {
            if (this.select_inspection == null)
            {
                return;
            }

            List <FileDescription>  files = new List <FileDescription>();
            List <TableLayoutPanel> lists = inspection_list.Controls.OfType <TableLayoutPanel>().ToList();

            foreach (TableLayoutPanel control in lists)
            {
                ComboBox        cb     = control.Controls.OfType <ComboBox>().ElementAt(0);
                Label           label  = control.Controls.OfType <Label>().ElementAt(0);
                string          path   = label.Text;
                int             action = cb.SelectedIndex;
                FileDescription file   = new FileDescription();
                file.path = path;
                switch (action)
                {
                case 1:
                    file.state = FileDescription.FilesStates.ToQuarantine;
                    break;

                case 2:
                    file.state = FileDescription.FilesStates.Delete;
                    break;

                default:
                    file.state = FileDescription.FilesStates.Allow;
                    break;
                }
                files.Add(file);
            }
            ServiceClient client = create_client();

            client.handle_files(files.ToArray(), this.select_inspection);

            client.remove_inspection(this.select_inspection);
            client.Close();
            inspection_list.Controls.Clear();
            inspection_label.Text  = "";
            this.select_inspection = null;
            inspections_update();
        }
Beispiel #2
0
        public async Task <ImageUploadResult> AddPhotoAsync(IFormFile file)
        {
            ImageUploadResult uploadResult = new();

            if (file.Length > 0)
            {
                using Stream stream = file.OpenReadStream();

                ImageUploadParams uploadParams = new()
                {
                    File = new FileDescription(file.FileName, stream)
                };

                uploadResult = await _cloudinary.UploadAsync(uploadParams);
            }

            return(uploadResult);
        }
        private void WriteFileDescription(FileDescription fd)
        {
            Debug.WriteLine("write fid:" + fd.FileId + "| pos:" + masterFileStream.Position);
            masterFileStream.Write(BitConverter.GetBytes(fd.FileId), 0, 4);
            masterFileStream.Write(BitConverter.GetBytes(fd.FileSize), 0, 4);
            masterFileStream.Write(BitConverter.GetBytes((int)fd.Fts), 0, 4);
            masterFileStream.Write(BitConverter.GetBytes((int)fd.Ftm), 0, 4);
            string pathAndOther = fd.Path + "\\" + fd.FileName;

            if (fd.FileExtension != null && fd.FileExtension != "")
            {
                pathAndOther += "." + fd.FileExtension;
            }
            masterFileStream.Write(ASCIIEncoding.ASCII.GetBytes(pathAndOther), 0, pathAndOther.Length);
            byte[] array = new byte[200 - pathAndOther.Length];
            masterFileStream.Write(array, 0, array.Length);
            masterFileStream.Flush();
        }
        /// <summary>
        /// 检测cue文件内的文件名是否与文件对应
        /// </summary>
        /// <param name="cueFile"></param>
        /// <returns></returns>
        public static bool CueMatchCheck(FileDescription cueFile)
        {
            var cueContext = EncodingConverter.GetStringFrom(cueFile.FullPath, cueFile.Encode);
            var rootPath   = Path.GetDirectoryName(cueFile.FullPath);
            var result     = true;

            foreach (Match audioName in CueFileNameRegex.Matches(cueContext))
            {
                var audioFile = Path.Combine(rootPath ?? "", audioName.Groups["fileName"].Value);
                result &= File.Exists(audioFile);
                Logger.Log($"{audioFile} {(result ? "exists" : "not found")}");
                if (!result)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #5
0
        public FileDescription GetFileDescription(string guid)
        {
            var    googleDoc = JsonConvert.DeserializeObject <dynamic>(File.ReadAllText(Path.Combine(_conversionConfig.StoragePath, guid)));
            string fileId    = googleDoc.doc_id;

            var file = _dataService.Files.Get(fileId).Execute();

            FileDescription result = new FileDescription();

            result.Guid = file.Id;
            result.Name = file.Name + ".pdf";
            if (file.Size != null)
            {
                result.Size = file.Size.Value;
            }

            return(result);
        }
Beispiel #6
0
        public async Task <ImageUploadResult> Upload(string fileName, Stream fileData)
        {
            var cloudinary = CloudinaryInstance();

            fileData.ResetPosition();
            var fileDescription = new FileDescription(fileName, fileData);

            var imageUploadParameters = new ImageUploadParams
            {
                File = fileDescription
            };

            var uploadResult = cloudinary.Upload(imageUploadParameters);

            return(ImageUploadResult.Create(uploadResult.Uri, uploadResult.SecureUri, uploadResult.Format,
                                            uploadResult.CreatedAt, uploadResult.PublicId, uploadResult.Length, uploadResult.Signature,
                                            uploadResult.Version));
        }
        private void CreateDescriptorFile(FileDescription fd, ChunkHash[] hashes)
        {
            FileStream fileStream = new FileStream(".\\descriptors\\descriptor_" + fd.FileName + "." + fd.FileExtension + ".desc", FileMode.Create, FileAccess.Write);

            byte[] data = new byte[Sizes.GetChunksNumber(fd.FileSize)];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = 0;
            }
            fileStream.Write(data, 0, data.Length);

            foreach (ChunkHash h in hashes)
            {
                fileStream.Write(h.Hash, 0, h.Hash.Length);
            }
            fileStream.Flush();
            fileStream.Close();
        }
        protected FileResult AttachmentResult(FileDescription file)
        {
            // We can have record in database, but no actual file in file storage
            if (file.Data == null)
            {
                throw new BusinessException("File doesn't exits", Utilities.Enums.ErrorCode.NOT_EXIST);
            }

            var contentDisposition = new ContentDisposition
            {
                FileName = HttpUtility.UrlEncode(file.FileName),
                Inline   = false
            };

            Response.Headers.Add("BYS-Content-Disposition", contentDisposition.ToString());

            return(File(file.Data, file.ContentType, file.FileName));
        }
        protected FileResult AttachmentResult(FileDescription file)
        {
            // We can have record in database, but no actual file in file storage
            if (file.Data == null)
            {
                throw new BusinessException(ErrorCodes.FileNotFound.ToString(), "File doesn't exits");
            }

            var contentDisposition = new ContentDisposition
            {
                FileName = file.FileName,
                Inline   = false,
            };

            Response.Headers.Add("Content-Disposition", contentDisposition.ToString());

            return(File(file.Data, file.ContentType, file.FileName));
        }
        /// <summary>
        /// Осуществляет получение потока данных для запрашиваемого файла (а также имя файла, MIME-тип, и размер в байтах).
        /// </summary>
        /// <param name="fileDescription">Описание файла.</param>
        /// <param name="fileName">Имя файла.</param>
        /// <param name="fileMimeType">MIME-тип файла.</param>
        /// <param name="fileSize">Размер файла в байтах.</param>
        /// <returns>Поток данных для запрашиваемого файла.</returns>
        private Stream GetFileStream(
            FileDescription fileDescription,
            out string fileName,
            out string fileMimeType,
            out long fileSize)
        {
            if (fileDescription == null)
            {
                throw new ArgumentNullException(nameof(fileDescription));
            }

            Stream fileStream       = null;
            Type   dataObjectType   = null;
            Type   filePropertyType = null;

            if (!string.IsNullOrEmpty(fileDescription.EntityPrimaryKey))
            {
                // Запрашиваемый файл уже был связан с объектом данных, и нужно вычитать из него файловое свойство.
                dataObjectType   = Type.GetType(fileDescription.EntityTypeName, true);
                filePropertyType = Information.GetPropertyType(dataObjectType, fileDescription.EntityPropertyName);
            }
            else
            {
                // Запрашиваемый файл еще не был связан с объектом даных, а значит находится в каталоге загрузок,
                // в подкаталоге с именем fileDescription.FileUplodKey.
                // Получение файлов по ключу загрузки реализовано в DataObjectWebFileProvider.
                filePropertyType = typeof(WebFile);
            }

            if (!HasDataObjectFileProvider(filePropertyType))
            {
                throw new Exception(string.Format("DataObjectFileProvider for \"{0}\" property type not found.", filePropertyType.AssemblyQualifiedName));
            }

            IDataObjectFileProvider dataObjectFileProvider = GetDataObjectFileProvider(filePropertyType);
            object fileProperty = dataObjectFileProvider.GetFileProperty(fileDescription);

            fileStream   = dataObjectFileProvider.GetFileStream(fileProperty);
            fileName     = dataObjectFileProvider.GetFileName(fileProperty);
            fileMimeType = dataObjectFileProvider.GetFileMimeType(fileProperty);
            fileSize     = fileStream.Length;

            return(fileStream);
        }
Beispiel #11
0
        public IServiceResult <FileDescription> GetAllWithJsonFormat()
        {
            var promoters = _context.Promoters;

            var promoterJsonModels = promoters.Select(p => _mapper.Map <PromoterJsonRecord>(p));

            var jsonText = JsonConvert.SerializeObject(promoterJsonModels, Formatting.Indented);

            var bytes    = Encoding.UTF8.GetBytes(jsonText);
            var fileName = $"promoters-export.json";

            var fileDescription = new FileDescription
            {
                Name  = fileName,
                Bytes = bytes
            };

            return(ServiceResult <FileDescription> .Success(fileDescription));
        }
        public void LocalFileInitTransfer(FileDescription fd)
        {
            Debug.WriteLine("LocalFileInitTransfer:" + fd.FileId);
            fd.Ftm = FileTransferMode.OnlyUpload;
            fd.Fts = FileTransferState.Finished;
            NewFileTransferManager.nftm.NewUploadFile(fd, fd.Path);
            MasterFileManager.mfm.RecordNewFile(fd);

            FileState           fs  = MasterFileManager.mfm.ProvideFileState(fd.FileId);
            ActiveFileResources afr =
                new ActiveFileResources(
                    fs,
                    new FileUploadManager(fs, false)
                    );

            FileTransferCenter.ftc.AddFile(afr);

            FrmFileTransfers.frmFileTransfers.ShowNewFile(fs);
        }
Beispiel #13
0
 private void btnBrowseIzvorisna_Click(object sender, EventArgs e)  //t+...
 {
     if (FileRegistrationManager.frm.RegistrationProcessStarted == true)
     {
         MessageBox.Show("Proces registriranja datoteke je već pokrenut!");
         return;
     }
     openFileDialog1.Multiselect = false;
     if (openFileDialog1.ShowDialog() == DialogResult.OK)
     {
         FileInfo        fi = new FileInfo(openFileDialog1.FileName);
         FileDescription fd = new FileDescription();
         fd.FileName      = Utils.GetFileNameFromPath(fi.Name);
         fd.Path          = fi.DirectoryName;
         fd.FileSize      = (uint)fi.Length;
         fd.FileExtension = fi.Extension;
         FileRegistrationManager.frm.StartRegistrationProcess(fd);
     }
 }
        public string PutBlob(Blob blob)
        {
            String path = null;

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(blob.Bytes);
                ms.Position = 0;
                FileDescription fileDescription = new FileDescription(blob.Filename, ms);
                RawUploadParams rawUploadParams = new RawUploadParams()
                {
                    File = fileDescription, Folder = blob.Container, Async = "false"
                };
                RawUploadResult result = cloudinary.Upload(rawUploadParams);
                path = result.Uri.AbsoluteUri;
            }

            return(path);
        }
Beispiel #15
0
        /// <summary>
        /// Осуществляет проверку того, что <see cref="FileDescription.FileUrl"/> и <see cref="FileDescription.PreviewUrl"/>
        /// корректно формируются по заданному описанию объекта данных, с которым связан файл.
        /// </summary>
        //[Test]
        public void TestUrlsByEntityProperties()
        {
            string fileBaseUrl = "http://localhost/api/File";

            // Свойства достаточные для описания файла, который привязан к объекту данных
            // (тип и первичный ключ объекта данных, а так же имя файлового свойства в объекте данных).
            КлассСМножествомТипов entity = new КлассСМножествомТипов();
            string entityTypeName        = entity.GetType().AssemblyQualifiedName;
            string entityPropertyName    = nameof(entity.PropertyStormnetFile);
            string entityPrimaryKey      = entity.__PrimaryKey.ToString();

            FileDescription fileDescription = new FileDescription(fileBaseUrl)
            {
                EntityTypeName     = entityTypeName,
                EntityPropertyName = entityPropertyName,
                EntityPrimaryKey   = entityPrimaryKey
            };

            Uri receivedFileUri    = new Uri(fileDescription.FileUrl);
            Uri receivedPreviewUri = new Uri(fileDescription.PreviewUrl);

            string receivedFileBaseUrl    = receivedFileUri.GetLeftPart(UriPartial.Path);
            string receivedPreviewBaseUrl = receivedPreviewUri.GetLeftPart(UriPartial.Path);

            NameValueCollection receivedFileQueryParameters    = HttpUtility.ParseQueryString(receivedFileUri.Query);
            NameValueCollection receivedPreviewQueryParameters = HttpUtility.ParseQueryString(receivedPreviewUri.Query);

            /*
             * Assert.AreEqual(fileBaseUrl, receivedFileBaseUrl);
             * Assert.AreEqual(fileBaseUrl, receivedPreviewBaseUrl);
             *
             * Assert.AreEqual(3, receivedFileQueryParameters.Count);
             * Assert.AreEqual(entityTypeName, receivedFileQueryParameters["entityTypeName"]);
             * Assert.AreEqual(entityPropertyName, receivedFileQueryParameters["entityPropertyName"]);
             * Assert.AreEqual(entityPrimaryKey, receivedFileQueryParameters["entityPrimaryKey"]);
             *
             * Assert.AreEqual(4, receivedPreviewQueryParameters.Count);
             * Assert.AreEqual(entityTypeName, receivedPreviewQueryParameters["entityTypeName"]);
             * Assert.AreEqual(entityPropertyName, receivedPreviewQueryParameters["entityPropertyName"]);
             * Assert.AreEqual(entityPrimaryKey, receivedPreviewQueryParameters["entityPrimaryKey"]);
             * Assert.AreEqual(true, bool.Parse(receivedPreviewQueryParameters["getPreview"]));
             */
        }
        public void UpdateFileDescription(FileDescription fd)
        {
            int i = 0;

            int[] fds = fileDescriptions.Keys.ToArray();
            for (; i < fds.Length; i++)
            {
                if (fds[i] == fd.FileId)
                {
                    break;
                }
            }
            lock (masterFileStream) {
                long pos = 4 + Sizes.FileDescriptionDriveSize * i;
                masterFileStream.Seek(pos, SeekOrigin.Begin);
                Debug.WriteLine("update fid:" + fd.FileId + "| pos:" + pos);
                WriteFileDescription(fd);
            }
        }
Beispiel #17
0
        private void WriteFileDescription(FileDescription fdesc)
        {
            writer.WriteStartElement("fileDescription");

            writer.WriteStartElement("fileContent");
            WriteParamGroup(fdesc.FileContent);
            writer.WriteEndElement();

            WriteList("sourceFileList", fdesc.SourceFiles, WriteSourceFile);

            if (fdesc.Contact != null)
            {
                writer.WriteStartElement("contact");
                WriteParamGroup(fdesc.Contact);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Beispiel #18
0
        public ImportResultDto ImportForestActor(FileDescription excelFile)
        {
            using (var memoryStream = new MemoryStream(excelFile.Data))
            {
                using (var package = new ExcelPackage(memoryStream))
                {
                    var worksheet = package.Workbook.Worksheets[1]; // Tip: To access the first worksheet, try index 1, not 0
                    int totalRows = worksheet.Dimension.Rows;

                    List <APActor> actors = new List <APActor>();

                    for (int i = 2; i < totalRows; i++)
                    {
                        actors.Add(
                            new APActor
                        {
                            AAStatus            = "Alive",
                            AASource            = worksheet.Cells[i, 1].Value?.ToString(),
                            APActorName         = worksheet.Cells[i, 2].Value?.ToString(),
                            APActorAddress      = worksheet.Cells[i, 3].Value?.ToString(),
                            APActorTypeCode     = worksheet.Cells[i, 4].Value?.ToString(),
                            GEStateProvinceCode = GetCode(worksheet.Cells[i, 5].Value?.ToString()),
                            GEDistrictCode      = GetCode(worksheet.Cells[i, 6].Value?.ToString()),
                            GECommuneCode       = GetCode(worksheet.Cells[i, 7].Value?.ToString()),
                            APActorEmail        = worksheet.Cells[i, 8].Value?.ToString(),
                            APActorPhone        = worksheet.Cells[i, 9].Value?.ToString(),
                            APActorWebsite      = worksheet.Cells[i, 10].Value?.ToString(),
                            APActorCode         = worksheet.Cells[i, 23].Value?.ToString(),
                        });
                    }

                    _unitOfWork.Context.BulkInsert(actors);

                    _unitOfWork.Complete();

                    return(new ImportResultDto
                    {
                        ImportRows = actors.Count
                    });
                }
            }
        }
Beispiel #19
0
        private static void PrepareForPackageDescription(ArchiveMetadata metadata, FileInfo packageFile)
        {
            metadata.FileDescriptions = null; // Removes any existing file-descriptions

            if (packageFile.Exists)
            {
                FileDescription informationPackageFileDescription = GetFileDescription
                                                                    (
                    packageFile,
                    packageFile.Directory
                                                                    );

                informationPackageFileDescription.Id = 0;

                metadata.FileDescriptions = new List <FileDescription>
                {
                    informationPackageFileDescription
                };
            }
        }
        public HeaderdFileContext(SerializationContext original, FileDescription description) : base(original)
        {
            Argument.NotNull(original, nameof(original));
            Argument.NotNull(description, nameof(description));

            _file = new HeaderedFile(description);
            switch (original.SerializerMode)
            {
            case SerializerMode.Deserialize:
                _file.Read(TextReader);
                break;

            case SerializerMode.Serialize:
                _file.CreateWriter();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(original.SerializerMode));
            }
        }
Beispiel #21
0
        public async Task SendMail()
        {
            var attachmentFile = new FileDescription[0];

            attachmentFile = attachmentFile.Append(new FileDescription
            {
                FileName = "BinhNguyen attachment file name",
                Data     = await File.ReadAllBytesAsync(@"E:\\config_background.txt")
            }).ToArray();

            var sendEmailInput = new SendEmailInput
            {
                Content         = string.Empty,
                Subject         = string.Empty,
                RecipientEmails = new string[] { "*****@*****.**" },
                AttachmentFiles = attachmentFile
            };

            await _sendMailService.SendMails(sendEmailInput);
        }
Beispiel #22
0
        public async Task <bool> AddFileToFolder(string folderId, FileDescription file)
        {
            try
            {
                var filter = Builders <Folder> .Filter.Where(x => x.Id == folderId);

                var update = Builders <Folder> .Update.PushEach(x => x.Files, new List <FileDescription> {
                    file
                });

                UpdateResult actionResult = await _context.GetFolderCollection().UpdateOneAsync(filter, update);

                return(actionResult.IsAcknowledged && actionResult.ModifiedCount > 0);
            }
            catch (Exception ex)
            {
                // log or manage the exception
                throw ex;
            }
        }
        private void LoadFileDescriptions()
        {
            if (masterFileStream != null)
            {
                int offset = 4;

                int fileSize = (int)masterFileStream.Length;
                while (offset + Sizes.FileDescriptionDriveSize <= fileSize)
                {
                    FileDescription fd = ReadFileDescription(offset);
                    if (fd != null && !FileDescriptions.ContainsKey(fd.FileId) && fd.Fts != FileTransferState.Deleted)
                    {
                        FileDescriptions.Add(fd.FileId, fd);
                        Debug.WriteLine("offset:" + offset);
                        Debug.WriteLine("file:" + fd.FileId);
                    }
                    offset += Sizes.FileDescriptionDriveSize;
                }
            }
        }
Beispiel #24
0
 private void WriteFile(StreamWriter writer, FileDescription file)
 {
     if (file.IsRemote)
     {
         WriteParam(writer, "file", file.FilePath);
     }
     else
     {
         if (file.Stream == null)
         {
             using (FileStream stream = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
             {
                 WriteFile(writer, stream, file.FileName);
             }
         }
         else
         {
             WriteFile(writer, file.Stream, file.FileName);
         }
     }
 }
        public IActionResult AddClaimFile(InsuranceClaimsAddClaimFileViewModel model)
        {
            InsuranceClaim insuranceClaim = _insuranceClaimsRepository.GetClaim(model.Id);

            if (ModelState.IsValid)
            {
                FileHandler     fileHandler     = new FileHandler();
                FileDescription fileDescription = fileHandler.UploadSingleFile(model.File, model.FileType, insuranceClaim.ClaimNo, DateTime.Now, model.Descrption);
                _fileDescriptionsRepository.Create(fileDescription);
                InsuranceClaimFile claimFile = new InsuranceClaimFile
                {
                    FileDescriptionId = fileDescription.Id,
                    InsuranceClaimId  = insuranceClaim.Id
                };
                _insuranceClaimFilesRepository.Add(claimFile);
                insuranceClaim.InsuranceClaimFiles.Add(claimFile);
                _insuranceClaimsRepository.Update(insuranceClaim);
                return(RedirectToAction("details", new { id = model.Id }));
            }
            return(RedirectToAction("AddClaimFile", new { id = model.Id }));
        }
        public string SaveFile(FileDescription fileDescription, Stream stream, SaveOptions saveOptions)
        {
            string key = GetOutputPath(fileDescription, saveOptions);

            stream.Seek(0, SeekOrigin.Begin);
            S3FileInfo fileInfo = new S3FileInfo(_client, bucketName, key);

            byte[] buffer = new byte[16384]; //16*1024
            using (Stream output = fileInfo.Create())
            {
                int read = stream.Read(buffer, 0, buffer.Length);
                while (read > 0)
                {
                    output.Write(buffer, 0, read);
                    read = stream.Read(buffer, 0, buffer.Length);
                }
                output.Flush();
                output.Close();
            }
            return(fileInfo.FullName);
        }
Beispiel #27
0
        public async Task <IActionResult> FileDescription()
        {
            RegistrarRolesAdministrationIndex index = new RegistrarRolesAdministrationIndex();

            FileDescription[] fileDescriptions =
                await _ServiceRegistrar.GetFilesDescriptionsByDocumentGroupNameAsync(
                    Presets.DocumentGroup1CAccount,
                    CancellationToken.None);

            string          selectedDocument = fileDescriptions.Length > 0 ? fileDescriptions[0].Descrioption : "";
            FileDescription fileDescription  = fileDescriptions.FirstOrDefault(i => i.Descrioption.Equals(selectedDocument));

            index.Documents     = fileDescriptions.Select(i => i.Descrioption).ToArray();
            index.DocumentGroup = Presets.DocumentGroup1CAccount;
            index.ReadADRoles   = fileDescriptions.FirstOrDefault(i => i.Descrioption.Equals(selectedDocument))?.ReadADRoles ?? new string[0];
            index.WriteADRoles  = fileDescriptions.FirstOrDefault(i => i.Descrioption.Equals(selectedDocument))?.WriteADRoles ?? new string[0];

            ViewData["SelectedDocument"] = selectedDocument;

            return(View(index));
        }
        public async Task Fetch(Path source, bool copySubDirs, Dictionary <FileDescription, byte[]> fileDescToBytesMapping, List <DirectoryDescription> subDirectories)
        {
            DirectoryInfo dir = new DirectoryInfo(source.AbsolutePath);

            if (copySubDirs)
            {
                foreach (var item in dir.GetDirectories())
                {
                    subDirectories.Add(new DirectoryDescription()
                    {
                        Name = item.Name
                    });
                }
            }

            FileInfo[] files = dir.GetFiles();

            foreach (FileInfo file in files)
            {
                byte[]          bytes;
                FileDescription fd    = new FileDescription();
                int             index = file.Name.LastIndexOf('.');                         // Get rid of file extension from name
                fd.Name          = index == -1 ? file.Name : file.Name.Substring(0, index); // Get rid of file extension from name
                fd.FileExtension = file.Extension;
                fd.LastWriteTime = file.LastWriteTime;

                // Read bytes
                bytes = File.ReadAllBytes(System.IO.Path.Combine(source.AbsolutePath, file.Name));

                fd.MimeType = "application/unknown";
                string ext = System.IO.Path.GetExtension(System.IO.Path.Combine(source.AbsolutePath, file.Name).ToLower());
                Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
                if (regKey != null && regKey.GetValue("Content Type") != null)
                {
                    fd.MimeType = regKey.GetValue("Content Type").ToString();
                }

                fileDescToBytesMapping.Add(fd, bytes);
            }
        }
Beispiel #29
0
 void OnTriggerEnter2D(Collider2D other)
 {
     if (other.gameObject.CompareTag("Item"))
     {
         FileDescription File = other.GetComponent <FileDescription> ();
         popUp.AddDownload(File.title, File.sizeFile);
         Destroy(other.gameObject);
     }
     if (other.gameObject.CompareTag("Virus") && timeCount <= 0)
     {
         int virusType = Random.Range(0, 4);
         if (virusType == 0)
         {
             int max = Random.Range(3, 9);
             for (int i = 0; i < max; i++)
             {
                 popUp.AddAlert("Error", "ふたなり-" + i + ".dll was not found.");
             }
         }
         else if (virusType == 1)
         {
             string errors = "";
             for (int i = 0; i < 4; i++)
             {
                 errors += bigErrors[Random.Range(0, bigErrors.Length)] + System.Environment.NewLine;
             }
             popUp.AddBigError("Fatal Error", "An error occured while executing the application", errors);
         }
         else if (virusType == 2)
         {
             popUp.AddBrowser();
         }
         else
         {
             popUp.AddSys32("Confirm Folder Delete", "Are you sure you want to delete 'C:\\System32\\' and all of its content?");
         }
         timeCount = InvulnerabilityTime;
         Destroy(other.gameObject);
     }
 }
Beispiel #30
0
        /// <summary>
        /// Uploads new image with selected parameters
        /// </summary>
        /// <param name="fileName">Name of the file to upload</param>
        /// <param name="imageMemoryStream">Memory stream containing the image data</param>
        /// <returns>Image uri</returns>
        public async Task <string> UploadImageAsync(MemoryStream imageMemoryStream, string fileName)
        {
            imageMemoryStream.Position = 0;
            var        cloudinaryAccount = new Account(cloudName, apiKey, apiSecret);
            Cloudinary cloudinary        = new Cloudinary(cloudinaryAccount);
            string     publicId          = Guid.NewGuid().ToString() + fileName;
            var        file         = new FileDescription(fileName, imageMemoryStream);
            var        uploadParams = new ImageUploadParams
            {
                File        = file,
                Format      = "jpg",
                PublicId    = publicId,
                UseFilename = true,
            };

            uploadParams.Check();
            var uploadResult = await cloudinary.UploadAsync(uploadParams);

            var uri = uploadResult.SecureUri.AbsoluteUri;

            return(uri);
        }
            public IEnumerable<FileDescriptionShort> AddFileDescriptions(FileResult fileResult)
            {
                List<string> filenames = new List<string>();
                for (int i = 0; i < fileResult.FileNames.Count(); i++)
                {
                    var fileDescription = new FileDescription
                    {
                        ContentType = fileResult.ContentTypes[i],
                        FileName = fileResult.FileNames[i],
                        Name = fileResult.Names[i],
                        CreatedTimestamp = fileResult.CreatedTimestamp,
                        UpdatedTimestamp = fileResult.UpdatedTimestamp,
                        Description = fileResult.Description
                    };

                    filenames.Add(fileResult.FileNames[i]);
                    _context.FileDescriptions.Add(fileDescription);
                }

                _context.SaveChanges();
                return GetNewFiles(filenames);
            }
        private void UploadFile(string filePath, FileDescription fileDescription)
        {
            var name = fileDescription.ItemType == "Resource" ? Path.GetFileName(filePath) : Path.GetFileNameWithoutExtension(filePath);

            byte[] fileData;

            if (fileDescription.ItemType == "DataSource")
                fileData = CreateDataSource(filePath);
            else if (fileDescription.ItemType == "Report")
                fileData = ReadReport(filePath);
            else
                fileData = File.ReadAllBytes(filePath);

            Warning[] warnings;

            _client.CreateCatalogItem(fileDescription.ItemType, name, _options.RemoteFolder, true, fileData, fileDescription.Properties, out warnings);
        }
 public void SaveFileData(FileDescription fileDescription, FileData fileData)
 {
     throw new NotImplementedException();
 }
 public FileData GetFileData(FileDescription fileDescription)
 {
     throw new NotImplementedException();
 }