public void Write(BinaryWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            writer.WriteInt32BigEndian(9994);

            for (var index = 0; index < 20; index++)
            {
                writer.Write((byte)0x0);
            }

            writer.WriteInt32BigEndian(FileLength.ToInt32());
            writer.WriteInt32LittleEndian(1000);
            writer.WriteInt32LittleEndian((int)ShapeType);
            writer.WriteDoubleLittleEndian(BoundingBox.XMin);
            writer.WriteDoubleLittleEndian(BoundingBox.YMin);
            writer.WriteDoubleLittleEndian(BoundingBox.XMax);
            writer.WriteDoubleLittleEndian(BoundingBox.YMax);
            writer.WriteDoubleLittleEndian(BoundingBox.ZMin);
            writer.WriteDoubleLittleEndian(BoundingBox.ZMax);
            writer.WriteDoubleLittleEndian(EscapeNoData(BoundingBox.MMin));
            writer.WriteDoubleLittleEndian(EscapeNoData(BoundingBox.MMax));
        }
Пример #2
0
        private static void Count(string filePath, string fromDictionaryPath)
        {
            VerifyFileExists(filePath);
            VerifyFileExists(fromDictionaryPath);
            long tokenCount = 0;

            using (new ConsoleWatch($"Reading [Count] {filePath} ({FileLength.MB(filePath)})...",
                                    () => $"Done; {tokenCount:n0} tokens found in file"))
            {
                if (filePath.EndsWith(".bion", StringComparison.OrdinalIgnoreCase))
                {
                    using (WordCompressor compressor = (fromDictionaryPath == null ? null : WordCompressor.OpenRead(fromDictionaryPath)))
                        using (BionReader reader = new BionReader(File.OpenRead(filePath), compressor: compressor))
                        {
                            while (reader.Read())
                            {
                                tokenCount++;
                            }
                        }
                }
                else
                {
                    using (JsonTextReader reader = new JsonTextReader(new StreamReader(filePath)))
                    {
                        while (reader.Read())
                        {
                            tokenCount++;
                        }
                    }
                }
            }
        }
Пример #3
0
        private static void Skip(string filePath, string fromDictionaryPath)
        {
            VerifyFileExists(filePath);
            VerifyFileExists(fromDictionaryPath);

            using (new ConsoleWatch($"Reading [Skip All] {filePath} ({FileLength.MB(filePath)})..."))
            {
                if (filePath.EndsWith(".bion", StringComparison.OrdinalIgnoreCase))
                {
                    using (WordCompressor compressor = (fromDictionaryPath == null ? null : WordCompressor.OpenRead(fromDictionaryPath)))
                        using (BionReader reader = new BionReader(File.OpenRead(filePath), compressor: compressor))
                        {
                            reader.Skip();
                        }
                }
                else
                {
                    using (JsonTextReader reader = new JsonTextReader(new StreamReader(filePath)))
                    {
                        reader.Read();
                        reader.Skip();
                    }
                }
            }
        }
        public void ToString_Test(long length, string format, string expectedValue)
        {
            var fileLength = new FileLength(length);
            var actual     = fileLength.ToString(format, CultureInfo.InvariantCulture);

            Assert.AreEqual(expectedValue, actual);
        }
Пример #5
0
        public override string Run(string strFileName)
        {
            int     len = FileLength.ToString().Length;
            decimal cnt = Start + Step * RunCount++;

            return(base.Run(IsSamp ? cnt.ToString().PadLeft(len, '0') : cnt.ToString()));
        }
Пример #6
0
        private IResult Test(IFormFile file) //Dosya boyutu ne?
        {
            //var sourcepath = Path.GetTempFileName();
            //FileInfo fileInfo = new FileInfo(sourcepath);
            //long fileLength = fileInfo.Length;

            return(new ErrorResult("Dosya boyutu : " + FileLength.CalculateLength(file.Length)));
        }
Пример #7
0
        private static void Compress(string fromPath, string toPath, string toDictionaryPath)
        {
            VerifyFileExists(fromPath);

            using (new ConsoleWatch($"Compressing {fromPath}...",
                                    () => $"Done. {FileLength.MB(fromPath)} to {FileLength.MB(toPath)} + {FileLength.MB(toDictionaryPath)} dictionary ({FileLength.Percentage(fromPath, toPath, toDictionaryPath)})"))
            {
                WordCompressor.Compress(fromPath, toPath, toDictionaryPath);
            }
        }
