コード例 #1
0
        private void UndoLastSegmentRemoval()
        {
            if (!RemovedSegments.Any())
            {
                return;
            }

            int addedSegmentTotalLength = RemovedSegments.Last().SegmentEndByteIndexInFile - RemovedSegments.Last().SegmentStartByteIndexInFile;

            Segments.Insert(RemovedSegments.Last().SegmentIndexInFile, RemovedSegments.Last());

            byte[] newBytes = new byte[FileBytes.Length + addedSegmentTotalLength];

            FileBytes.Take(RemovedSegments.Last().SegmentStartByteIndexInFile).ToArray().CopyTo(newBytes, 0);
            RemovedSegments.Last().Content.CopyTo(newBytes, RemovedSegments.Last().SegmentStartByteIndexInFile);
            FileBytes.Skip(RemovedSegments.Last().SegmentStartByteIndexInFile).ToArray().CopyTo(newBytes, RemovedSegments.Last().SegmentEndByteIndexInFile);
            FileBytes = newBytes;

            for (int i = RemovedSegments.Last().SegmentIndexInFile; i < Segments.Count; i++)
            {
                Segments[i].SegmentStartByteIndexInFile += addedSegmentTotalLength;
                Segments[i].SegmentEndByteIndexInFile   += addedSegmentTotalLength;
                Segments[i].SegmentIndexInFile++;
            }

            RemovedSegments.RemoveAt(RemovedSegments.Count - 1);
        }
コード例 #2
0
ファイル: HttpService.cs プロジェクト: asbarkouky85/Helpers
        public async Task <FileBytes> DownloadFileAsync(string url, object query = null)
        {
            HttpResponseMessage mes = await Get(url, query);

            if (mes.IsSuccessStatusCode)
            {
                FileBytes b = new FileBytes();
                b.Bytes = await mes.Content.ReadAsByteArrayAsync();

                b.FileName = url.GetAfter("/");

                if (mes.Content.Headers.ContentDisposition != null)
                {
                    b.FileName = mes.Content.Headers.ContentDisposition.FileName;
                }

                if (mes.Content.Headers.ContentType != null)
                {
                    b.MimeType = mes.Content.Headers.ContentType.MediaType;
                }
                else
                {
                    b.MimeType = MimeData.GetFileMimeType(b.FileName);
                }

                return(b);
            }
            else
            {
                return(null);
            }
        }
コード例 #3
0
        public FileBytes GetThumb(string filePath, int maxWidth, int maxHeight)
        {
            if (!File.Exists(filePath))
            {
                return(null);
            }

            Image  current = Image.FromFile(filePath);
            Bitmap canvas  = ResizeImage(current, maxWidth, maxHeight);

            var bytes = new byte[0];


            using (MemoryStream st = new MemoryStream())
            {
                canvas.Save(st, current.RawFormat);
                bytes = st.ToArray();
            }

            FileInfo  inf      = new FileInfo(filePath);
            var       FileName = inf.Name.GetBeforeLast(".") + "__" + maxWidth + "x" + maxHeight + inf.Extension;
            FileBytes b        = new FileBytes(FileName, bytes);

            return(b);
        }
コード例 #4
0
ファイル: ModelFileData.cs プロジェクト: Alriac/STL_Showcase
        public bool LoadFileBytes(bool KeepInMemory)
        {
            try
            {
                if (FileBytes != null)
                {
                    FileBytes.Dispose();
                }

                FileStream stream = File.OpenRead(this.FileFullPath);

                if (KeepInMemory && stream.Length <= 100 * 1024 * 1024)
                {
                    byte[] bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    MemoryStream newMemoryStream = new MemoryStream();
                    newMemoryStream.Write(bytes, 0, bytes.Length);
                    newMemoryStream.Position = 0;
                    stream.Dispose();
                    this.FileBytes = newMemoryStream;
                }
                else
                {
                    this.FileBytes = stream;
                }
                return(true);
            }
            catch
            {
                FileBytes = null;
                return(false);
            }
        }
