Exemple #1
0
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string typeStr = reader.ReadToEnd(",;");

            if (reader.Current == ',') // to get rid of the TE header.
            {
                reader.ReadToEnd(';');
            }

            ConnectionType type;

            try
            {
                type = (ConnectionType)Enum.Parse(typeof(ConnectionType), typeStr.Replace("-", string.Empty), true);
            }
            catch (ArgumentException err)
            {
                throw new FormatException("Unknown connection type '" + typeStr + "'.", err);
            }

            // got parameters
            if (reader.Current == ';')
            {
                HeaderParameterCollection parameters = HeaderParameterCollection.Parse(reader);
                return(new ConnectionHeader(type, parameters));
            }

            return(new ConnectionHeader(type));
        }
        public void MakeCreator()
        {
            reader = A.Fake <ITextReader>();
            var words = new List <string> {
                "Привет", "Земля", "и", "Земля"
            };

            A.CallTo(() => reader.ReadWords(null))
            .WithAnyArguments()
            .Returns(words);

            wordProcessor = A.Fake <IWordProcessor>();
            var wordsWithCounts = new List <WordWithCount>
            {
                new WordWithCount("земля", 2),
                new WordWithCount("привет", 1)
            };

            A.CallTo(() => wordProcessor.ProcessWords(words))
            .WithAnyArguments()
            .Returns(wordsWithCounts);

            var builder = new ContainerBuilder();

            builder.RegisterInstance(reader).As <ITextReader>();
            builder.RegisterInstance(wordProcessor).As <IWordProcessor>();
            var container = GetContainer(builder);

            imageCreator = container.Resolve <IImageCreator>();
        }
Exemple #3
0
        public void startCompression(string path)
        {
            ITextReader  reader    = Core.class_fabric.getTextReaderComponent();
            Queue <word> proc_data = reader.startDataProcessing(path);

            Action(Core.class_fabric.getBWTCompression(), proc_data);
        }
        /// <summary>
        /// Parse parameters.
        /// </summary>
        /// <param name="reader">Parser containing buffer to parse.</param>
        /// <param name="delimiter">Parameter delimiter</param>
        /// <returns>A collection with all parameters (or just a empty collection).</returns>
        /// <exception cref="FormatException">Expected a value after equal sign.</exception>
        public static HeaderParameterCollection Parse(ITextReader reader, char delimiter)
        {
            if (reader.Current == delimiter)
                reader.Consume();
            reader.ConsumeWhiteSpaces();

            var collection = new HeaderParameterCollection();
            string name = reader.ReadToEnd("=" + delimiter);
            while (name != string.Empty && !reader.EOF)
            {
                // got a parameter value
                if (reader.Current == '=')
                {
                    reader.ConsumeWhiteSpaces('=');

                    string value = reader.Current == '"'
                                       ? reader.ReadQuotedString()
                                       : reader.ReadToEnd(delimiter);

                    reader.ConsumeWhiteSpaces();
                    if (value == string.Empty && reader.Current != delimiter)
                        throw new FormatException("Expected a value after equal sign.");

                    collection.Add(name, value);
                }
                else // got no value
                {
                    collection.Add(name, string.Empty);
                }

                reader.ConsumeWhiteSpaces(delimiter); // consume delimiter and white spaces
                name = reader.ReadToEnd("=" + delimiter);
            }
            return collection;
        }
Exemple #5
0
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            //key: "value"; key: "value"

            var cookies = new RequestCookieCollection();

            while (!reader.EOF)
            {
                // read name
                string cookieName = reader.ReadToEnd("=;");

                // cookie with value?
                if (reader.Current == '=')
                {
                    reader.Consume();
                    reader.ConsumeWhiteSpaces();

                    // is value quoted or not?
                    string value = reader.Current == '"' ? reader.ReadQuotedString() : reader.ReadToEnd(";");
                    cookies.Add(new RequestCookie(cookieName, value));
                }
                //else
                //    cookies.Add(new RequestCookie(cookieName, string.Empty));

                // consume whitespaces and cookie separator
                reader.ConsumeWhiteSpaces(';');
            }

            return(new CookieHeader(cookies));
        }
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string typeStr = reader.ReadToEnd(",;");
            if (reader.Current == ',') // to get rid of the TE header.
                reader.ReadToEnd(';');

            ConnectionType type;

            try
            {
                type = (ConnectionType) Enum.Parse(typeof (ConnectionType), typeStr.Replace("-", string.Empty), true);
            }
            catch (ArgumentException err)
            {
                throw new FormatException("Unknown connection type '" + typeStr + "'.", err);
            }

            // got parameters
            if (reader.Current == ';')
            {
                HeaderParameterCollection parameters = HeaderParameterCollection.Parse(reader);
                return new ConnectionHeader(type, parameters);
            }

            return new ConnectionHeader(type);
        }