Пример #8
0
        private static void ToBion(string jsonPath, string bionPath, string dictionaryPath)
        {
            VerifyFileExists(jsonPath);

            using (new ConsoleWatch($"Converting {jsonPath} to {bionPath}...",
                                    () => $"Done. {FileLength.MB(jsonPath)} JSON to {FileLength.MB(bionPath)} BION{(String.IsNullOrEmpty(dictionaryPath) ? "" : $" + {FileLength.MB(dictionaryPath)} dictionary")} ({FileLength.Percentage(jsonPath, bionPath, dictionaryPath)})"))
            {
                JsonBionConverter.JsonToBion(jsonPath, bionPath, dictionaryPath);
            }
        }
        public int CompareTo(object obj)
        {
            if (!(obj is SimpleFileInfo))
            {
                throw new ArgumentException("Incorrect type in SimpleCompare.CompareTo!");
            }

            SimpleFileInfo other = (SimpleFileInfo)obj;

            return(FileName.CompareTo(other.FileName) == 0 ? FileLength.CompareTo(other.FileLength) : FileName.CompareTo(other.FileName));
        }
Пример #10
0
        private static void Expand(string fromPath, string toPath, string fromDictionaryPath)
        {
            VerifyFileExists(fromPath);
            VerifyFileExists(fromDictionaryPath);

            using (new ConsoleWatch($"Expanding {fromPath}...",
                                    () => $"Done. {FileLength.MB(fromPath)} + {FileLength.MB(fromDictionaryPath)} dictionary to {FileLength.MB(toPath)}"))
            {
                WordCompressor.Expand(fromPath, toPath, fromDictionaryPath);
            }
        }
Пример #11
0
        private static void ToJson(string fromPath, string toPath, string dictionaryPath)
        {
            VerifyFileExists(fromPath);
            VerifyFileExists(dictionaryPath);

            using (new ConsoleWatch($"Converting {fromPath} to {toPath}...",
                                    () => $"Done. {FileLength.MB(fromPath)} BION to {FileLength.MB(toPath)} JSON"))
            {
                JsonBionConverter.BionToJson(fromPath, toPath, dictionaryPath);
            }
        }
Пример #12
0
 public override int GetHashCode()
 {
     return
         (FileID?.GetHashCode() ?? 0 ^
          FileLength.GetHashCode() ^
          FileName?.GetHashCode() ?? 0 ^
          FileShardIDs?.GetHashCodeEnumerable() ?? 0 ^
          FileShardHashes?.GetHashCodeEnumerable() ?? 0 ^
          LastModified.GetHashCode() ^
          SHA1?.GetHashCode() ?? 0);
 }
Пример #13
0
        //возвращает ассоциативный массив (словарь) со всеми вычисленными настройками
        public Dictionary <String, String> GetAllInfo()
        {
            Dictionary <String, String> info = new Dictionary <string, string>();

            info.Add("Имя файла", FileName);
            info.Add("Путь до файла", Path);
            info.Add("Длина файла", FileLength.ToString());
            info.Add("Дата создания файла", FileCreatedDate.ToString());
            info.Add("Состояние файла", CheckState());

            return(info);
        }
Пример #14
0
        public static bool SizeRatioUnder(string originalFile, string actualFile, float maximumSizePercentage)
        {
            long originalSize = new FileInfo(originalFile).Length;
            long actualSize   = new FileInfo(actualFile).Length;

            Trace.WriteLine($"{originalFile} => {FileLength.MB(originalSize)}");
            Trace.WriteLine($"{actualFile} => {FileLength.MB(actualSize)}");

            bool isSmallEnough = actualSize <= originalSize * maximumSizePercentage;

            Assert.IsTrue(isSmallEnough, $"{actualFile} was {FileLength.MB(actualSize)}, which was over {maximumSizePercentage:p0} of {originalFile} size {FileLength.MB(originalSize)}.");
            return(isSmallEnough);
        }
        public double ConvertFileLength(long lengthInBytes, FileLength converTo)
        {
            const double Factor = 1024;

            switch (converTo)
            {
                case FileLength.KB:
                    return lengthInBytes / Factor;
                case FileLength.MB:
                    return lengthInBytes / Math.Pow(2, Factor);
                default:
                    return lengthInBytes;
            }
        }