コード例 #5
0
        public void RemoveSegment(int index)
        {
            if (index > Segments.Count)
            {
                return;
            }

            byte[] BytesBeforeSegment = FileBytes.Take(Segments[index].SegmentStartByteIndexInFile).ToArray();
            byte[] BytesAfterSegment  = FileBytes.Skip(Segments[index].SegmentEndByteIndexInFile).ToArray();

            byte[] tmpBytes = new byte[BytesBeforeSegment.Length + BytesAfterSegment.Length];

            BytesBeforeSegment.CopyTo(tmpBytes, 0);
            BytesAfterSegment.CopyTo(tmpBytes, BytesBeforeSegment.Length);

            FileBytes = tmpBytes;

            int removedSegmentTotalLength = Segments[index].SegmentEndByteIndexInFile - Segments[index].SegmentStartByteIndexInFile;

            RemovedSegments.Add(Segments[index]);
            Segments.RemoveAt(index);

            for (int i = index; i < Segments.Count; i++)
            {
                Segments[i].SegmentStartByteIndexInFile -= removedSegmentTotalLength;
                Segments[i].SegmentEndByteIndexInFile   -= removedSegmentTotalLength;
                Segments[i].SegmentIndexInFile--;
            }

            Modified = true;
            ChangesHistory.Add(new Change()
            {
                TypeOfChange = ChangeType.SegmentRemoval, UndoAction = UndoLastSegmentRemoval
            });
        }
コード例 #6
0
        public async Task <FileBytes> DownloadFileAsync(string url, object query = null)
        {
            HttpResponseMessage mes = await GetAsync(url, query);

            if (mes.IsSuccessStatusCode)
            {
                var Bytes = await mes.Content.ReadAsByteArrayAsync();

                var       FileName = url.GetAfterLast("/")?.GetBeforeFirst("?");
                FileBytes b        = new FileBytes(FileName, Bytes);
                if (mes.Content.Headers.ContentDisposition != null)
                {
                    b.FileName = mes.Content.Headers.ContentDisposition.FileName;
                }

                if (mes.Content.Headers.ContentType != null)
                {
                    b.MimeType = mes.Content.Headers.ContentType.MediaType;
                }
                else
                {
                    b.MimeType = MimeData.GetFileMimeType(b.FileName);
                }

                return(b);
            }
            else
            {
                string message = await mes.Content.ReadAsStringAsync();

                throw new CodeShellHttpException(mes.StatusCode, message);
            }
        }
コード例 #7
0
ファイル: UploadParams.cs プロジェクト: Dennis-Rosenbaum/XTRF
        public byte[] GetFileBytes()
        {
            if (FileBytes != null && FileBytes.Any())
            {
                return(FileBytes);
            }

            return(Encoding.UTF8.GetBytes(FileContent));
        }