Exemple #7
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        /// <example>
        /// Contact: "Mr. Watson" <sip:[email protected]>
        ///  ;q=0.7; expires=3600,
        ///  "Mr. Watson" <mailto:[email protected]>;q=0.1
        /// </example>
        public IHeader Parse(string name, ITextReader reader)
        {
            var contacts = new List <Contact>();

            try
            {
                Contact item = UriParser.ParseContact(reader);
                contacts.Add(item);
                while (reader.Current == ',')
                {
                    reader.ConsumeWhiteSpaces(',');
                    if (!reader.EOF)
                    {
                        item = UriParser.ParseContact(reader);
                    }
                    contacts.Add(item);
                }
            }
            catch (FormatException err)
            {
                throw new ParseException("Failed to parse header '" + name + "'.", err);
            }

            return(new ContactHeader(name)
            {
                Contacts = contacts
            });
        }
Exemple #8
0
 public static void ConsumesAll(ITextReader r)
 {
     while (!r.EndOfFile)
     {
         r.Read();
     }
 }
Exemple #9
0
 public TagCloud(ITagDrawer drawer, ITextReader textReader, IWordsAnalyzer wordsAnalyzer, IImageSaver imageSaver)
 {
     this.drawer        = drawer;
     this.textReader    = textReader;
     this.wordsAnalyzer = wordsAnalyzer;
     this.imageSaver    = imageSaver;
 }
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        /// <example>
        /// Digest realm="atlanta.com",
        /// domain="sip:boxesbybob.com", qop="auth",
        /// nonce="f84f1cec41e6cbe5aea9c8e88d359",
        /// opaque="", stale=FALSE, algorithm=MD5
        /// </example>
        public IHeader Parse(string name, ITextReader reader)
        {
            reader.ConsumeWhiteSpaces();
            string digest = reader.ReadWord().ToLower();
            if (digest != "digest")
                throw new ParseException("Authorization header is not digest authentication");

            reader.ConsumeWhiteSpaces();
            var parameters = new KeyValueCollection();
            UriParser.ParseParameters(parameters, reader, ',');

            var header = new Authenticate(name)
                             {
                                 Algortihm = parameters["algorithm"],
                                 Domain = UriParser.Parse(parameters["domain"]),
                                 Realm = parameters["realm"],
                                 Nonce = parameters["nonce"],
                                 Qop = parameters["qop"],
                                 Opaque = parameters["opaque"]
                             };

            try
            {
                header.Stale = bool.Parse(parameters["stale"]);
            }
            catch (Exception err)
            {
                throw new ParseException("Failed to parse 'stale' in WWW-Authenticate header.", err);
            }

            return header;
        }
Exemple #11
0
        /// <summary>
        /// Parse a query string
        /// </summary>
        /// <param name="reader">string to parse</param>
        /// <returns>A collection</returns>
        /// <exception cref="ArgumentNullException"><c>reader</c> is <c>null</c>.</exception>
        public static ParameterCollection Parse(ITextReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            var parameters = new ParameterCollection();
            while (!reader.EOF)
            {
                string name = HttpUtility.UrlDecode(reader.ReadToEnd("&="));
                char current = reader.Current;
                reader.Consume();
                switch (current)
                {
                    case '&':
                        parameters.Add(name, string.Empty);
                        break;
                    case '=':
                        {
                            string value = reader.ReadToEnd("&");
                            reader.Consume();
                            parameters.Add(name, HttpUtility.UrlDecode(value));
                        }
                        break;
                    default:
                        parameters.Add(name, string.Empty);
                        break;
                }
            }

            return parameters;
        }