Пример #16
0
 public override void Write(BinaryWriter writer, IShapefileHeader value, WordCount origin)
 {
     FileCode.Write(writer, FileCodeValue, origin); //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     Unused1.Write(writer, UnusedValue, origin);    //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     Unused2.Write(writer, UnusedValue, origin);    //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     Unused3.Write(writer, UnusedValue, origin);    //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     Unused4.Write(writer, UnusedValue, origin);    //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     Unused5.Write(writer, UnusedValue, origin);    //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     FileLength.Write(writer, value.FileLength, origin);
     Version.Write(writer, VersionValue, origin);   //TODO: ShapefileHeader should be constructed with this const value... then we write the property value.
     ShapeType.Write(writer, value.ShapeType, origin);
     BoxMin.Write(writer, value.BoundingBox.Min, origin);
     BoxMax.Write(writer, value.BoundingBox.Max, origin);
 }
        private byte[] commonAction(string _name, MainModel.LogType _type)
        {
            string message = "Отправляем информацию о файле;";

            log(message, _type, MainModel.ModelPart.Server);

            model.server.networkStream = model.server.user.TcpClient.GetStream();

            byte[] byteSend = new byte[model.server.user.TcpClient.ReceiveBufferSize];


            FileInfo fInfo = new FileInfo(model.server.serverWatcher.Path + "\\" + _name);

            message = "Отправляем команду - " + model.server.Command + ";";

            log(message, _type, MainModel.ModelPart.Server);

            byte[] ByteCommand = new byte[MainModel.FIXED_BUFFER_SIZE];
            ByteCommand = System.Text.Encoding.UTF8.GetBytes(model.server.Command.ToCharArray());
            model.server.networkStream.Write(ByteCommand, 0, ByteCommand.Length);


            string FileName = fInfo.Name;


            byte[] ByteFileName = new byte[MainModel.MAX_BYTES_BUFFER_SIZE];
            ByteFileName = System.Text.Encoding.UTF8.GetBytes(FileName.ToCharArray());


            string FileLength;

            makeFormatedLenght(ref ByteFileName, out FileLength);

            message = "Отправляем длину имени - " + FileLength + ";";

            log(message, _type, MainModel.ModelPart.Server);

            byte[] ByteFileNameLength = new byte[MainModel.FIXED_BUFFER_SIZE];

            ByteFileNameLength = System.Text.Encoding.UTF8.GetBytes(FileLength.ToCharArray());
            model.server.networkStream.Write(ByteFileNameLength, 0, ByteFileNameLength.Length);

            message = "Отправляем имя - " + FileName + ";";
            log(message, _type, MainModel.ModelPart.Server);

            model.server.networkStream.Write(ByteFileName, 0, ByteFileName.Length);

            return(ByteFileName);
        }
Пример #18
0
        private static void AddWhitespace(string fromJsonPath, string toJsonPath)
        {
            VerifyFileExists(fromJsonPath);

            using (new ConsoleWatch($"Writing {fromJsonPath} with formatting to {toJsonPath}...",
                                    () => $"Done; {FileLength.MB(fromJsonPath)} => {FileLength.MB(toJsonPath)} ({FileLength.Percentage(fromJsonPath, toJsonPath)})"))
            {
                using (JsonTextReader reader = new JsonTextReader(new StreamReader(fromJsonPath)))
                    using (JsonTextWriter writer = new JsonTextWriter(new StreamWriter(toJsonPath)))
                    {
                        writer.Formatting = Formatting.Indented;
                        writer.WriteToken(reader);
                    }
            }
        }
Пример #19
0
 public override IShapefileHeader Read(BinaryReader reader, WordCount origin)
 {
     return(new ShapefileHeader()
     {
         BoundingBox = new BoundingBox <IPointZ>()
         {
             Min = BoxMin.Read(reader, origin),
             Max = BoxMax.Read(reader, origin)
         },
         FileCode = FileCode.Read(reader, origin),
         FileLength = FileLength.Read(reader, origin),
         ShapeType = (ShapeType)ShapeType.Read(reader, origin),
         Version = Version.Read(reader, origin)
     });
 }
        public double ConvertFileLength(long lengthInBytes, FileLength converTo)
        {
            const double Factor = 1024;

            switch (converTo)
            {
            case FileLength.KB:
                return(lengthInBytes / Factor);

            case FileLength.MB:
                return(lengthInBytes / Math.Pow(2, Factor));

            default:
                return(lengthInBytes);
            }
        }