コード例 #8
0
        public virtual bool SaveTemp(TmpFileData req, out SavedFileDto dto, long?type = null, string folder = null, bool db = false)
        {
            dto = new SavedFileDto();
            try
            {
                if (req?.TmpPath == null)
                {
                    return(false);
                }

                folder = folder ?? "uploads";

                if (type != null && FolderByCategory.TryGetValue(type.Value, out string catFolder))
                {
                    folder = catFolder;
                }

                string fileName = Utils.GenerateID().ToString() + "_" + req.Name;
                dto.Path = Utils.CombineUrl(folder, fileName);

                string saveLocation = Path.Combine(SaveRoot, dto.Path).Replace("/", "\\");

                Utils.CreateFolderForFile(saveLocation);
                FileBytes bytes = null;

                if (UrlRegex.IsMatch(req.TmpPath))
                {
                    bytes = FileUtils.DownloadFile(req.TmpPath);
                    if (bytes != null)
                    {
                        fileName = bytes.FileName;
                        var dir = Path.GetDirectoryName(dto.Path);

                        bytes.Save(dir);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    string cur = Path.Combine(TempRoot, req.TmpPath);
                    if (File.Exists(dto.Path))
                    {
                        File.Delete(dto.Path);
                    }
                    File.Copy(cur, saveLocation);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #9
0
        public override TmpFileData AddToTemp(FileBytes bts, string key)
        {
            var data = base.AddToTemp(bts, key);

            if (data != null)
            {
                data.Url = Utils.CombineUrl("fileserver/gettempfile?path=" + data.TmpPath);
            }
            return(data);
        }
コード例 #10
0
        public static FileContentResult ToFileResult(this FileBytes res)
        {
            var x = new FileContentResult(res.Bytes, res.MimeType);

            if (res.FileName != null)
            {
                x.FileDownloadName = res.FileName + res.Extension;
            }
            return(x);
        }
コード例 #11
0
        public void SetBytes()
        {
            FileBytes file = new FileBytes("testfile.txt");

            file.Bytes[0] = 42;

            Assert.Equal(42, file.Bytes[0]);

            // For demo purposes only, this is not a good test,
            // we are essentially testing .NET arrays
        }
コード例 #12
0
        public void TestEmail()
        {
            var srv  = Injector.GetService <EmailService>();
            var cl   = srv.CreateClient();
            var mail = srv.CreateMessage("*****@*****.**", "Subject Test", "", true);
            var byts = new FileBytes[] { new FileBytes(@"C:\ASGA_TFS\Libraries\CodeShellCore\master\Configurator.UI\wwwroot\img\default_user.png") };

            mail.Body = "<h1>Hi</h1><img src=\"%A0%\" />";
            srv.AppendAttachments(mail, byts);
            var res = srv.SendEmail(cl, mail);
        }
コード例 #13
0
        public virtual FileBytes GetBytesByUrl(string path)
        {
            string filePath = Path.Combine(_paths.RootFolderPath, path);
            var    b        = new FileBytes(filePath);

            if (b.Size == null)
            {
                throw new ArgumentOutOfRangeException("not found");
            }
            return(b);
        }
コード例 #14
0
        public virtual SubmitResult SaveAttachment(SaveAttachmentRequest req)
        {
            req.AttachmentTypeId = req.AttachmentTypeId == 0 ? DefaultAttachmentType : req.AttachmentTypeId;
            var cat = unit.AttachmentCategoryRepository.FindSingle(req.AttachmentTypeId);

            var path = Path.Combine(_paths.TempFolder, req.TmpPath);
            var dto  = new FileBytes(path);

            if (dto.Bytes == null)
            {
                return(new SubmitResult(1, "MSG_file_is_not_in_tmp"));
            }

            ValidateFiles(cat, new[] { dto });

            var att = new Attachment()
            {
                FileName             = req.Name,
                AttachmentCategoryId = req.AttachmentTypeId
            };

            string url = null;

            if (req.SaveInDb)
            {
                att.BinaryAttachment = new BinaryAttachment(dto.Bytes);
            }
            else
            {
                var root = _paths.RootFolderPath;
                var name = Guid.NewGuid();
                url          = Utils.CombineUrl(cat.FolderPath ?? "default", name.ToString() + dto.Extension);
                att.FullPath = Path.Combine(root, url).Replace("/", "\\");

                Utils.CreateFolderForFile(att.FullPath);
                File.WriteAllBytes(att.FullPath, dto.Bytes);
            }

            unit.AttachmentRepository.Add(att);
            var s = unit.SaveChanges();

            s.Data["FileData"] = new SavedFileDto
            {
                Id   = att.Id.ToString(),
                Path = url
            };
            return(s);
        }
コード例 #15
0
        private void UndoLastExcessBytesAfterSegmentRemoval()
        {
            Segment restoredSegment = RemovedSegments.Last();

            byte[] tmpBytes = new byte[FileBytes.Length + restoredSegment.Length];
            FileBytes.Take(restoredSegment.SegmentStartByteIndexInFile).ToArray().CopyTo(tmpBytes, 0);
            restoredSegment.Content.CopyTo(tmpBytes, restoredSegment.SegmentStartByteIndexInFile);
            FileBytes.Skip(restoredSegment.SegmentStartByteIndexInFile).ToArray().CopyTo(tmpBytes, restoredSegment.SegmentEndByteIndexInFile);
            FileBytes = tmpBytes;

            Segments[restoredSegment.SegmentIndexInFile].ExcessBytesAfterSegment = restoredSegment.Length;

            for (int i = restoredSegment.SegmentIndexInFile + 1; i < Segments.Count; i++)
            {
                Segments[i].SegmentStartByteIndexInFile += restoredSegment.Length;
                Segments[i].SegmentEndByteIndexInFile   += restoredSegment.Length;
            }

            RemovedSegments.RemoveAt(RemovedSegments.Count - 1);
        }
コード例 #16
0
        public virtual List <TmpFileData> Upload(Dictionary <string, IFormFile> files)
        {
            List <TmpFileData> lst = new List <TmpFileData>();

            foreach (var d in files)
            {
                using (MemoryStream str = new MemoryStream())
                {
                    d.Value.CopyTo(str);
                    byte[]      byts = str.ToArray();
                    var         bts  = new FileBytes(d.Value.FileName, byts);
                    TmpFileData data = FileUtils.AddToTemp(bts, d.Key);
                    if (data != null)
                    {
                        lst.Add(data);
                    }
                }
            }
            return(lst);
        }
コード例 #17
0
        public virtual FileBytes GetBytes(long id)
        {
            var att = unit.AttachmentRepository.FindSingle(id);

            if (att == null)
            {
                throw new ArgumentOutOfRangeException("not found");
            }

            if (att.BinaryAttachmentId != null)
            {
                var s = unit.AttachmentRepository.GetSingleValue(e => e.BinaryAttachment, e => e.Id == id);
                return(new FileBytes(att.FileName, s.Bytes));
            }
            else
            {
                var f = new FileBytes(att.FullPath);
                f.SetFileName(att.FileName);
                return(f);
            }
        }
コード例 #18
0
        public FileBytes ReadBytes(string path)
        {
            var bytes = new List <byte>(_numberOfBytes);

            using (StreamReader reader = new StreamReader(path))
            {
                for (var i = 0; i < _numberOfBytes; i++)
                {
                    if (reader.Peek() < 0)
                    {
                        break;
                    }

                    bytes.Add((byte)reader.Read());
                }
            }

            var res = new FileBytes(path, bytes);

            return(res);
        }
コード例 #19
0
        public void RemoveExcessBytesAfterSegment(int index)
        {
            if (index > Segments.Count)
            {
                return;
            }

            int numberOfExcessBytes       = Segments[index].ExcessBytesAfterSegment;
            int segmentEndByteIndexInFile = Segments[index].SegmentEndByteIndexInFile;

            byte[] removedBytes = FileBytes.Skip(segmentEndByteIndexInFile).Take(numberOfExcessBytes).ToArray();
            byte[] tmpBytes     = new byte[FileBytes.Length - numberOfExcessBytes];

            FileBytes.Take(segmentEndByteIndexInFile).ToArray().CopyTo(tmpBytes, 0);
            FileBytes.Skip(segmentEndByteIndexInFile + numberOfExcessBytes).ToArray().CopyTo(tmpBytes, segmentEndByteIndexInFile);

            FileBytes = tmpBytes;
            Segments[index].ExcessBytesAfterSegment = 0;
            RemovedSegments.Add(new Segment()
            {
                Length  = numberOfExcessBytes,
                Content = removedBytes,
                SegmentStartByteIndexInFile = segmentEndByteIndexInFile,
                SegmentEndByteIndexInFile   = segmentEndByteIndexInFile + numberOfExcessBytes,
                SegmentIndexInFile          = index
            });

            for (int i = index + 1; i < Segments.Count; i++)
            {
                Segments[i].SegmentStartByteIndexInFile -= numberOfExcessBytes;
                Segments[i].SegmentEndByteIndexInFile   -= numberOfExcessBytes;
            }

            Modified = true;
            ChangesHistory.Add(new Change()
            {
                TypeOfChange = ChangeType.ExcessBytesRemoval, UndoAction = UndoLastExcessBytesAfterSegmentRemoval
            });
        }
コード例 #20
0
        public virtual TmpFileData AddToTemp(FileBytes bts, string key)
        {
            if (bts.Size == null)
            {
                return(null);
            }
            var id          = Guid.NewGuid();
            var tmpPath     = "Tmp/" + id.ToString() + bts.Extension;
            var tmpFullPath = Path.Combine(TempRoot, tmpPath);

            Utils.CreateFolderForFile(tmpFullPath);
            File.WriteAllBytes(tmpFullPath, bts.Bytes);
            return(new TmpFileData
            {
                Url = tmpPath,
                Size = bts.Size ?? 0,
                TmpPath = tmpPath,
                UploadId = key,
                Name = bts.FileName,
                MimeType = bts.MimeType
            });
        }
コード例 #21
0
        public async Task EncodeRSA()
        {
            var segment = Segments.Find(i => i.Name == JPEGResources.SegmentNameDictionary[0xDA]);

            byte[] bytes = FileBytes.Take(segment.SegmentEndByteIndexInFile - 2).Skip(segment.SegmentStartByteIndexInFile + 20).ToArray();
            long   p     = 10007;
            long   q     = 10009;
            var    keys  = RSAService.ZnajdzWykladnikPublicznyiPrywatny(p, q);

            var result = RSAService.Encode(bytes, keys[0], p * q);

            int takeSkip = segment.SegmentEndByteIndexInFile - 2 - segment.SegmentStartByteIndexInFile - 20;

            result.Take(takeSkip)
            .ToArray()
            .CopyTo(FileBytes, segment.SegmentStartByteIndexInFile + 20);
            var newFileBytes = new byte[FileBytes.Length + result.Length - takeSkip];

            FileBytes.CopyTo(newFileBytes, 0);
            result.Skip(takeSkip).ToArray().CopyTo(newFileBytes, FileBytes.Length);
            FileBytes = newFileBytes;
            Modified  = true;
            await SaveFile();
        }
コード例 #22
0
        public async Task DecodeRSA()
        {
            var segment = Segments.Find(i => i.Name == JPEGResources.SegmentNameDictionary[0xDA]);

            byte[] bytes       = FileBytes.Take(segment.SegmentEndByteIndexInFile - 2).Skip(segment.SegmentStartByteIndexInFile + 20).ToArray();
            int    excessBytes = bytes.Length * 8 - bytes.Length;

            byte[] newBytes = new byte[bytes.Length * 8];
            bytes.CopyTo(newBytes, 0);
            FileBytes.Skip(FileBytes.Length - excessBytes).ToArray().CopyTo(newBytes, bytes.Length);
            long p = 10007;
            long q = 10009;

            var keys = RSAService.ZnajdzWykladnikPublicznyiPrywatny(p, q);

            var result = RSAService.Decode(newBytes, keys[1], p * q);

            result.CopyTo(FileBytes, segment.SegmentStartByteIndexInFile + 20);
            byte[] newFileBytes = new byte[FileBytes.Length - excessBytes];
            FileBytes.Take(FileBytes.Length - excessBytes).ToArray().CopyTo(newFileBytes, 0);
            FileBytes = newFileBytes;
            Modified  = true;
            await SaveFile();
        }
コード例 #23
0
        public void ReadFile()
        {
            FileBytes file = new FileBytes("testfile.txt");

            Assert.Equal(13, file.Bytes.Length);
        }