Exemple #12
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            ViaEntry entry = ParseEntry(reader);

            if (reader.Current != ',')
            {
                return new Via {
                           entry
                }
            }
            ;

            var via = new Via {
                entry
            };

            while (reader.Current == ',')
            {
                reader.ConsumeWhiteSpaces(',');

                entry = ParseEntry(reader);
                via.Add(entry);
            }
            return(via);
        }

        #endregion
    }
Exemple #13
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            var route = new Route(name);

            try
            {
                SipUri uri = UriParser.Parse(reader);
                route.Items.Add(new RouteEntry(name)
                {
                    Uri = uri
                });
                while (reader.Current == ',')
                {
                    reader.ConsumeWhiteSpaces(',');
                    if (!reader.EOF)
                    {
                        uri = UriParser.Parse(reader);
                    }
                    route.Items.Add(new RouteEntry(name)
                    {
                        Uri = uri
                    });
                }
            }
            catch (FormatException err)
            {
                throw new ParseException("Failed to parse header '" + name + "'.", err);
            }

            return(route);
        }
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string value = reader.ReadToEnd(",;");
            if (reader.Current == ',') // to get rid of the TE header.
                reader.ReadToEnd(';');

            ConnectionType type;
            if (string.Compare(value, "close", true) == 0)
                type = ConnectionType.Close;
            else if (value.StartsWith("keep-alive", StringComparison.CurrentCultureIgnoreCase))
                type = ConnectionType.KeepAlive;
            else if (value.StartsWith("te", StringComparison.CurrentCultureIgnoreCase))
                type = ConnectionType.TransferEncoding;
            else
                throw new FormatException("Unknown connection type '" + value + "'.");

            // got parameters
            if (reader.Current == ';')
            {
                HeaderParameterCollection parameters = HeaderParameterCollection.Parse(reader);
                return new ConnectionHeader(type, parameters);
            }

            return new ConnectionHeader(type);
        }
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        /// <example>
        /// Authorization: Digest username="******",
        ///                 realm="biloxi.com",
        ///                 nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
        ///                 uri="sip:[email protected]",
        ///                 qop=auth,
        ///                 nc=00000001,
        ///                 cnonce="0a4f113b",
        ///                 response="6629fae49393a05397450978507c4ef1",
        ///                 opaque="5ccc069c403ebaf9f0171e9517f40e41"
        /// </example>
        public IHeader Parse(string name, ITextReader reader)
        {
            reader.ConsumeWhiteSpaces();
            string digest = reader.ReadWord().ToLower();
            if (digest != "digest")
                throw new ParseException("Authorization header is not digest authentication");

            reader.ConsumeWhiteSpaces();
            var parameters = new KeyValueCollection();
            UriParser.ParseParameters(parameters, reader, ',');

            var header = new Authorization(name)
                             {
                                 UserName = parameters["username"],
                                 Realm = parameters["realm"],
                                 Nonce = parameters["nonce"],
                                 Qop = parameters["qop"],
                                 ClientNonce = parameters["cnonce"],
                                 Opaque = parameters["opaque"],
                                 Response = parameters["response"],
                                 Uri = UriParser.Parse(parameters["uri"])
                             };

            try
            {
                header.NonceCounter = int.Parse(parameters["nc"]);
            }
            catch (Exception err)
            {
                throw new ParseException("Failed to parse 'nc' in Authorization header.", err);
            }

            return header;
        }
Exemple #16
0
    /// <summary>
    /// Parse a header
    /// </summary>
    /// <param name="name">Name of header.</param>
    /// <param name="reader">Reader containing value.</param>
    /// <returns>HTTP Header</returns>
    /// <exception cref="FormatException">Header value is not of the expected format.</exception>
    public IHeader Parse(string name, ITextReader reader)
    {
      //key: "value"; key: "value"

      var cookies = new RequestCookieCollection();
      while (!reader.EOF)
      {
        // read name
        string cookieName = reader.ReadToEnd("=;");

        // cookie with value?
        if (reader.Current == '=')
        {
          reader.Consume();
          reader.ConsumeWhiteSpaces();

          // is value quoted or not?
          string value = reader.Current == '"' ? reader.ReadQuotedString() : reader.ReadToEnd(";");
          cookies.Add(new RequestCookie(cookieName, value));
        }

        // consume whitespaces and cookie separator
        reader.ConsumeWhiteSpaces(';');
      }

      return new CookieHeader(cookies);
    }