Пример #21
0
        public List <KeyValuePair <string, string> > ToKeyValuePairs()
        {
            var result = new List <KeyValuePair <string, string> >(10);

            // leave out null values, but string.Empty is preserved
            if (FileName != null)
            {
                result.Add("FileName", FileName);
            }

            if (ContentId > 0)
            {
                result.Add("ContentId", ContentId.ToString());
            }

            if (ContentType != null)
            {
                result.Add("ContentType", ContentType);
            }
            if (PropertyName != null)
            {
                result.Add("PropertyName", PropertyName);
            }

            result.Add("UseChunk", UseChunk.ToString());
            result.Add("Overwrite", Overwrite.ToString());
            result.Add("FileLength", FileLength.ToString());

            if (ChunkToken != null)
            {
                result.Add("ChunkToken", ChunkToken);
            }

            if (FileText != null)
            {
                result.Add("FileText", FileText);
            }

            return(result);
        }
Пример #22
0
 protected string GenerateEntityTag()
 {
     //Generate entity tag based on file name and length
     byte[] entityTagBytes = Encoding.ASCII.GetBytes(String.Format("{0}|{1}", FileName, FileLength.ToString()));
     return("W/" + Convert.ToBase64String(new MD5CryptoServiceProvider().ComputeHash(entityTagBytes)));
 }
