Exemple #1
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="stream">Stream containing the content</param>
    /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
    /// <param name="encoding">Stream encoding</param>
    /// Note: contentType and encoding are not used?
    /// <returns>A http form, or null if content could not be parsed.</returns>
    /// <exception cref="InvalidDataException"></exception>
    public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
    {
      if (stream == null || stream.Length == 0)
        return null;
      if (!CanParse(contentType))
        return null;
      if (encoding == null)
        encoding = Encoding.UTF8;

      HttpForm form = new HttpForm();

      using (TextReader reader = new StreamReader(stream, encoding))
      {
        // let's start with saving the raw xml
        form.Add("__xml__", reader.ReadToEnd());

        try
        {
          // Now let's process the data.
          XmlDocument doc = new XmlDocument();
          doc.LoadXml(form["__xml__"].Value);
          XmlNode child = doc.FirstChild;
          // Skip to next node if the node is an XML Declaration 
          if (child.NodeType == XmlNodeType.XmlDeclaration)
            child = child.NextSibling;
          TraverseNode(form, child);
        }
        catch (XmlException err)
        {
          throw new InvalidDataException("Failed to traverse XML", err);
        }
      }

      return form;
    }
        private void TestPost()
        {
            MyController  controller = new MyController();
            IHttpResponse response;
            IHttpSession  session = DefaultSession;
            HttpForm      form    = new HttpForm();

            form.Add("user[firstName]", "jonas");
            string text = Post(controller, "/my/hello/id", form, out response, session);

            Assert.Equal("jonas", text);
        }
        public static Task <IllustsPage> GetIllustRankingAsync(this PixivClient client, RankMode mode = RankMode.Day, DateTime?date = default, int offset = 0)
        {
            var data = new HttpForm {
                { "offset", offset.ToString() }, { "mode", mode.GetSymbol() }
            };

            if (date != null)
            {
                data.Add("date", date.Value.ToString("yyyy-MM-dd"));
            }

            return(client.GetAsync <IllustsPage>("/v1/illust/ranking", data));
        }
        public static Task <IllustsPage> SearchIllustAsync(this PixivClient client, string word, SearchMode mode = SearchMode.PartialMatchTags, SortOptions sortOptions = SortOptions.DateDecreasing, SearchDuration?duration = default, int offset = 0)
        {
            var data = new HttpForm {
                { "word", word }, { "search_target", mode.GetSymbol() }, { "sort", sortOptions.GetSymbol() }, { "offset", offset.ToString() }
            };

            if (duration != null)
            {
                data.Add("duration", duration.GetSymbol());
            }

            return(client.GetAsync <IllustsPage>("/v1/search/illust"));
        }
        public void TestModifications()
        {
            HttpFile file = new HttpFile("testFile", "nun", "nun");

            _form.AddFile(file);
            Assert.Equal(file, _form.GetFile("testFile"));

            _form.Add("valueName", "value");
            Assert.Equal("value", _form["valueName"].Value);

            _form.Clear();
            Assert.Null(_form.GetFile("testFile"));
            Assert.Null(_form["valueName"].Value);
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
        /// <param name="encoding">Stream encoding</param>
        /// Note: contentType and encoding are not used?
        /// <returns>A http form, or null if content could not be parsed.</returns>
        /// <exception cref="InvalidDataException"></exception>
        public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
        {
            if (stream == null || stream.Length == 0)
            {
                return(null);
            }
            if (!CanParse(contentType))
            {
                return(null);
            }
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            HttpForm form = new HttpForm();

            using (TextReader reader = new StreamReader(stream, encoding))
            {
                // let's start with saving the raw xml
                form.Add("__xml__", reader.ReadToEnd());

                try
                {
                    // Now let's process the data.
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(form["__xml__"].Value);
                    XmlNode child = doc.FirstChild;
                    // Skip to next node if the node is an XML Declaration
                    if (child.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        child = child.NextSibling;
                    }
                    TraverseNode(form, child);
                }
                catch (XmlException err)
                {
                    throw new InvalidDataException("Failed to traverse XML", err);
                }
            }

            return(form);
        }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="stream">Stream containing the content</param>
    /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
    /// <param name="encoding">Stream enconding</param>
    /// <returns>A http form, or null if content could not be parsed.</returns>
    /// <exception cref="InvalidDataException">If contents in the stream is not valid input data.</exception>
    /// <exception cref="ArgumentNullException">If any parameter is null</exception>
    public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
    {
      if (stream == null)
        throw new ArgumentNullException("stream");
      if (string.IsNullOrEmpty(contentType))
        throw new ArgumentNullException("contentType");
      if (encoding == null)
        throw new ArgumentNullException("encoding");

      if (!CanParse(contentType))
        throw new InvalidOperationException("Cannot parse contentType: " + contentType);

      //multipart/form-data, boundary=AaB03x
      int pos = contentType.IndexOf("=");
      if (pos == -1)
        throw new InvalidDataException("Missing boundry in content type.");

      string boundry = contentType.Substring(pos + 1).Trim();
      HttpMultipart multipart = new HttpMultipart(stream, boundry, encoding);

      HttpForm form = new HttpForm();

      HttpMultipart.Element element;
      while ((element = multipart.ReadNextElement()) != null)
      {
        if (string.IsNullOrEmpty(element.Name))
          throw new InvalidDataException("Error parsing request. Missing value name.\nElement: " + element);

        if (!string.IsNullOrEmpty(element.Filename))
        {
          if (string.IsNullOrEmpty(element.ContentType))
            throw new InvalidDataException("Error parsing request. Value '" + element.Name + "' lacks a content type.");

          // Read the file data
          byte[] buffer = new byte[element.Length];
          stream.Seek(element.Start, SeekOrigin.Begin);
          stream.Read(buffer, 0, (int) element.Length);

          // Generate a filename
          string filename = element.Filename;
          string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
          // if the internet path doesn't exist, assume mono and /var/tmp
          string path = string.IsNullOrEmpty(internetCache)
              ? Path.Combine("var", "tmp")
              : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");
          element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

          // If the file exists generate a new filename
          while (File.Exists(element.Filename))
            element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");

          if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

          File.WriteAllBytes(element.Filename, buffer);
          form.AddFile(new HttpFile(element.Name, element.Filename, element.ContentType, filename));
        }
        else
        {
          byte[] buffer = new byte[element.Length];
          stream.Seek(element.Start, SeekOrigin.Begin);
          stream.Read(buffer, 0, (int) element.Length);
          form.Add(element.Name, encoding.GetString(buffer));
        }
      }

      return form;
    }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type (with any additional info like boundry). Content type is always supplied in lower case</param>
        /// <param name="encoding">Stream enconding</param>
        /// <returns>A http form, or null if content could not be parsed.</returns>
        /// <exception cref="InvalidDataException">If contents in the stream is not valid input data.</exception>
        /// <exception cref="ArgumentNullException">If any parameter is null</exception>
        public HttpForm Decode(Stream stream, string contentType, Encoding encoding)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (string.IsNullOrEmpty(contentType))
            {
                throw new ArgumentNullException("contentType");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            if (!CanParse(contentType))
            {
                throw new InvalidOperationException("Cannot parse contentType: " + contentType);
            }

            //multipart/form-data, boundary=AaB03x
            int pos = contentType.IndexOf("=");

            if (pos == -1)
            {
                throw new InvalidDataException("Missing boundry in content type.");
            }

            string        boundry   = contentType.Substring(pos + 1).Trim();
            HttpMultipart multipart = new HttpMultipart(stream, boundry, encoding);

            HttpForm form = new HttpForm();

            HttpMultipart.Element element;
            while ((element = multipart.ReadNextElement()) != null)
            {
                if (string.IsNullOrEmpty(element.Name))
                {
                    throw new InvalidDataException("Error parsing request. Missing value name.\nElement: " + element);
                }

                if (!string.IsNullOrEmpty(element.Filename))
                {
                    if (string.IsNullOrEmpty(element.ContentType))
                    {
                        throw new InvalidDataException("Error parsing request. Value '" + element.Name + "' lacks a content type.");
                    }

                    // Read the file data
                    byte[] buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int)element.Length);

                    // Generate a filename
                    string filename      = element.Filename;
                    string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
                    // if the internet path doesn't exist, assume mono and /var/tmp
                    string path = string.IsNullOrEmpty(internetCache)
                                               ? Path.Combine("var", "tmp")
                                               : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");
                    element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

                    // If the file exists generate a new filename
                    while (File.Exists(element.Filename))
                    {
                        element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");
                    }

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    File.WriteAllBytes(element.Filename, buffer);
                    form.AddFile(new HttpFile(element.Name, element.Filename, element.ContentType, filename));
                }
                else
                {
                    byte[] buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int)element.Length);
                    form.Add(element.Name, encoding.GetString(buffer));
                }
            }

            return(form);
        }
Exemple #9
0
 private void TestPost()
 {
     MyController controller = new MyController();
     IHttpResponse response;
     IHttpSession session = DefaultSession;
     HttpForm form = new HttpForm();
     form.Add("user[firstName]", "jonas");
     string text = Post(controller, "/my/hello/id", form, out response, session);
     Assert.Equal("jonas", text);
 }