Exemple #17
0
 /// <summary>
 /// Parse a message value.
 /// </summary>
 /// <param name="name">Header name</param>
 /// <param name="reader">Reader containing the string that should be parsed.</param>
 /// <returns>Newly created header.</returns>
 /// <exception cref="ParseException">Header value is malformed.</exception>
 public IHeader Parse(string name, ITextReader reader)
 {
     return(new StringHeader(name)
     {
         Value = reader.ReadToEnd()
     });
 }
 /// <summary>
 /// Parse a message value.
 /// </summary>
 /// <param name="name">Name of header being parsed.</param>
 /// <param name="reader">Reader containing the string that should be parsed.</param>
 /// <returns>Newly created header.</returns>
 /// <exception cref="ParseException">Header value is malformed.</exception>
 public IHeader Parse(string name, ITextReader reader)
 {
     string temp = reader.ReadToEnd();
     int value;
     if (!int.TryParse(temp, out value))
         throw new ParseException("Failed to convert '" + temp + "' to int.");
     return new NumericHeader(name) {Value = value};
 }
Exemple #19
0
 public CSVReader(ITextReader reader)
 {
     if (reader == null)
     {
         throw new ArgumentNullException(nameof(reader), "Please provide a valid text reader.");
     }
     _reader = reader;
 }
Exemple #20
0
 /// <summary>
 /// Parse a header
 /// </summary>
 /// <param name="name">Name of header.</param>
 /// <param name="reader">Reader containing value.</param>
 /// <returns>HTTP Header</returns>
 /// <exception cref="FormatException">Header value is not of the expected format.</exception>
 public IHeader Parse(string name, ITextReader reader)
 {
   string temp = reader.ReadToEnd();
   int value;
   if (!int.TryParse(temp, out value))
     throw new FormatException("Header '" + name + "' do not contain a numerical value ('" + temp + "').");
   return new NumericHeader(name, value);
 }