Пример #23
0
        private static void Read(string filePath, string fromDictionaryPath)
        {
            VerifyFileExists(filePath);
            VerifyFileExists(fromDictionaryPath);
            long tokenCount = 0;

            using (new ConsoleWatch($"Reading [Full] {filePath} ({FileLength.MB(filePath)})...",
                                    () => $"Done; {tokenCount:n0} tokens found in file"))
            {
                if (filePath.EndsWith(".bion", StringComparison.OrdinalIgnoreCase))
                {
                    using (WordCompressor compressor = (fromDictionaryPath == null ? null : WordCompressor.OpenRead(fromDictionaryPath)))
                        using (BionReader reader = new BionReader(File.OpenRead(filePath), compressor: compressor))
                        {
                            while (reader.Read())
                            {
                                tokenCount++;

                                switch (reader.TokenType)
                                {
                                case BionToken.PropertyName:
                                case BionToken.String:
                                    String8 value8 = reader.CurrentString8();
                                    //string valueS = reader.CurrentString();
                                    break;

                                case BionToken.Integer:
                                    long valueI = reader.CurrentInteger();
                                    break;

                                case BionToken.Float:
                                    double valueF = reader.CurrentFloat();
                                    break;
                                }
                            }
                        }
                }
                else
                {
                    using (JsonTextReader reader = new JsonTextReader(new StreamReader(filePath)))
                    {
                        while (reader.Read())
                        {
                            tokenCount++;

                            switch (reader.TokenType)
                            {
                            case JsonToken.PropertyName:
                            case JsonToken.String:
                                string valueS = (string)reader.Value;
                                break;

                            case JsonToken.Integer:
                                long valueI = (long)reader.Value;
                                break;

                            case JsonToken.Float:
                                double valueF = (double)reader.Value;
                                break;
                            }
                        }
                    }
                }
            }
        }
 public bool Equals(ShapeFileHeader other) =>
 other != null &&
 FileLength.Equals(other.FileLength) &&
 ShapeType.Equals(other.ShapeType) &&
 BoundingBox.Equals(other.BoundingBox);
        private void renameFileForUser(string _name, string _newName)
        {
            string message = "Отправляем информацию о файле;";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            model.server.networkStream = model.server.user.TcpClient.GetStream();
            byte[] byteSend = new byte[model.server.user.TcpClient.ReceiveBufferSize];

            FileInfo fInfoOld = new FileInfo(model.server.serverWatcher.Path + "\\" + _name);
            FileInfo fInfoNew = new FileInfo(model.server.serverWatcher.Path + "\\" + _newName);

            message = "Отправляем команду - " + model.server.Command + ";";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            byte[] ByteCommand = new byte[MainModel.FIXED_BUFFER_SIZE];
            ByteCommand = System.Text.Encoding.UTF8.GetBytes(model.server.Command.ToCharArray());
            model.server.networkStream.Write(ByteCommand, 0, ByteCommand.Length);

            string FileNameOld = fInfoOld.Name;
            string FileNameNew = fInfoNew.Name;

            byte[] ByteFileName = new byte[MainModel.MAX_BYTES_BUFFER_SIZE];
            ByteFileName = System.Text.Encoding.UTF8.GetBytes(FileNameOld.ToCharArray());

            string FileLength;

            makeFormatedLenght(ref ByteFileName, out FileLength);

            message = "Отправляем длину старого имени - " + FileLength + ";";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            byte[] ByteFileNameLength = new byte[MainModel.FIXED_BUFFER_SIZE];
            ByteFileNameLength = System.Text.Encoding.UTF8.GetBytes(FileLength.ToCharArray());
            model.server.networkStream.Write(ByteFileNameLength, 0, ByteFileNameLength.Length);


            message = ByteFileName.Length.ToString() + " - длина имени файла" + ";";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            message = "Отправляем имя - " + FileNameOld + ";";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            model.server.networkStream.Write(ByteFileName, 0, ByteFileName.Length);

            log("Старое имя отправлено;", MainModel.LogType.Rename, MainModel.ModelPart.Server);

            byte[] ByteFileNewName = new byte[MainModel.MAX_BYTES_BUFFER_SIZE];
            ByteFileNewName = System.Text.Encoding.UTF8.GetBytes(FileNameNew.ToCharArray());

            string NewFileLength = "";

            for (int count = 0; count < 2 - ByteFileNewName.Length.ToString().Length; count++)
            {
                NewFileLength += "0";
            }

            NewFileLength += "0" + ByteFileNewName.Length.ToString();

            message = "Отправляем длину новго имени - " + NewFileLength + ";";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            byte[] ByteFileNewNameLength = new byte[MainModel.FIXED_BUFFER_SIZE];
            ByteFileNewNameLength = System.Text.Encoding.UTF8.GetBytes(NewFileLength.ToCharArray());
            model.server.networkStream.Write(ByteFileNewNameLength, 0, ByteFileNewNameLength.Length);

            message = ByteFileNewName.Length.ToString() + " - длина имени файла;";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            message = "Отправляем имя - " + FileNameNew + ";";

            log(message, MainModel.LogType.Rename, MainModel.ModelPart.Server);

            model.server.networkStream.Write(ByteFileNewName, 0, ByteFileNewName.Length);

            log("Новое имя отправлено;", MainModel.LogType.Rename, MainModel.ModelPart.Server);

            model.server.fileStream.Close();

            log("Файл переименован у всех пользователям;", MainModel.LogType.Rename, MainModel.ModelPart.Server);
            log("Все потоки закрыты", MainModel.LogType.Rename, MainModel.ModelPart.Server);
        }
Пример #26
0
        public async Task Extract()
        {
            TotalWords = (await mRead(64)).GetValueOrDefault();
            FileLength?.Invoke(TotalWords);
            mMaxHistory    = Convert.ToUInt32((await mRead(32)).GetValueOrDefault());
            mPresentLength = Convert.ToInt32((await mRead(8)).GetValueOrDefault());
            int historyLengthInBits = Log2_WiegleyJ(mMaxHistory - 1) + 1;

            while (mWordsWritten < TotalWords)
            {
                var type = await mRead(1);

                if (type == null)
                {
                    throw new EndOfStreamException();
                }

                if (type.Value == 1)
                {
                    var word = await mRead(8);

                    if (word == null)
                    {
                        throw new EndOfStreamException();
                    }
                    await mWrite(word.Value, 8);

                    mHistory.AddLast(Convert.ToByte(word.Value));
                    if (mHistory.Count > mMaxHistory)
                    {
                        mHistory.RemoveFirst();
                    }

                    mWordsWritten++;
                    WordsWritten?.Invoke(1);
                }
                else if (type.Value == 0)
                {
                    var offset = await mRead(historyLengthInBits);

                    var length = await mRead(mPresentLength);

                    if (offset == null || length == null)
                    {
                        throw new EndOfStreamException();
                    }

                    if (offset >= mHistory.Count)
                    {
                        throw new ArgumentOutOfRangeException(nameof(offset));
                    }

                    if (offset < length - 1)
                    {
                        throw new ArgumentOutOfRangeException(nameof(length));
                    }

                    var pointer = mHistory.Last;
                    for (int i = 0; i < offset.Value; i++)
                    {
                        pointer = pointer.Previous;
                    }
                    for (int i = 0; i < length.Value; i++)
                    {
                        mHistory.AddLast(pointer.Value);
                        await mWrite(pointer.Value, 8);

                        pointer = pointer.Next;
                        if (mHistory.Count > mMaxHistory)
                        {
                            mHistory.RemoveFirst();
                        }
                    }

                    mWordsWritten += length.Value;
                    WordsWritten?.Invoke(length.Value);
                }
                else
                {
                    throw new ArgumentOutOfRangeException(nameof(type));
                }
            }
        }
