public static string ReadNullTermString(this BinaryReader reader)
 {
     var bytes = new List<byte>();
     byte b;
     while((b=reader.ReadByte())!=0)
         bytes.Add(b);
     return bytes.AsString();
 }
Exemple #2
0
        protected string ReplaceBlockTokens(IPage Page, string Content, IContentContainer ContentContainer)
        {
            // Link
            for (int i = 0; i < this.RegexLinkTokens.Length; i++)
            {
                while (Regex.IsMatch(Content, this.RegexLinkTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                {
                    Content = Regex.Replace(Content, this.RegexLinkTokens[i], Page.Type == FileType.Static ? Page.URL : "[MenuLink]");
                }
            }

            // Token
            for (int i = 0; i < this.RegexTokenTokens.Length; i++)
            {
                while (Regex.IsMatch(Content, this.RegexTokenTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                {
                    if (!Regex.IsMatch(Content, this.RegexTokenTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                    {
                        continue;
                    }

                    MatchCollection matchCollection = Regex.Matches(Content, this.RegexTokenTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

                    for (int k = 0; k < matchCollection.Count; k++)
                    {
                        List <string> extensions = this.GetExtensions(matchCollection[k].Value);

                        while (Content.Contains(matchCollection[k].Value))
                        {
                            Content = Content.ReplaceOne(matchCollection[k].Value,
                                                         Page.Type == FileType.Static
                                                               ? this.ProcessExtensions(Page.Keywords, extensions)
                                                               : "[MenuKeyword" + (extensions.Count == 0 ? string.Empty : ":" + extensions.AsString(":")) + "]");
                        }
                    }
                }
            }

            return(Content);
        }
Exemple #3
0
        public string Invoke(IPage Page, IContentContainer ContentContainer)
        {
            string content = Page.Content;

            List <IPage> pages = (from IPage item in ContentContainer.Pages
                                  where item.Type == FileType.Static
                                  select item).ToList();

            IPage mainpage = (from IPage item in ContentContainer.Pages
                              where item.Type == FileType.Index && item.ContinueNumber == 0
                              select item).First();

            for (int i = 0; i < this.RegexTokens.Length; i++)
            {
                if (!Regex.IsMatch(content, this.RegexTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                {
                    continue;
                }

                while (Regex.IsMatch(content, this.RegexTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                {
                    string tokenStart      = string.Empty;
                    int    tokenStartIndex = 0;

                    string tokenEnd      = Regex.Match(content, this.RegexTokensStart[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline).Value;
                    int    tokenEndIndex = content.IndexOf(tokenEnd);

                    MatchCollection tokenStartMatchCollection = Regex.Matches(content, this.RegexTokensStart[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    tokenStartIndex = content.IndexOf(tokenStartMatchCollection[0].Value);

                    // Looking for last [staticblock:X:X] before [/staticblock]
                    for (int k = 0; k < tokenStartMatchCollection.Count; k++)
                    {
                        int tokenIndex = content.LastIndexOf(this.RegexTokensStart[i], tokenStartMatchCollection[k].Value, tokenEndIndex);
                        if (tokenEndIndex < tokenIndex || tokenIndex < 0)
                        {
                            break;
                        }

                        tokenStartIndex = tokenIndex;
                    }

                    // Replacing
                    string tokenValue = content.Substring(tokenStartIndex, tokenEndIndex + tokenEnd.Length - tokenStartIndex);
                    content = content.Remove(tokenStartIndex, tokenEndIndex + tokenEnd.Length - tokenStartIndex);

                    tokenStart = Regex.Match(tokenValue, this.RegexTokensStart[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline).Value;

                    // Minimum and maximum
                    List <int> minmax = this.GetMinMaxExtensions(tokenStart);

                    int multiplyCount = this.Random.Next(minmax[0], minmax[1]);
                    if (minmax[0] == 0 && minmax[1] == 0)
                    {
                        multiplyCount = pages.Count;
                    }

                    // Preparing content to multiply
                    tokenValue = tokenValue.Replace(tokenStart, pages.Count != 0 ? string.Empty : string.Format("[MenuBlock:{0}:{1}]", minmax[0], minmax[1]));
                    tokenValue = tokenValue.Replace(tokenEnd, pages.Count != 0 ? string.Empty : "[/MenuBlock]");

                    // Multiplying
                    int           pageIndex    = 0;
                    StringBuilder blockContent = new StringBuilder(tokenValue.Length * multiplyCount);
                    for (int k = 0; k < multiplyCount; k++)
                    {
                        if (pages.Count == 0)
                        {
                            blockContent.Append(this.ReplaceBlockTokens(mainpage, tokenValue, ContentContainer));
                        }
                        else
                        {
                            if (pages.Count <= pageIndex)
                            {
                                pageIndex = 0;
                            }

                            blockContent.Append(this.ReplaceBlockTokens(pages[pageIndex], tokenValue, ContentContainer));
                            pageIndex++;
                        }
                    }

                    // Inserting new content
                    content = content.Insert(tokenStartIndex, blockContent.ToString());
                }

                // Cleaning for left tokens
                content = Regex.Replace(content, this.RegexTokensStart[i], string.Empty, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                content = Regex.Replace(content, this.RegexTokensEnd[i], string.Empty, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }

            // Replace out of blocks tokens
            // Tokens
            for (int i = 0; i < this.RegexTokenTokens.Length; i++)
            {
                if (!Regex.IsMatch(content, this.RegexTokenTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                {
                    continue;
                }

                MatchCollection matchCollection = Regex.Matches(content, this.RegexTokenTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

                for (int k = 0; k < matchCollection.Count; k++)
                {
                    List <string> extensions = this.GetExtensions(matchCollection[k].Value);

                    while (content.Contains(matchCollection[k].Value))
                    {
                        content = content.ReplaceOne(matchCollection[k].Value,
                                                     Page.Type == FileType.Static
                                                           ? this.ProcessExtensions(Page.Keywords, extensions)
                                                           : "[Keyword" + (extensions.Count == 0 ? string.Empty : ":" + extensions.AsString(":")) + "]");
                    }
                }
            }

            // Links
            for (int i = 0; i < this.RegexLinkTokens.Length; i++)
            {
                if (!Regex.IsMatch(content, this.RegexLinkTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline))
                {
                    continue;
                }

                MatchCollection matchCollection = Regex.Matches(content, this.RegexLinkTokens[i], RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

                for (int k = 0; k < matchCollection.Count; k++)
                {
                    while (content.Contains(matchCollection[k].Value))
                    {
                        content = content.ReplaceOne(matchCollection[k].Value, Page.Type == FileType.Static ? Page.URL : "[KeywordLink]");
                    }
                }
            }

            return(content);
        }
 public static String GetRoleString(params String[] roles)
 {
     List<String> items = new List<string>(roles);
     return items.AsString<String>(",");
 }
Exemple #5
0
 public static string Join <T>(this List <T> list, string separator = ";")
 {
     return(list.AsString(separator));
 }
Exemple #6
0
 public WhileNode(List <Token <TokenType> > condition, LexerPosition linePosition) : base(linePosition)
 {
     this.condition = condition.AsString();
 }
Exemple #7
0
        public static void Main(string[] args)
        {
            if (args.Length > 1 && args[0] == "--prod")
            {
                Console.WriteLine($"Assembly      = {Directory.GetParent(typeof(Program).Assembly.Location).FullName}");
                Console.WriteLine($"BaseDirectory = {AppDomain.CurrentDomain.BaseDirectory}");
                Console.WriteLine($"GetCurrentDir = {Directory.GetCurrentDirectory()}");
                Directory.SetCurrentDirectory(Directory.GetParent(typeof(Program).Assembly.Location).FullName);
                Console.WriteLine($"GetCurrentDir = {Directory.GetCurrentDirectory()}");
            }

            if (args.Length > 0 && args[0] == "--docs" || true.Equals(false))
            {
                var docs = "../docs/";
                Directory.CreateDirectory(docs);
                var sections = new List <string>
                {
                    DocGeneration.For <CourseProblem>(),
                    DocGeneration.For <CourseProblemCollaborationConfig>(),
                    DocGeneration.For <CourseProblemCase>(),
                    DocGeneration.For <CourseReference>(),
                };
                File.WriteAllText($"{docs}/README.md", sections.AsString("\n\n\n"));
                return;
            }

            if (args.Length > 0 && args[0] == "--generate")
            {
                var enumImports = new List <Type> {
                    typeof(ProcessStatus),
                    typeof(SubmissionStatus),
                    typeof(ProblemType),
                    typeof(ProblemStatus),
                    typeof(CcEventType),
                    typeof(CcUserGroupStatus),
                    typeof(DiffResultLineType),
                    typeof(ProcessStatusCodes),
                    typeof(ChangeType),
                };

                Directory.CreateDirectory("_client/src/models/");
                var destModelPath    = "_client/src/models/DataModel.d.ts";
                var modelDefinitions = TypeScript.Definitions();

                enumImports.ForEach(T =>
                {
                    modelDefinitions = modelDefinitions.RegisterTypeConvertor(T, i => T.Name);
                });

                modelDefinitions = modelDefinitions
                                   .For <User>()
                                   .For <Language>()
                                   .For <Course>()
                                   .For <CcData>()
                                   .For <CcEvent>()
                                   .For <CcDataAgg>()
                                   .For <MarkSolutionItem>()
                                   .For <TableRequest>()
                                   .For <TableResponse>()
                                   .For <SingleCourse>()
                                   .For <ProcessStatus>()
                                   .For <CommentServiceItem>()
                                   .For <GradeDto>()
                                   .For <StudentScoreboardCourse>()
                                   .For <CcGroup>()
                                   .For <UnauthorizedObjectIface>()
                                   .For <SimpleFileDto>()

                                   .For <ApiError>()
                                   .For <CcDataDto>()
                                   .For <CcDataLight>()

                                   .For <DiffResult>()
                                   .For <AppUser>()
                                   .For <DiffResultComposite>();

                var destModel = modelDefinitions
                                .WithModuleNameFormatter((moduleName) => "")
                                .WithMemberFormatter((identifier) =>
                                                     char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1)
                                                     )
                                .WithTypeFormatter((type, f) => "I" + ((TsClass)type).Name)
                                .Generate();

                var importLine = $"import {{ {enumImports.Select(i => i.Name).AsString(", ")} }} from  './Enums'";
                var dateLine   = $"// generated at {DateTime.Now.ToUniversalTime()} (UTC)";
                var guidLine   = $"export const __uuid = '{Guid.NewGuid()}'";
                File.WriteAllText(destModelPath, $"{importLine}\n{destModel}\n\n{dateLine}\n{guidLine}");

                var enumDefinition = TypeScript.Definitions();
                enumImports.ForEach(T =>
                {
                    enumDefinition = enumDefinition.For(T);
                });

                var enumBase = enumDefinition
                               .WithModuleNameFormatter((moduleName) => "")
                               .WithMemberFormatter((identifier) =>
                                                    char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1)
                                                    )
                               .WithTypeFormatter((type, f) => "I" + ((TsClass)type).Name)
                               .Generate();

                enumBase += AddEnumLike <ProcessStatus>();

                File.WriteAllText(
                    "_client/src/models/Enums.ts",
                    enumBase.Replace("export const enum", "export enum")
                    );
                Environment.Exit(0);
            }

            CreateWebHostBuilder(args)
            .Build()
            .Run();
        }
Exemple #8
0
        /// <summary>
        /// Valida a CTe de acordo com o Schema.
        /// </summary>
        public void Validar()
        {
            var listaErros = new List <string>();

            if (CTe.Any())
            {
                var pathSchemaCTe = Parent.Configuracoes.Arquivos.GetSchema(SchemaCTe.CTe);
                foreach (var cte in CTe)
                {
                    var xml = cte.GetXml();
                    XmlSchemaValidation.ValidarXml(xml, pathSchemaCTe, out var erros, out _);

                    listaErros.AddRange(erros);

                    if (cte.InfCTe.Ide.TpCTe == CTeTipo.Anulacao ||
                        cte.InfCTe.Ide.TpCTe == CTeTipo.Complemento)
                    {
                        continue;
                    }

                    var xmlModal =
                        ((CTeNormal)cte.InfCTe.InfoCTe).InfModal.Modal.GetXml(DFeSaveOptions.DisableFormatting);
                    SchemaCTe schema;

                    switch (((CTeNormal)cte.InfCTe.InfoCTe).InfModal.Modal)
                    {
                    case CTeAereoModal _:
                        schema = SchemaCTe.CTeModalAereo;
                        break;

                    case CTeAquavModal _:
                        schema = SchemaCTe.CTeModalAquaviario;
                        break;

                    case CTeDutoModal _:
                        schema = SchemaCTe.CTeModalDutoviario;
                        break;

                    case CTeFerrovModal _:
                        schema = SchemaCTe.CTeModalFerroviario;
                        break;

                    case CTeMultimodal _:
                        schema = SchemaCTe.CTeMultiModal;
                        break;

                    case CTeRodoModal _:
                        schema = SchemaCTe.CTeModalRodoviario;
                        break;

                    default:
                        continue;
                    }

                    var pathSchemaModal = Parent.Configuracoes.Arquivos.GetSchema(schema);
                    XmlSchemaValidation.ValidarXml(xmlModal, pathSchemaModal, out var errosModal, out _);
                    listaErros.AddRange(errosModal);
                }
            }

            if (CTeOS.Any())
            {
                var pathSchemaCTeOS = Parent.Configuracoes.Arquivos.GetSchema(SchemaCTe.CTeOS);
                foreach (var cte in CTeOS)
                {
                    var xml = cte.GetXml();
                    XmlSchemaValidation.ValidarXml(xml, pathSchemaCTeOS, out var erros, out _);

                    listaErros.AddRange(erros);

                    if (cte.InfCTe.Ide.TpCTe == CTeTipo.Anulacao ||
                        cte.InfCTe.Ide.TpCTe == CTeTipo.Complemento)
                    {
                        continue;
                    }

                    var xmlModal =
                        ((CTeNormalOS)cte.InfCTe.InfoCTeOS).InfModal.Modal.GetXml(DFeSaveOptions.DisableFormatting);
                    SchemaCTe schema;

                    switch (((CTeNormalOS)cte.InfCTe.InfoCTeOS).InfModal.Modal)
                    {
                    case CTeRodoModalOS _:
                        schema = SchemaCTe.CTeModalRodoviarioOS;
                        break;

                    default:
                        continue;
                    }

                    var pathSchemaModal = Parent.Configuracoes.Arquivos.GetSchema(schema);
                    XmlSchemaValidation.ValidarXml(xmlModal, pathSchemaModal, out var errosModal, out _);
                    listaErros.AddRange(errosModal);
                }
            }

            Guard.Against <ACBrDFeValidationException>(listaErros.Any(), "Erros de validação do xml." +
                                                       $"{(Parent.Configuracoes.Geral.ExibirErroSchema ? Environment.NewLine + listaErros.AsString() : "")}");
        }
        public static string UpdateTriggerSql(Type version)
        {
            // Step 0. Get source type
            Type source = version
                          .GetInterfaces()
                          .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IVersion <>))
                          .SelectMany(i => i.GetGenericArguments())
                          .FirstOrDefault();

            // Step 1. Get properties
            List <PropertyInfo> versionPropertyList = version.GetProperties().ToList();
            List <PropertyInfo> sourcePropertyList  = source.GetProperties().ToList();

            // Step 2. Sort version properties
            versionPropertyList.Sort((x, y) => x.Name.CompareTo(y.Name));

            // Step 3. Get the property list
            List <PropertyInfo> mappedPropertyList = versionPropertyList.FindAll(x => {
                // Step 1. Filter non direct or Original_* matches
                string versionPropertyName = GetUnderlyingColumnName(x);

                if (!sourcePropertyList.Any(y => y.Name == versionPropertyName))
                {
                    return(false);
                }

                // Step 2. Drop Id
                if (versionPropertyName == "Id")
                {
                    return(false);
                }

                return(true);
            });

            // step 4. Get column list
            string versionColumnList = versionPropertyList.AsString(x => string.Format("[{0}]", x.Name), ",\r\n");
            string sourceColumnList  = versionPropertyList.AsString(x => string.Format("{0}", GetSourceColumn(x)), ",\r\n");

            // step 5. Create the sql
            string insertSql = string.Format(@"IF EXISTS(SELECT* FROM sys.objects WHERE [name] = N'InsertVersion{0}Trigger' AND [type] = 'TR')
                                BEGIN
                                DROP TRIGGER [InsertVersion{0}Trigger];
                            END;
                            
                            GO;
                            
                            CREATE TRIGGER [InsertVersion{0}Trigger] ON [{0}]
                            FOR AFTER INSERT
                            AS
                            BEGIN

                                INSERT [{0}Version] ( 
                                [Id],
                                [Version_CurrentId],
                                [Version_Operation],
                                {1})
                                SELECT 
                                i.Version_Id,
                                i.Id,
                                'INSERT',
                                {2} 
                                FROM Inserted i
                                    INNER JOIN Deleted d ON i.Id = d.Id
                                    INNER JOIN [{0}] s ON i.Id = s.Id

                            END;

                            GO", source.Name, versionColumnList, sourceColumnList);

            string updateSql = string.Format(@"IF EXISTS(SELECT* FROM sys.objects WHERE [name] = N'UpdateVersion{0}Trigger' AND [type] = 'TR')
                                BEGIN
                                DROP TRIGGER [UpdateVersion{0}Trigger];
                            END;
                            
                            GO;
                            
                            CREATE TRIGGER [UpdateVersion{0}Trigger] ON [{0}]
                            FOR UPDATE
                            AS
                            BEGIN

                                INSERT [{0}Version] ( 
                                [Id],
                                [Version_CurrentId],
                                [Version_Operation],
                                {1})
                                SELECT 
                                i.Version_Id,
                                i.Id,
                                'UPDATE',
                                {2} 
                                FROM Inserted i
                                    INNER JOIN Deleted d ON i.Id = d.Id
                                    INNER JOIN [{0}] s ON i.Id = s.Id

                            END;

                            GO", source.Name, versionColumnList, sourceColumnList);

            string deleteSql = string.Format(@"IF EXISTS(SELECT* FROM sys.objects WHERE [name] = N'DeleteVersion{0}Trigger' AND [type] = 'TR')
                                BEGIN
                                DROP TRIGGER [DeleteVersion{0}Trigger];
                            END;
                            
                            GO;
                            
                            CREATE TRIGGER [DeleteVersion{0}Trigger] ON [{0}]
                            FOR DELETE
                            AS
                            BEGIN

                                INSERT [{0}Version] ( 
                                [Id],
                                [Version_CurrentId],
                                [Version_Operation],
                                {1})
                                SELECT 
                                i.Version_Id,
                                i.Id,
                                'DELETE',
                                {2} 
                                FROM Deleted d 
                                    INNER JOIN [{0}] s ON i.Id = s.Id

                            END;

                            GO;", source.Name, versionColumnList, sourceColumnList);

            return(string.Format("{0}\r\n {1}\r\n {2}\r\n", insertSql, updateSql, deleteSql));
        }
Exemple #10
0
 public override string ToString()
 {
     return($"ID: {ID}, Status: {Status}, Date: {Date}{_stops.AsString()}");
 }
 public void ExceptionShouldNeverHaveFired()
 {
     Assert.AreEqual(0, _channelExceptionRegister.Count, _channelExceptionRegister.AsString());
 }
Exemple #12
0
        public static BString DecodeString(BencodeStream stream, Encoding encoding)
        {
            if (stream == null) throw new ArgumentNullException("stream");
            if (encoding == null) throw new ArgumentNullException("encoding");

            // Minimum valid bencode string is '0:' meaning an empty string
            if (stream.Length < 2)
                throw new BencodeDecodingException<BString>("Minimum valid stream length is 2 (an empty string: '0:')", stream.Position);

            var lengthChars = new List<char>();

            while (!stream.EndOfStream)
            {
                var c = stream.ReadChar();

                // Break when we reach ':' if it is not the first character found
                if (lengthChars.Count > 0 && c == ':')
                    break;

                // Character then must be a digit
                if (!c.IsDigit())
                {
                    if (lengthChars.Count == 0)
                        throw new BencodeDecodingException<BString>(string.Format("Must begin with an integer but began with '{0}'", c), stream.Position);

                    // We have found some digits but this is neither a digit nor a ':' as expected
                    throw new BencodeDecodingException<BString>("Delimiter ':' was not found.", stream.Position);
                }

                // Because of memory limitations (~1-2 GB) we know for certain we cannot handle more than 10 digits (10GB)
                if (lengthChars.Count >= BString.LengthMaxDigits)
                {
                    throw new UnsupportedBencodeException(
                        string.Format("Length of string is more than {0} digits (>10GB) and is not supported (max is ~1-2GB).", BString.LengthMaxDigits),
                        stream.Position);
                }

                lengthChars.Add(c);
            }

            var stringLength = long.Parse(lengthChars.AsString());

            // Int32.MaxValue is ~2GB and is the absolute maximum that can be handled in memory
            if (stringLength > int.MaxValue)
            {
                throw new UnsupportedBencodeException(
                    string.Format("Length of string is {0:N0} but maximum supported length is {1:N0}.", stringLength, int.MaxValue),
                    stream.Position);
            }

            // TODO: Catch possible OutOfMemoryException when stringLength is close Int32.MaxValue ?
            var bytes = stream.Read((int)stringLength);

            // If the two don't match we've reached the end of the stream before reading the expected number of chars
            if (bytes.Length != stringLength)
            {
                throw new BencodeDecodingException<BString>(
                    string.Format("Expected string to be {0:N0} bytes long but could only read {1:N0} bytes.", stringLength, bytes.Length),
                    stream.Position);
            }

            return new BString(bytes, encoding);
        }
Exemple #13
0
        public static BNumber DecodeNumber(BencodeStream stream)
        {
            if (stream == null) throw new ArgumentNullException("stream");

            if (stream.Length < 3)
                throw new BencodeDecodingException<BNumber>("Minimum valid length of stream is 3 ('i0e').", stream.Position);

            // Numbers must start with 'i'
            if (stream.ReadChar() != 'i')
                throw new BencodeDecodingException<BNumber>(string.Format("Must begin with 'i' but began with '{0}'.", stream.ReadPreviousChar()), stream.Position);

            var isNegative = false;
            var digits = new List<char>();
            while (stream.Peek() != 'e' && stream.Peek() != -1)
            {
                // We do not support numbers that cannot be stored as a long (Int64)
                if (digits.Count >= BNumber.MaxDigits)
                {
                    throw new UnsupportedBencodeException(
                        string.Format(
                            "The number '{0}' has more than 19 digits and cannot be stored as a long (Int64) and therefore is not supported.",
                            digits.AsString()),
                        stream.Position);
                }

                var c = stream.ReadChar();

                // There may be only one '-'
                if (c == '-' && !isNegative)
                {
                    // '-' must be the first char after the beginning 'i'
                    if (digits.Count > 0)
                        throw new BencodeDecodingException<BNumber>("A '-' must be directly after 'i' and before any digits.", stream.Position);

                    isNegative = true;
                    continue;
                }

                // If it is not a digit at this point it is invalid
                if (!c.IsDigit())
                    throw new BencodeDecodingException<BNumber>(string.Format("Must only contain digits and a single prefixed '-'. Invalid character '{0}'", c), stream.Position);

                digits.Add(c);
            }

            // We need at least one digit
            if (digits.Count < 1)
                throw new BencodeDecodingException<BNumber>("It contains no digits.", stream.Position);

            // Leading zeros are not valid
            if (digits[0] == '0' && digits.Count > 1)
                throw new BencodeDecodingException<BNumber>("Leading '0's are not valid.", stream.Position);

            // '-0' is not valid either
            if (digits[0] == '0' && digits.Count == 1 && isNegative)
                throw new BencodeDecodingException<BNumber>("'-0' is not a valid number.", stream.Position);

            if (stream.ReadChar() != 'e')
                throw new BencodeDecodingException<BNumber>("Missing end character 'e'.", stream.Position);

            if (isNegative)
                digits.Insert(0, '-');

            long number;
            if (!long.TryParse(digits.AsString(), out number))
            {
                // This should only happen if the number is bigger than 9,223,372,036,854,775,807 (or smaller than the negative version)
                throw new UnsupportedBencodeException(
                    string.Format(
                        "The value {0} cannot be stored as a long (Int64) and is therefore not supported. The supported values range from {1:N0} to {2:N0}",
                        digits.AsString(), long.MinValue, long.MaxValue),
                    stream.Position);
            }

            return new BNumber(number);
        }
Exemple #14
0
 public void Day06_TestRun03()
 {
     Assert.AreEqual("0 2 7 0", testDataA.AsString());
     Assert.AreEqual(sut.input06A, sut.InputA.AsString());
 }