Exemple #21
0
 public static Generic.IEnumerable <Tasks.Task <string> > ReadAllLines(this ITextReader me)
 {
     Tasks.Task <string> result;
     while ((result = me.ReadLine()).NotNull())
     {
         yield return(result);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonReader"/> class.
        /// </summary>
        /// <param name="textReader">The <see cref="ITextReader"/> to take ownership of.</param>
        public JsonReader( ITextReader textReader )
        {
            Ensure.That(textReader).NotNull();

            this.sb = new StringBuilder();
            this.parents = new Stack<JsonToken>();
            this.reader = textReader;
        }
Exemple #23
0
 public TagCloudHelper(ITextReader textReader, TagCloudTextAnalyzer textAnalyzer, TagCloudDrawer drawer,
                       IImageSaver imageSaver)
 {
     this.textReader   = textReader;
     this.textAnalyzer = textAnalyzer;
     this.drawer       = drawer;
     this.imageSaver   = imageSaver;
     Settings          = new TagCloudSettings();
 }
Exemple #24
0
 public IHeader Parse(string name, ITextReader reader)
 {
   var header = new AuthorizationHeader();
   reader.ConsumeWhiteSpaces();
   header.Scheme = reader.ReadWord();
   reader.ConsumeWhiteSpaces();
   header.Data = reader.ReadToEnd();
   return header;
 }
Exemple #25
0
        /// <summary>
        /// Compares the generated hash value from the text with the hash value from the file.
        /// </summary>
        /// <param name="text">The text for generating the hash.</param>
        /// <param name="reader">The textreader for the hash value.</param>
        /// <returns>
        /// true if the hash from the file is equal to the computed hash.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        public bool CompareWithHash(string text, ITextReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            return(this.CompareWithHash(text, reader.GetString()));
        }
 /// <summary>
 /// Create a <see cref="NumericHeader"/> header.
 /// </summary>
 /// <param name="name">Name of header.</param>
 /// <param name="reader">Reader containing value.</param>
 /// <returns>HTTP Header</returns>
 /// <exception cref="FormatException">Header value is not of the expected format.</exception>
 public IHeader Create(string name, ITextReader reader)
 {
     if (reader == null) return null;
     string temp = reader.ReadToEnd();
     int value;
     if (!int.TryParse(temp, out value))
         throw new FormatException(string.Format("Header '{0}' do not contain a numerical value ('{1}').", name, temp, CultureInfo.CurrentCulture));
     return new NumericHeader(name, value);
 }
 public IHeader Parse(string name, ITextReader reader)
 {
     var header = new AuthorizationHeader();
     reader.ConsumeWhiteSpaces();
     header.Scheme = reader.ReadWord();
     reader.ConsumeWhiteSpaces();
     header.Data = reader.ReadToEnd();
     return header;
 }
Exemple #28
0
 public RsaKeyFromXmlFileLoader(IMyFile myFile, ITextReader xmlReader, IXmlSerializationUtils <EnvCryptKey> xmlSerializationUtils, IExternalRepresentationToKeyMapper <EnvCryptKey, RsaKey> mapper) : base(myFile, xmlReader, xmlSerializationUtils)
 {
     Contract.Requires <ArgumentNullException>(myFile != null, "myFile");
     Contract.Requires <ArgumentNullException>(xmlReader != null, "xmlReader");
     Contract.Requires <ArgumentNullException>(xmlSerializationUtils != null, "xmlSerializationUtils");
     Contract.Requires <ArgumentNullException>(mapper != null, "mapper");
     //
     _mapper = mapper;
 }
Exemple #29
0
        public static string ReadsAll(ITextReader r)
        {
            var buff = new StringBuilder();

            while (!r.EndOfFile)
            {
                buff.Append((char)r.Read());
            }
            return(buff.ToString());
        }
Exemple #30
0
 protected KeyFromXmlFileLoader(IMyFile myFile, ITextReader xmlReader, IXmlSerializationUtils <EnvCryptKey> xmlSerializationUtils)
 {
     Contract.Requires <ArgumentNullException>(myFile != null, "myFile");
     Contract.Requires <ArgumentNullException>(xmlReader != null, "xmlReader");
     Contract.Requires <ArgumentNullException>(xmlSerializationUtils != null, "xmlSerializationUtils");
     //
     _myFile                = myFile;
     _xmlReader             = xmlReader;
     _xmlSerializationUtils = xmlSerializationUtils;
 }
Exemple #31
0
        public PlyAsciiReader(ITextReader sourceReader, PlyHeader header)
            : base(header)
        {
            if (header.Format != PlyFormat.Ascii)
            {
                throw new NotSupportedException($"The {nameof(PlyAsciiReader)} does not support binary data.");
            }

            _textReader = sourceReader;
        }
 public void SetUp()
 {
     textReader            = A.Fake <ITextReader>();
     wordsFilter           = A.Fake <IWordsFilter>();
     wordsCounter          = A.Fake <IWordsCounter>();
     wordsToSizesConverter = A.Fake <IWordsToSizesConverter>();
     ccl        = A.Fake <ICloudLayouter>();
     visualiser = A.Fake <IVisualiser>();
     imageSaver = A.Fake <IFileSaver>();
 }
Exemple #33
0
 public ExampleAction(
     ITagCloudBuilder tagCloudBuilder, ICloudVisualizer cloudVisualizer,
     ITextReader textReader, ITextHandler textHandler, SpiralParams spiralParams)
 {
     this.tagCloudBuilder = tagCloudBuilder;
     this.cloudVisualizer = cloudVisualizer;
     this.textReader      = textReader;
     this.textHandler     = textHandler;
     this.spiralParams    = spiralParams;
 }
Exemple #34
0
 public TagCloudRunner(ICloudVisualizer visualizer, ITagReader tagReader, IWordFilter wordFilter, ITextReader wordReader, string pathToWords, string pathToPicture, ImageFormat format)
 {
     this.visualizer    = visualizer;
     this.tagReader     = tagReader;
     this.wordFilter    = wordFilter;
     this.wordReader    = wordReader;
     this.pathToWords   = pathToWords;
     this.pathToPicture = pathToPicture;
     this.format        = format;
 }
Exemple #35
0
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string temp = reader.ReadToEnd();
            int    value;

            if (!int.TryParse(temp, out value))
            {
                throw new FormatException("Header '" + name + "' do not contain a numerical value ('" + temp + "').");
            }
            return(new NumericHeader(name, value));
        }
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string type = reader.ReadUntil("/");
            reader.Consume('/');
            string subType = reader.ReadToEnd(';');
            reader.Consume(';', ' ', '\t');

            var contentType = new ContentType {SubType = subType, Type = type};
            UriParser.ParseParameters(contentType.Parameters, reader);
            return contentType;
        }