Пример #27
0
        private int GetContentLength(string boundary)
        {
            int contentLength = 0;

            for (int i = 0; i < RangesStartIndexes.Length; i++)
            {
                contentLength += Convert.ToInt32(RangesEndIndexes[i] - RangesStartIndexes[i]) + 1;

                if (MultipartRequest)
                {
                    contentLength += boundary.Length + ContentType.Length + RangesStartIndexes[i].ToString().Length + RangesEndIndexes[i].ToString().Length + FileLength.ToString().Length + 49;
                }
            }

            if (MultipartRequest)
            {
                contentLength += boundary.Length + 4;
            }

            return(contentLength);
        }
Пример #28
0
        /// <summary>
        /// Enables processing of the result of an action method by a custom type that inherits from the ActionResult class. (Overrides ActionResult.ExecuteResult(ControllerContext).)
        /// </summary>
        /// <param name="context">The context within which the result is executed.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            EntityTag = GenerateEntityTag(context);
            GetRanges(context.HttpContext.Request);

            if (ValidateRanges(context.HttpContext.Response) && ValidateModificationDate(context.HttpContext.Request, context.HttpContext.Response) && ValidateEntityTag(context.HttpContext.Request, context.HttpContext.Response))
            {
                context.HttpContext.Response.AddHeader("Last-Modified", HttpModificationDate.ToString("r"));
                context.HttpContext.Response.AddHeader("ETag", String.Format("\"{0}\"", EntityTag));
                context.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");

                if (!RangeRequest)
                {
                    context.HttpContext.Response.AddHeader("Content-Length", FileLength.ToString());
                    context.HttpContext.Response.ContentType = ContentType;
                    context.HttpContext.Response.StatusCode  = 200;
                    if (!context.HttpContext.Request.HttpMethod.Equals("HEAD"))
                    {
                        WriteEntireEntity(context.HttpContext.Response);
                    }
                }
                else
                {
                    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

                    context.HttpContext.Response.AddHeader("Content-Length", GetContentLength(boundary).ToString());
                    if (!MultipartRequest)
                    {
                        context.HttpContext.Response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", RangesStartIndexes[0], RangesEndIndexes[0], FileLength));
                        context.HttpContext.Response.ContentType = ContentType;
                    }
                    else
                    {
                        context.HttpContext.Response.ContentType = String.Format("multipart/byteranges; boundary={0}", boundary);
                    }
                    context.HttpContext.Response.StatusCode = 206;
                    if (!context.HttpContext.Request.HttpMethod.Equals("HEAD"))
                    {
                        for (int i = 0; i < RangesStartIndexes.Length; i++)
                        {
                            if (MultipartRequest)
                            {
                                context.HttpContext.Response.Write(String.Format("--{0}\r\n", boundary));
                                context.HttpContext.Response.Write(String.Format("Content-Type: {0}\r\n", ContentType));
                                context.HttpContext.Response.Write(String.Format("Content-Range: bytes {0}-{1}/{2}\r\n\r\n", RangesStartIndexes[i], RangesEndIndexes[i], FileLength));
                            }

                            if (context.HttpContext.Response.IsClientConnected)
                            {
                                WriteEntityRange(context.HttpContext.Response, RangesStartIndexes[i], RangesEndIndexes[i]);
                                if (MultipartRequest)
                                {
                                    context.HttpContext.Response.Write("\r\n");
                                }
                            }
                            else
                            {
                                return;
                            }
                        }
                        if (MultipartRequest)
                        {
                            context.HttpContext.Response.Write(String.Format("--{0}--", boundary));
                        }
                    }
                }
            }
        }
 public override int GetHashCode()
 => FileLength.GetHashCode() ^ ShapeType.GetHashCode() ^ BoundingBox.GetHashCode();