Exemple #37
0
        /// <summary>
        /// Writes the hash value file (filename.extension) from the content of a File.
        /// </summary>
        /// <param name="reader">The reader for the input data.</param>
        /// <param name="writer">The textwriter for the output.</param>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="writer"/>is null</exception>
        public void WriteHash(ITextReader reader, ITextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            string hash = this.GetHashFromReader(reader);

            writer.Write(hash);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CsvReader"/> class.
        /// </summary>
        /// <param name="textReader">The <see cref="ITextReader"/> to take ownership of.</param>
        /// <param name="format">The <see cref="CsvFormat"/> to use.</param>
        public CsvReader( ITextReader textReader, CsvFormat format )
        {
            Ensure.That(textReader).NotNull();
            Ensure.That(format).NotNull();

            this.csvFormat = format;
            this.sb = new StringBuilder();
            this.record = new List<Substring>();
            this.readOnlyRecord = new ReadOnlyList.Wrapper<Substring>(this.record);
            this.tr = textReader;
        }
Exemple #39
0
        public static async Tasks.Task <string> ReadUpTo(this ITextReader me, Func <char, bool> predicate)
        {
            Text.Builder result = await me.Empty ? null : "";
            char?        next;

            while ((next = await me.Read(predicate.Negate())).HasValue)
            {
                result += next.Value;
            }
            return(result);
        }
Exemple #40
0
        /// <summary>
        /// Compares the computed hash value with the hash value from the input data.
        /// </summary>
        /// <param name="reader">The textreader for computing the hash.</param>
        /// <param name="hashReader">The textreader for the hash value.</param>
        /// <returns>
        /// true if the hash from the textreader is equal to the computed hash.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="hashReader"/>is null</exception>
        public bool CompareWithHash(ITextReader reader, ITextReader hashReader)
        {
            if (hashReader == null)
            {
                throw new ArgumentNullException("hashReader");
            }

            string hash = this.GetHashFromReader(reader);

            return(hash.Equals(hashReader.GetString(), StringComparison.InvariantCultureIgnoreCase));
        }
Exemple #41
0
        public static ViaEntry ParseEntry(ITextReader reader)
        {
            //SIP/2.0/UDP erlang.bell-telephone.com:5060;branch=z9hG4bK87asdks7
            var entry = new ViaEntry();

            // read SIP/
            reader.ConsumeWhiteSpaces();
            entry.Protocol = reader.ReadUntil("/ \t");
            if (entry.Protocol == null)
                throw new FormatException("Expected Via header to start with 'SIP' or 'SIPS'.");
            reader.ConsumeWhiteSpaces('/');

            // read 2.0/
            entry.SipVersion = reader.ReadUntil("/ \t");
            if (entry.SipVersion == null)
                throw new FormatException("Expected to find sip version in Via header.");
            reader.ConsumeWhiteSpaces('/');

            // read UDP or TCP
            entry.Transport = reader.ReadWord();
            if (entry.Transport == null)
                throw new FormatException("Expected to find transport protocol after sip version in Via header.");
            reader.ConsumeWhiteSpaces();

            entry.Domain = reader.ReadUntil(";: \t");
            if (entry.Domain == null)
                throw new FormatException("Failed to find domain in via header.");
            reader.ConsumeWhiteSpaces();

            if (reader.Current == ':')
            {
                reader.Read();
                reader.ConsumeWhiteSpaces();
                string temp = reader.ReadToEnd("; \t");
                reader.ConsumeWhiteSpaces();
                int port;
                if (!int.TryParse(temp, out port))
                    throw new FormatException("Invalid port specified.");
                entry.Port = port;
            }

            UriParser.ParseParameters(entry.Parameters, reader);
            string rport = entry.Parameters["rport"];
            if (!string.IsNullOrEmpty(rport)) //parameter can exist, but be empty. = rport requested.
            {
                int value;
                if (!int.TryParse(rport, out value))
                    throw new FormatException("RPORT is not a number.");
                entry.Rport = value;
            }

            return entry;
        }
Exemple #42
0
 public CloudCombiner(ICloudConfiguration configuration,
                      ICircularCloudLayouter cloudLayouter,
                      ITextReader textReader,
                      IEnumerable <ITagManipulator> tagFilters,
                      ITagStatisticsGenerator statisticsGenerator)
 {
     Configuration       = configuration;
     CloudLayouter       = cloudLayouter;
     TextReader          = textReader;
     TagFilters          = tagFilters;
     StatisticsGenerator = statisticsGenerator;
 }
Exemple #43
0
        /// <summary>
        /// Computes the hash value from the content of a file.
        /// </summary>
        /// <param name="reader">The reader for the input data.</param>
        /// <returns>Hash as a hex-string.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        public string GetHashFromReader(ITextReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            using (Stream stream = reader.GetStream())
            {
                return this.algorithm.ComputeHashFromStream(stream);
            }
        }
        public DirectoryDataProvider(string databasePathAscii, int databaseVersion, ITextReader fileReaderParam)
        {
            DatabasePathASCII = databasePathAscii;
            _fileReader       = fileReaderParam;

            if (databaseVersion != 26)
            {
                throw new ArgumentException("Only version 26 of the database is supported by this class");
            }

            // Read and parse CSV data from the files
        }