Пример #30
0
 public int CompareTo(DownloadableImageLink other)
 {
     return(FileLength.CompareTo(other.FileLength));
 }
Пример #31
0
        public void ManageMultipartDownload(/*Byte[] content, String name, HttpRequest request, HttpResponse response*/)
        {
            //Request = request;
            //Response = response;
            //FileName = name;
            ////if (FileContent == null)
            ////    FileContent = File.ReadAllBytes(FilePath);
            //FileLength = content.Length;
            //FileContent = content;
            //ContentType = "application/pdf";
            //Generate entity tag
            EntityTag = GenerateEntityTag();
            //Get ranges from request
            GetRanges(Request);

            //If all validations are successful
            if (ChangeSignature || Validate(Request, Response))
            {
                //Set common headers
                //Response.Buffer = false;
                Response.AddHeader("Last-Modified", FileModificationDate.ToString("r"));
                Response.AddHeader("ETag", String.Format("\"{0}\"", EntityTag));
                //Response.Cache.SetCacheability(HttpCacheability.Public); //required for etag output
                //Response.Cache.SetETag(EntityTag);
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "inline;filename=" + FileName);
                //If this is not range Request
                if (!RangeRequest)
                {
                    //Set standard headers
                    Response.AddHeader("Content-Length", FileLength.ToString());
                    //Response.AddHeader("Content-Type", "application/pdf");
                    //Set status code
                    Response.StatusCode = 200;

                    //If this is not HEAD Request
                    if (!Request.HttpMethod.Equals("HEAD"))
                    {
                        //Write entire file to Response
                        Console.WriteLine("Request.HttpMethod : " + Request.HttpMethod);
                        Console.WriteLine("Write entire file to Response");
                        WriteEntireEntity(Response);
                    }
                }
                //If this is range Request
                else
                {
                    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

                    //Compute and set content length
                    Response.AddHeader("Content-Length", GetContentLength(boundary).ToString());

                    //If this is not multipart Request
                    if (!MultipartRequest)
                    {
                        //Set content range and type
                        Response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", RangesStartIndexes[0], RangesEndIndexes[0], FileLength));
                        Response.ContentType = ContentType;
                    }
                    //Otherwise
                    else
                    {
                        //Set proper content type
                        Response.ContentType = String.Format("multipart/byteranges; boundary={0}", boundary);
                    }

                    //Set status code
                    Response.StatusCode = 206;

                    //If this not HEAD Request
                    if (!Request.HttpMethod.Equals("HEAD"))
                    {
                        //For each Requested range
                        for (int i = 0; i < RangesStartIndexes.Length; i++)
                        {
                            //If this is multipart Request
                            if (MultipartRequest)
                            {
                                //Write additional multipart info
                                Response.Write(String.Format("--{0}\r\n", boundary));
                                Response.Write(String.Format("Content-Type: {0}\r\n", ContentType));
                                Response.Write(String.Format("Content-Range: bytes {0}-{1}/{2}\r\n\r\n", RangesStartIndexes[i], RangesEndIndexes[i], FileLength));
                            }

                            //Write range (with multipart separator if required)
                            if (Response.IsClientConnected)
                            {
                                Console.Write("WriteEntityRange");
                                WriteEntityRange(Response, RangesStartIndexes[i], RangesEndIndexes[i]);
                                if (MultipartRequest)
                                {
                                    Response.Write("\r\n");
                                }
                                Response.Flush();
                            }
                            else
                            {
                                return;
                            }
                        }

                        //If this is multipart Request
                        if (MultipartRequest)
                        {
                            Response.Write(String.Format("--{0}--", boundary));
                        }
                    }
                }
            }
        }