Exemple #45
0
        /// <summary>
        /// Computes the hash value from the content of a file.
        /// </summary>
        /// <param name="reader">The reader for the input data.</param>
        /// <returns>Hash as a hex-string.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        public string GetHashFromReader(ITextReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            using (Stream stream = reader.GetStream())
            {
                return(this.algorithm.ComputeHashFromStream(stream));
            }
        }
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string value = reader.ReadToEnd();

            try
            {
                return new DateHeader(name, DateTime.Parse(value));
            }
            catch (FormatException err)
            {
                throw new FormatException("Failed to parse 'Date' header.", err);
            }
        }
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string contentType = reader.ReadToEnd(';');

            // got parameters
            if (reader.Current == ';')
            {
                HeaderParameterCollection parameters = HeaderParameterCollection.Parse(reader);
                return new ContentTypeHeader(contentType, parameters);
            }

            return new ContentTypeHeader(contentType);
        }
Exemple #48
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            reader.ConsumeWhiteSpaces();
            string number = reader.ReadWord();
            reader.ConsumeWhiteSpaces();
            string method = reader.ReadWord();

            int sequence;
            if (!int.TryParse(number, out sequence))
                throw new ParseException("Sequence number in CSeq must only contain digits, invalid value: " + number);

            return new CSeq(sequence, method);
        }
Exemple #49
0
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string value = reader.ReadToEnd();

            try
            {
                return(new DateHeader(name, DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)));
            }
            catch (FormatException err)
            {
                throw new BadRequestException("'" + name + "' do not contain a valid date", err);
            }
        }
Exemple #50
0
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="FormatException">Header value is not of the expected format.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            string value = reader.ReadToEnd();

            try
            {
                return new DateHeader(name, DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal));
            }
            catch (FormatException err)
            {
                throw new BadRequestException("'" + name + "' do not contain a valid date", err);
            }
        }
        public void SetUp()
        {
            this.mockery = new Mockery();

            this.algorithm = this.mockery.NewMock<IHashAlgorithm>();

            this.reader = this.mockery.NewMock<ITextReader>();

            this.writer = this.mockery.NewMock<ITextWriter>();

            this.hashReader = this.mockery.NewMock<ITextReader>();

            this.testee = new HashService(this.algorithm);
        }
Exemple #52
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            ViaEntry entry = ParseEntry(reader);
            if (reader.Current != ',')
                return new Via {entry};

            var via = new Via {entry};
            while (reader.Current == ',')
            {
                reader.ConsumeWhiteSpaces(',');
                entry = ParseEntry(reader);
                via.Add(entry);
            }
            return via;
        }
        /// <summary>
        /// Called when the object is being disposed of. Inheritors must call base.OnDispose to be properly disposed.
        /// </summary>
        /// <param name="disposing">If set to <c>true</c>, release both managed and unmanaged resources; otherwise release only the unmanaged resources.</param>
        protected override void OnDispose( bool disposing )
        {
            if( disposing )
            {
                //// dispose-only (i.e. non-finalizable) logic
                //// (managed, disposable resources you own)

                if( this.tr != null )
                {
                    this.tr.Close();
                    this.tr = null;
                }
            }

            //// shared cleanup logic
            //// (unmanaged resources)


            base.OnDispose(disposing);
        }
Exemple #54
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            var header = new MethodsHeader(name);

            string method = reader.ReadToEnd(',');
            do
            {
                header.Methods.Add(method.Trim());

                if (reader.Current == ',')
                    reader.Consume(); // eat the current comma
                reader.ConsumeWhiteSpaces();

                // read next.
                method = reader.ReadToEnd(',');

            } while (!reader.EOF && reader.Current == ',');

            header.Methods.Add(method);
            return header;
        }
        /// <summary>
        /// Parse a header
        /// </summary>
        /// <param name="name">Name of header.</param>
        /// <param name="reader">Reader containing value.</param>
        /// <returns>HTTP Header</returns>
        /// <exception cref="System.FormatException">Header value is not of the expected format.</exception>
        public IHeader Create(string name, ITextReader reader)
        {
            if (reader == null) return null;
            var cookies = new RequestCookieCollection();
            while (!reader.Eof)
            {
                string cookieName = reader.ReadToEnd("=;");

                if (reader.Current == '=')
                {
                    reader.Consume();
                    reader.ConsumeWhiteSpaces();

                    string value = reader.Current == '"' ? reader.ReadQuotedString() : reader.ReadToEnd(";");
                    cookies.Add(cookieName, new RequestCookie(cookieName, value));
                }

                reader.ConsumeWhiteSpaces(';');
            }

            return new CookieHeader(cookies);
        }
Exemple #56
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="name">Name of header being parsed.</param>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        public IHeader Parse(string name, ITextReader reader)
        {
            var route = new Route(name);
            try
            {
                SipUri uri = UriParser.Parse(reader);
                route.Items.Add(new RouteEntry(name) {Uri = uri});
                while (reader.Current == ',')
                {
                    reader.ConsumeWhiteSpaces(',');
                    if (!reader.EOF)
                        uri = UriParser.Parse(reader);
                    route.Items.Add(new RouteEntry(name) {Uri = uri});
                }
            }
            catch (FormatException err)
            {
                throw new ParseException("Failed to parse header '" + name + "'.", err);
            }

            return route;
        }
Exemple #57
0
        /// <summary>
        /// Parse a message value.
        /// </summary>
        /// <param name="reader">Reader containing the string that should be parsed.</param>
        /// <returns>Newly created header.</returns>
        /// <exception cref="ParseException">Header value is malformed.</exception>
        /// <example>
        /// Contact: "Mr. Watson" <sip:[email protected]> 
        ///  ;q=0.7; expires=3600, 
        ///  "Mr. Watson" <mailto:[email protected]>;q=0.1 
        /// </example>
        public IHeader Parse(string name, ITextReader reader)
        {
            var contacts = new List<Contact>();
            try
            {
                Contact item = UriParser.ParseContact(reader);
                contacts.Add(item);
                while (reader.Current == ',')
                {
                    reader.ConsumeWhiteSpaces(',');
                    if (!reader.EOF)
                        item = UriParser.ParseContact(reader);
                    contacts.Add(item);
                }
            }
            catch (FormatException err)
            {
                throw new ParseException("Failed to parse header '" + name + "'.", err);
            }

            return new ContactHeader(name) {Contacts = contacts};
        }
 /// <summary>
 /// Wraps the specified <see cref="ITextReader"/>, in <see cref="TextReader"/>.
 /// </summary>
 /// <param name="textReader">The <see cref="ITextReader"/> to wrap.</param>
 /// <returns>The disposable wrapper created.</returns>
 public static TextReader Wrap( ITextReader textReader )
 {
     return new ITexReaderAsTextReader(textReader);
 }
            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if( this.textReader.NotNullReference() )
                    {
                        this.textReader.Close();
                        this.textReader = null;
                    }
                }

                base.Dispose(disposing);
            }
            internal ITexReaderAsTextReader( ITextReader textReader )
            {
                if( textReader.NullReference() )
                    throw new ArgumentNullException().StoreFileLine();

                this.textReader = textReader;
            }