void LoadMultiPart()
        {
            string boundary = GetParameter(ContentType, "; boundary=");

            if (boundary == null)
            {
                return;
            }

            Stream        input      = GetSubStream(InputStream);
            HttpMultipart multi_part = new HttpMultipart(input, boundary, ContentEncoding);

            HttpMultipart.Element e;
            while ((e = multi_part.ReadNextElement()) != null)
            {
                if (e.Filename == null)
                {
                    byte[] copy = new byte[e.Length];

                    input.Position = e.Start;
                    input.Read(copy, 0, (int)e.Length);

                    form.Add(e.Name, ContentEncoding.GetString(copy));
                }
                else
                {
                    //
                    // We use a substream, as in 2.x we will support large uploads streamed to disk,
                    //
                    HttpPostedFile sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
                    files.AddFile(e.Name, sub);
                }
            }
            EndSubStream(input);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Extracts the JSON part from the multi-part message
        /// </summary>
        /// <returns>
        /// A <see cref="Stream"/> that contains the posted JSON
        /// </returns>
        private Stream ExtractJsonBodyStreamFromMultiPartMessage()
        {
            var contentType           = this.Request.Headers.ContentType;
            var boundary              = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
            var multipart             = new HttpMultipart(this.Request.Body, boundary);
            var multipartBoundaries   = multipart.GetBoundaries();
            var jsonMultipartBoundary = multipartBoundaries.SingleOrDefault(x => x.ContentType == "application/json");

            if (jsonMultipartBoundary == null)
            {
                throw new InvalidOperationException("A multipart request must contain a JSON part");
            }

            var bodyStream = jsonMultipartBoundary.Value;

            if (Logger.IsTraceEnabled)
            {
                var reader        = new StreamReader(bodyStream);
                var multipartjson = reader.ReadToEnd();
                bodyStream.Position = 0;

                Logger.Trace("multipart post JSON: {0}", multipartjson);
            }

            return(bodyStream);
        }
Ejemplo n.º 3
0
        private Stream GetImageBodyStream()
        {
            var contentTypeRegex = new Regex("^multipart/form-data;\\s*boundary=(.*)$", RegexOptions.IgnoreCase);
            var boundary         = contentTypeRegex.Match(Request.Headers.ContentType).Groups[1].Value;
            var multipart        = new HttpMultipart(Request.Body, boundary);
            var bodyStream       = multipart.GetBoundaries().First(b => b.Name == "image").Value;

            return(bodyStream);
        }
Ejemplo n.º 4
0
        public void Should_locate_all_boundaries()
        {
            // Given
            var stream = BuildInputStream(null, 10);
            var multipart = new HttpMultipart(stream, Boundary);

            // When
            var boundaries = multipart.GetBoundaries();

            // Then
            boundaries.Count().ShouldEqual(10);
        }
Ejemplo n.º 5
0
        public void Should_locate_boundary_when_it_is_not_at_the_beginning_of_stream()
        {
            // Given
            var stream = BuildInputStream("some padding in the stream", 1);
            var multipart = new HttpMultipart(stream, Boundary);

            // When
            var boundaries = multipart.GetBoundaries();

            // Then
            boundaries.Count().ShouldEqual(1);
        }
Ejemplo n.º 6
0
        public void Should_locate_boundary_when_it_is_not_at_the_beginning_of_stream()
        {
            // Given
            var stream    = BuildInputStream("some padding in the stream", 1);
            var multipart = new HttpMultipart(stream, Boundary);

            // When
            var boundaries = multipart.GetBoundaries();

            // Then
            boundaries.Count().ShouldEqual(1);
        }
Ejemplo n.º 7
0
        public void Should_locate_all_boundaries()
        {
            // Given
            var stream    = BuildInputStream(null, 10);
            var multipart = new HttpMultipart(stream, Boundary);

            // When
            var boundaries = multipart.GetBoundaries();

            // Then
            boundaries.Count().ShouldEqual(10);
        }
Ejemplo n.º 8
0
        public void Should_limit_the_number_of_boundaries()
        {
            // Given
            var stream    = BuildInputStream(null, StaticConfiguration.RequestQueryFormMultipartLimit + 10);
            var multipart = new HttpMultipart(stream, Boundary);

            // When
            var boundaries = multipart.GetBoundaries();

            // Then
            boundaries.Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// The file start.
        /// </summary>
        /// <param name="stream">
        /// The stream.
        /// </param>
        /// <returns>
        /// The <see cref="ServiceResponse"/>.
        /// </returns>
        public FilesUploadedResultDTO uploadMultipart(string fileId, Stream stream)
        {
            try
            {
                var request        = this.CurrentRequest;
                var requestHeaders = request.Headers;

                Guid fileIdVal;
                if (string.IsNullOrWhiteSpace(fileId) || !Guid.TryParse(fileId, out fileIdVal))
                {
                    throw new ApplicationException("fileId is not passed or not a GUID");
                }

                string contentType   = requestHeaders["Content-Type"];
                int    boundaryIndex = contentType.With(x => x.IndexOf("boundary=", StringComparison.Ordinal));
                var    streamedFiles = new HttpMultipart(
                    stream,
                    boundaryIndex > 0 ? contentType.Substring(boundaryIndex + 9).Trim() : null);
                var createdFiles  = new List <Guid>();
                var notSavedFiles = new Dictionary <string, string>();
                foreach (var httpMultipartBoundary in streamedFiles.GetBoundaries())
                {
                    var fileName = string.IsNullOrWhiteSpace(httpMultipartBoundary.Filename)
                                       ? httpMultipartBoundary.Name
                                       : httpMultipartBoundary.Filename;
                    if (fileName.Equals("FileName", StringComparison.InvariantCultureIgnoreCase) ||
                        fileName.Equals("Upload", StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    var file = new UploadedFileDTO
                    {
                        fileId      = fileIdVal,
                        fileName    = fileName,
                        contentType = httpMultipartBoundary.ContentType,
                        content     = httpMultipartBoundary.Value.ReadFully(),
                        dateCreated = DateTime.Now,
                    };

                    this.FileModel.SaveWeborbFile(file);
                    createdFiles.Add(fileIdVal);
                }

                return(this.FormatSuccessfulResponse(createdFiles, notSavedFiles));
            }
            catch (Exception ex)
            {
                var error = new Error(Errors.CODE_ERRORTYPE_GENERIC_ERROR, "File upload unhandled exception", ex.ToString());
                IoC.Resolve <ILogger>().Error("File upload unhandled exception", ex);
                throw new FaultException <Error>(error, error.errorMessage);
            }
        }
Ejemplo n.º 10
0
        void LoadMultiPart()
        {
            string boundary = GetParameter(ContentType, "; boundary=");

            if (boundary == null)
            {
                return;
            }

            var input = GetSubStream(InputStream);

            //DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
            //Not ending with \r\n?
            var ms = MemoryStreamFactory.GetStream(32 * 1024);

            input.CopyTo(ms);
            input = ms;
            ms.WriteByte((byte)'\r');
            ms.WriteByte((byte)'\n');

            input.Position = 0;

            //Uncomment to debug
            var content = ms.ReadToEnd();

            Console.WriteLine(boundary + "::" + content);
            input.Position = 0;

            var multi_part = new HttpMultipart(input, boundary, ContentEncoding);

            HttpMultipart.Element e;
            while ((e = multi_part.ReadNextElement()) != null)
            {
                if (e.Filename == null)
                {
                    byte[] copy = new byte[e.Length];

                    input.Position = e.Start;
                    input.Read(copy, 0, (int)e.Length);

                    form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy));
                }
                else
                {
                    //
                    // We use a substream, as in 2.x we will support large uploads streamed to disk,
                    //
                    HttpPostedFile sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
                    files.AddFile(e.Name, sub);
                }
            }
            EndSubStream(input);
        }
Ejemplo n.º 11
0
        private async Task LoadMultiPart(WebROCollection form)
        {
            string boundary = GetParameter(ContentType, "; boundary=");

            if (boundary == null)
            {
                return;
            }

            using (var requestStream = InputStream)
            {
                // DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
                // Not ending with \r\n?
                var ms = new MemoryStream(32 * 1024);
                await requestStream.CopyToAsync(ms).ConfigureAwait(false);

                var input = ms;
                ms.WriteByte((byte)'\r');
                ms.WriteByte((byte)'\n');

                input.Position = 0;

                // Uncomment to debug
                // var content = new StreamReader(ms).ReadToEnd();
                // Console.WriteLine(boundary + "::" + content);
                // input.Position = 0;

                var multi_part = new HttpMultipart(input, boundary, ContentEncoding);

                HttpMultipart.Element e;
                while ((e = multi_part.ReadNextElement()) != null)
                {
                    if (e.Filename == null)
                    {
                        byte[] copy = new byte[e.Length];

                        input.Position = e.Start;
                        input.Read(copy, 0, (int)e.Length);

                        form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
                    }
                    else
                    {
                        //
                        // We use a substream, as in 2.x we will support large uploads streamed to disk,
                        //
                        var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
                        files[e.Name] = sub;
                    }
                }
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Testing Mono");
            string boundary           = "9051914041544843365972754266";
            string body_input_with_cr = "--9051914041544843365972754266\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\ntext default\r\n--9051914041544843365972754266\r\nContent-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"\r\nContent-Type: text/plain\r\n\r\nContent of a.txt.\r\n\r\n--9051914041544843365972754266\r\nContent-Disposition: form-data; name=\"file2\"; filename=\"a.html\"\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE html><title>Content of a.html.</title>\r\n\r\n--9051914041544843365972754266--";
            string body_input_no_cr   = "--9051914041544843365972754266\nContent-Disposition: form-data; name=\"text\"\n\ntext default\n--9051914041544843365972754266\nContent-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"\nContent-Type: text/plain\n\nContent of a.txt.\n\n--9051914041544843365972754266\nContent-Disposition: form-data; name=\"file2\"; filename=\"a.html\"\nContent-Type: text/html\n\n<!DOCTYPE html><title>Content of a.html.</title>\n\n--9051914041544843365972754266--";

            string input = body_input_no_cr;

            byte[] bytes = Encoding.ASCII.GetBytes(input);
            var    data  = new MemoryStream();

            data.Write(bytes, 0, bytes.Length);
            data.Position = 0;
            var multipart = new HttpMultipart(data, boundary, Encoding.UTF8);

            HttpMultipart.Element ele;
            Console.WriteLine("\nBroken MONO Implementation\n");
            while ((ele = multipart.ReadNextElement()) != null)
            {
                var val = System.Text.Encoding.UTF8.GetString(bytes, (int)ele.Start, (int)ele.Length);
                Console.WriteLine("Part Length: " + ele.Length + " Value:" + val);
            }

            data.Position = 0;
            var fix_multipart = new Fix_HttpMultipart(data, boundary, Encoding.UTF8);

            Fix_HttpMultipart.Element fixele;
            Console.WriteLine("\nFixed MONO Implementation\n");
            while ((fixele = fix_multipart.ReadNextElement()) != null)
            {
                var val = System.Text.Encoding.UTF8.GetString(bytes, (int)fixele.Start, (int)fixele.Length);
                Console.WriteLine("Part Length: " + fixele.Length + " Value:" + val);
            }


            data.Position = 0;

            string prepended_boundary = "--9051914041544843365972754266";
            var    net_multipart      = new HttpMultipartContentTemplateParser(bytes, input.Length, Encoding.ASCII.GetBytes(prepended_boundary), Encoding.UTF8);

            Console.WriteLine("\nNET Implementation\n");
            net_multipart.ParseIntoElementList();
            foreach (MultipartContentElement element in net_multipart._elements)
            {
                var val = System.Text.Encoding.UTF8.GetString(bytes, (int)element._offset, (int)element._length);
                Console.WriteLine("Part Length: " + element._length + " Value:" + val);
            }
        }
Ejemplo n.º 13
0
        private void ParseFormData()
        {
            if (string.IsNullOrEmpty(this.Headers.ContentType))
            {
                return;
            }

            var contentType = this.Headers["content-type"].First();
            var mimeType    = contentType.Split(';').First();

            if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
            {
                var reader = new StreamReader(this.Body);
                this.form          = reader.ReadToEnd().AsQueryDictionary();
                this.Body.Position = 0;
            }

            if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var boundary  = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
            var multipart = new HttpMultipart(this.Body, boundary);

            var formValues = new NameValueCollection(StringComparer.OrdinalIgnoreCase);

            foreach (var httpMultipartBoundary in multipart.GetBoundaries())
            {
                if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
                {
                    var reader = new StreamReader(httpMultipartBoundary.Value);
                    formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());
                }
                else
                {
                    this.files.Add(new HttpFile(httpMultipartBoundary));
                }
            }

            foreach (var key in formValues.AllKeys.Where(key => key != null))
            {
                this.form[key] = formValues[key];
            }

            this.Body.Position = 0;
        }
        private string GetJsonBody()
        {
            var    contentTypeRegex = new Regex("^multipart/form-data;\\s*boundary=(.*)$", RegexOptions.IgnoreCase);
            Stream bodyStream       = null;

            if (contentTypeRegex.IsMatch(Request.Headers.ContentType))
            {
                var boundary  = contentTypeRegex.Match(Request.Headers.ContentType).Groups[1].Value;
                var multipart = new HttpMultipart(Request.Body, boundary);
                bodyStream = multipart.GetBoundaries().First(b => b.Name.Equals("json")).Value;
            }
            else
            {
                // Regular model binding goes here.
                bodyStream = Request.Body;
            }

            var jsonBody = new StreamReader(bodyStream).ReadToEnd();

            return(jsonBody);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Decode body stream
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Decoded data.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Something unexpected failed.</exception>
        /// <exception cref="ArgumentNullException"><c>stream</c> is <c>null</c>.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (contentType == null)
                throw new ArgumentNullException("contentType");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            //multipart/form-data, boundary=AaB03x
            string boundry = contentType.Parameters["boundary"];
            if (boundry == null)
                throw new FormatException("Missing boundary in content type.");

            var multipart = new HttpMultipart(stream, boundry, encoding);

            var form = new DecodedData();
            /*
            FileStream stream1 = new FileStream("C:\\temp\\mimebody.tmp", FileMode.Create);
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream1.Write(bytes, 0, bytes.Length);
            stream1.Flush();
            stream1.Close();
            */

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

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

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

                    // Generate a filename
                    string originalFileName = 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);

                    var file = new HttpFile
                                   {
                                       Name = element.Name,
                                       OriginalFileName = originalFileName,
                                       ContentType = element.ContentType,
                                       TempFileName = element.Filename
                                   };
                    form.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int) element.Length);

                    form.Parameters.Add(HttpUtility.UrlDecode(element.Name), encoding.GetString(buffer));
                }
            }

            return form;
        }
Ejemplo n.º 16
0
        public OSHttpRequest(HttpListenerContext context)
        {
            _request = context.Request;
            _context = context;

            if (null != _request.Headers["content-encoding"])
                _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
            if (null != _request.Headers["content-type"])
                _contentType = _request.Headers["content-type"];
            _queryString = new NameValueCollection();
            _query = new Hashtable();
            try
            {
                foreach (string item in _request.QueryString.Keys)
                {
                    try
                    {
                        _queryString.Add(item, _request.QueryString[item]);
                        _query[item] = _request.QueryString[item];
                    }
                    catch (InvalidCastException)
                    {
                        MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it",
                                                         item);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                MainConsole.Instance.Error("[OSHttpRequest]: Error parsing querystring");
            }

            if (ContentType != null && ContentType.StartsWith("multipart/form-data"))
            {
                HttpMultipart.Element element;
                var boundry = "";
                var multipart = new HttpMultipart(InputStream, boundry, ContentEncoding ?? Encoding.UTF8);

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

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

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

                        // Generate a filename
                        var originalFileName = element.Filename;
                        var internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                        // if the internet path doesn't exist, assume mono and /var/tmp
                        var 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);

                        var file = new HttpFile
                                       {
                                           Name = element.Name,
                                           OriginalFileName = originalFileName,
                                           ContentType = element.ContentType,
                                           TempFileName = element.Filename
                                       };
                        Files.Add(element.Name, file);
                    }
                    /*else
                    {
                        var buffer = new byte[element.Length];
                        message.Body.Seek(element.Start, SeekOrigin.Begin);
                        message.Body.Read(buffer, 0, (int)element.Length);

                        form.Add(Uri.UnescapeDataString(element.Name), message.ContentEncoding.GetString(buffer));
                    }*/
                }
            }
        }
Ejemplo n.º 17
0
        public OSHttpRequest(HttpListenerContext context)
        {
            _request = context.Request;
            _context = context;

            if (null != _request.Headers["content-encoding"])
            {
                _contentEncoding = Encoding.GetEncoding(_request.Headers["content-encoding"]);
            }
            if (null != _request.Headers["content-type"])
            {
                _contentType = _request.Headers["content-type"];
            }
            _queryString = new NameValueCollection();
            _query       = new Hashtable();
            try
            {
                foreach (string item in _request.QueryString.Keys)
                {
                    try
                    {
                        _queryString.Add(item, _request.QueryString[item]);
                        _query[item] = _request.QueryString[item];
                    }
                    catch (InvalidCastException)
                    {
                        MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it",
                                                         item);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                MainConsole.Instance.Error("[OSHttpRequest]: Error parsing querystring");
            }

            if (ContentType != null && ContentType.StartsWith("multipart/form-data"))
            {
                HttpMultipart.Element element;
                var boundry   = "";
                var multipart = new HttpMultipart(InputStream, boundry, ContentEncoding ?? Encoding.UTF8);

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

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

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

                        // Generate a filename
                        var originalFileName = element.Filename;
                        var internetCache    = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                        // if the internet path doesn't exist, assume mono and /var/tmp
                        var 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);

                        var file = new HttpFile
                        {
                            Name             = element.Name,
                            OriginalFileName = originalFileName,
                            ContentType      = element.ContentType,
                            TempFileName     = element.Filename
                        };
                        Files.Add(element.Name, file);
                    }

                    /*else
                     * {
                     *  var buffer = new byte[element.Length];
                     *  message.Body.Seek(element.Start, SeekOrigin.Begin);
                     *  message.Body.Read(buffer, 0, (int)element.Length);
                     *
                     *  form.Add(Uri.UnescapeDataString(element.Name), message.ContentEncoding.GetString(buffer));
                     * }*/
                }
            }
        }
Ejemplo n.º 18
0
        public dynamic Execute(dynamic parameters, INancyModule module)
        {
            var contentType = module.Request.Headers["content-type"].First();
            var mimeType    = contentType.Split(';').First();

            if (mimeType != "multipart/batch" && mimeType != "multipart/mixed")
            {
                return((int)HttpStatusCode.BadRequest);
            }

            var multipartBoundry = Regex.Match(contentType, @"boundary=(?<token>[^\n\; ]*)").Groups["token"].Value.Replace("\"", "");

            if (string.IsNullOrEmpty(multipartBoundry))
            {
                return((int)HttpStatusCode.BadRequest);
            }



            var multipart = new HttpMultipart(module.Request.Body, multipartBoundry);

            IDictionary <string, IEnumerable <string> > headers = module.Request.Headers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);


            string batchResponseGuid = Guid.NewGuid().ToString().ToLower();

            var response = new Response
            {
                ContentType = string.Format("{0}; boundary=batchresponse_{1}", mimeType, batchResponseGuid),
                StatusCode  = HttpStatusCode.Accepted
            };

            _responseBuilder.Append(string.Format("--batchresponse_{0}\r\n", batchResponseGuid));
            _responseBuilder.Append("Content-Type: application/http\r\n");
            _responseBuilder.Append("Content-Transfer-Encoding: binary\r\n\r\n");

            foreach (var boundry in multipart.GetBoundaries())
            {
                using (var httpRequest = new StreamReader(boundry.Value))
                {
                    var httpRequestText = httpRequest.ReadToEnd();

                    var rawRequestStream = new MemoryStream(Encoding.UTF8.GetBytes(httpRequestText));
                    var nancyRequest     = rawRequestStream.ReadAsRequest(headers);

                    _engine.HandleRequest(nancyRequest, OnSuccess, OnError);
                }
            }

            _responseBuilder.Append(string.Format("\r\n--batchresponse_{0}--", batchResponseGuid));

            var responseText = _responseBuilder.ToString();
            var byteData     = Encoding.UTF8.GetBytes(responseText);

            response.Headers.Add("Content-Length", byteData.Length.ToString());

            response.Contents = contentStream =>
            {
                contentStream.Write(byteData, 0, byteData.Length);
            };

            return(response);
        }
Ejemplo n.º 19
0
        public TeamModule(IBootstrapInjection injection)
        {
            _teamService           = injection.Services.Team;
            _teamPontuationService = injection.Services.TeamPontuation;
            Get[EndpointConfigurationEnum.GET_TEAM] = p =>
            {
                var teamId = p.teamId;
                return(Response.AsJson(new TeamDTO(_teamService.GetTeam(teamId))));
            };

            Post[EndpointConfigurationEnum.JOIN_TEAM] = p =>
            {
                var token  = p.token;
                var userId = p.userId;
                var teamid = p.teamId;
                _teamService.JoinTeam(userId, token, teamid);
                return(HttpStatusCode.OK);
            };



            Get[EndpointConfigurationEnum.GET_TEAM_USER] = p =>
            {
                var team = _teamService.GetTeamFromUser(p.userId);
                if (team == null)
                {
                    return(HttpStatusCode.NotFound);
                }
                return(Response.AsJson(new TeamDTO(team)));
            };

            Put[EndpointConfigurationEnum.GET_IMAGE_TEAM] = p =>
            {
                var contentTypeRegex = new Regex("^multipart/form-data;\\s*boundary=(.*)$", RegexOptions.IgnoreCase);
                var boundary         = contentTypeRegex.Match(Request.Headers.ContentType).Groups[1].Value;
                var multipart        = new HttpMultipart(this.Request.Body, boundary);
                var bodyStream       = multipart.GetBoundaries().First(b => b.Name == "image").Value;
                var teamId           = p.teamId;
                _teamService.SubmitTeamImage(teamId, bodyStream);
                return(HttpStatusCode.OK);
            };

            Get[EndpointConfigurationEnum.GET_IMAGE_TEAM] = p =>
            {
                try
                {
                    Stream imagem = _teamService.GetImage(p.teamId);
                    if (imagem == null)
                    {
                        throw new ArgumentException("Não existe");
                    }
                    return(Response.FromStream(imagem, "image/jpg"));
                }
                catch (ArgumentException)
                {
                    return(HttpStatusCode.NotFound);
                }
                catch (Exception)
                {
                    return(HttpStatusCode.InternalServerError);
                }
            };

            Post[EndpointConfigurationEnum.CREATE_TEAM] = p =>
            {
                try
                {
                    var founderId = p.founderId.Value;
                    var dto       = JsonConvert.DeserializeObject <TeamDTO>(Request.Body.AsString());
                    _teamService.CreateTeam(founderId, dto.Id, dto.Alias);
                    dto.Members.Where(c => c.Contains("@")).ToList()
                    .ForEach(c => _teamService.InvitePlayer(c, dto.Id));
                    return(HttpStatusCode.OK);
                }
                catch (TeamAlreadyExistException ex)
                {
                    return(Response.AsJson(new GenericErrorDTO(ex)));
                }
                catch (Exception ex)
                {
                    return(Response.AsJson(new GenericErrorDTO(ex)));
                }
            };

            Put[EndpointConfigurationEnum.INVITE_PLAYER_TEAM] = p =>
            {
                if (p.email.ToString().Contains("@"))
                {
                    _teamService.InvitePlayer(p.email.ToString(), p.teamId.ToString());
                    return(HttpStatusCode.Accepted);
                }
                else
                {
                    return(HttpStatusCode.NotAcceptable);
                }
            };

            Get[EndpointConfigurationEnum.GET_TEAM_PONTUATIONS] = p =>
            {
                string id     = p.teamId.ToString();
                var    result = _teamPontuationService.GetTeamPontuations(id).Select(c => new PlayerPontuationDTO(c)).ToList();
                return(Response.AsJson(result));
            };
        }
        public new static MyBasicHttpExecutionContent GetRunContent(XmlNode yourContentNode)
        {
            MyBasicHttpExecutionContent myRunContent = new MyBasicHttpExecutionContent();

            if (yourContentNode != null)
            {
                if (yourContentNode.Attributes["protocol"] != null && yourContentNode.Attributes["actuator"] != null)
                {
                    //Content
                    try
                    {
                        myRunContent.caseProtocol = (CaseProtocol)Enum.Parse(typeof(CaseProtocol), yourContentNode.Attributes["protocol"].Value);
                    }
                    catch
                    {
                        myRunContent.errorMessage = "Error :error protocol in Content";
                        return(myRunContent);
                    }
                    myRunContent.caseActuator = yourContentNode.Attributes["actuator"].Value;

                    //Uri
                    XmlNode tempUriDataNode = yourContentNode["Uri"];
                    if (tempUriDataNode != null)
                    {
                        if (tempUriDataNode.Attributes["httpMethod"] != null)
                        {
                            myRunContent.httpMethod = tempUriDataNode.Attributes["httpMethod"].Value;
                        }
                        else
                        {
                            myRunContent.httpMethod = "GET";
                        }
                        myRunContent.httpUri = CaseTool.GetXmlParametContent(tempUriDataNode);
                    }
                    else
                    {
                        myRunContent.errorMessage = "Error :http uri (this element is necessary)";
                        return(myRunContent);
                    }

                    //HttpHeads
                    XmlNode tempHttpHeadsDataNode = yourContentNode["Heads"];
                    if (tempHttpHeadsDataNode != null)
                    {
                        if (tempHttpHeadsDataNode.HasChildNodes)
                        {
                            foreach (XmlNode headNode in tempHttpHeadsDataNode.ChildNodes)
                            {
                                if (headNode.Attributes["name"] != null)
                                {
                                    myRunContent.httpHeads.Add(new KeyValuePair <string, caseParameterizationContent>(headNode.Attributes["name"].Value, CaseTool.GetXmlParametContent(headNode)));
                                }
                                else
                                {
                                    myRunContent.errorMessage = "Error :can not find http Head name in heads";
                                }
                            }
                        }
                    }

                    //HttpBody
                    XmlNode tempHttpBodyDataNode = yourContentNode["Body"];
                    if (tempHttpHeadsDataNode != null)
                    {
                        myRunContent.httpBody = CaseTool.GetXmlParametContent(tempHttpBodyDataNode);
                    }
                    //AisleConfig
                    if (yourContentNode["AisleConfig"] != null)
                    {
                        myRunContent.myHttpAisleConfig.httpDataDown = CaseTool.GetXmlParametContent(yourContentNode["AisleConfig"], "HttpDataDown");
                    }
                    //HttpMultipart
                    XmlNode tempHttpMultipartNode = yourContentNode["HttpMultipart"];
                    if (tempHttpMultipartNode != null)
                    {
                        if (tempHttpMultipartNode.HasChildNodes)
                        {
                            foreach (XmlNode multipartNode in tempHttpMultipartNode.ChildNodes)
                            {
                                HttpMultipart hmp = new HttpMultipart();
                                if (multipartNode.Name == "MultipartData")
                                {
                                    hmp.isFile   = false;
                                    hmp.fileData = multipartNode.InnerText;
                                }
                                else if (multipartNode.Name == "MultipartFile")
                                {
                                    hmp.isFile   = true;
                                    hmp.fileData = CaseTool.GetFullPath(multipartNode.InnerText, MyConfiguration.CaseFilePath);
                                }
                                else
                                {
                                    continue;
                                }
                                hmp.name     = CaseTool.GetXmlAttributeVauleEx(multipartNode, "name", null);
                                hmp.fileName = CaseTool.GetXmlAttributeVauleEx(multipartNode, "filename", null);
                                myRunContent.myMultipartList.Add(hmp);
                            }
                        }
                    }
                }
                else
                {
                    myRunContent.errorMessage = "Error :can not find protocol or actuator in Content ";
                }
            }
            else
            {
                myRunContent.errorMessage = "Error :yourContentNode is null";
            }
            return(myRunContent);
        }
Ejemplo n.º 21
0
            private async Task <FormData> GetForm()
            {
                var formData = _environment.Get <FormData>("SuperGlue.Owin.Form#data");

                if (formData != null)
                {
                    return(formData);
                }

                var form = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);

                if (string.IsNullOrEmpty(Headers.ContentType))
                {
                    formData = new FormData(new ReadableStringCollection(form.ToDictionary(x => x.Key, x => x.Value.ToArray())), new List <HttpFile>());
                    Set("SuperGlue.Owin.Form#data", formData);
                    return(formData);
                }

                var contentType = Headers.ContentType;
                var mimeType    = contentType.Split(';').First();

                if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                {
                    var reader = new StreamReader(Body, Encoding.UTF8, true, 4 * 1024, true);

                    var accumulator = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);

                    ParseDelimited(await reader.ReadToEndAsync().ConfigureAwait(false), new[] { '&' }, AppendItemCallback, accumulator);

                    foreach (var kv in accumulator)
                    {
                        form.Add(kv.Key, kv.Value);
                    }
                }

                if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
                {
                    formData = new FormData(new ReadableStringCollection(form.ToDictionary(x => x.Key, x => x.Value.ToArray())), new List <HttpFile>());
                    Set("SuperGlue.Owin.Form#data", formData);
                    return(formData);
                }

                var boundary  = Regex.Match(contentType, @"boundary=(?<token>[^\n\; ]*)").Groups["token"].Value;
                var multipart = new HttpMultipart(Body, boundary);

                var files = new List <HttpFile>();

                foreach (var httpMultipartBoundary in multipart.GetBoundaries())
                {
                    if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
                    {
                        var reader = new StreamReader(httpMultipartBoundary.Value);

                        if (!form.ContainsKey(httpMultipartBoundary.Name))
                        {
                            form[httpMultipartBoundary.Name] = new List <string>();
                        }

                        form[httpMultipartBoundary.Name].Add(reader.ReadToEnd());
                    }
                    else
                    {
                        files.Add(new HttpFile(
                                      httpMultipartBoundary.ContentType,
                                      httpMultipartBoundary.Filename,
                                      httpMultipartBoundary.Value
                                      ));
                    }
                }

                formData = new FormData(new ReadableStringCollection(form.ToDictionary(x => x.Key, x => x.Value.ToArray())), files);
                Set("SuperGlue.Owin.Form#data", formData);
                return(formData);
            }
Ejemplo n.º 22
0
        public bool Decode(IRequest message)
        {
            if (!message.ContentType.StartsWith(MimeType))
            {
                return(false);
            }

            var contentType = message.Headers["Content-Type"];
            //multipart/form-data, boundary=AaB03x
            var boundry = contentType.GetParameter("boundry");

            if (boundry == null)
            {
                throw new FormatException("Missing boundary in content type.");
            }

            var multipart = new HttpMultipart(message.Body, boundry, message.ContentEncoding);

            var form = message.Form;

            /*
             * FileStream stream1 = new FileStream("C:\\temp\\mimebody.tmp", FileMode.Create);
             * byte[] bytes = new byte[stream.Length];
             * stream.Read(bytes, 0, bytes.Length);
             * stream1.Write(bytes, 0, bytes.Length);
             * stream1.Flush();
             * stream1.Close();
             */

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

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

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

                    // Generate a filename
                    var    originalFileName = element.Filename;
                    string internetCache    = null;// Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

                    // if the internet path doesn't exist, assume mono and /var/tmp
                    var 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);

                    var file = new HttpFile
                    {
                        Name             = element.Name,
                        OriginalFileName = originalFileName,
                        ContentType      = element.ContentType,
                        TempFileName     = element.Filename
                    };
                    message.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    message.Body.Seek(element.Start, SeekOrigin.Begin);
                    message.Body.Read(buffer, 0, (int)element.Length);

                    form.Add(Uri.UnescapeDataString(element.Name), message.ContentEncoding.GetString(buffer));
                }
            }


            return(true);
        }
Ejemplo n.º 23
0
        void LoadMultiPart()
        {
            this.Form = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            this.Files = new Dictionary<string, HttpPostedFile>(StringComparer.OrdinalIgnoreCase);

            var contentType = this.request.ContentType;

            if (contentType == null)
            {
                return;
            }

            string boundary = GetParameter(contentType, "; boundary=");

            if (boundary == null)
            {
                return;
            }

            Stream input = GetSubStream(this.request.InputStream);

            //DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
            //Not ending with \r\n?
            var ms = new MemoryStream(32 * 1024);
            input.CopyTo(ms);
            input = ms;
            ms.WriteByte((byte)'\r');
            ms.WriteByte((byte)'\n');

            input.Position = 0;

            //Uncomment to debug
            //var content = new StreamReader(ms).ReadToEnd();
            //Console.WriteLine(boundary + "::" + content);
            //input.Position = 0;

            HttpMultipart multi_part = new HttpMultipart(input, boundary, this.request.ContentEncoding);

            HttpMultipart.Element e;
            while ((e = multi_part.ReadNextElement()) != null)
            {
                if (e.Filename == null)
                {
                    byte[] copy = new byte[e.Length];

                    input.Position = e.Start;
                    input.Read(copy, 0, (int)e.Length);

                    Form.Add(e.Name, this.request.ContentEncoding.GetString(copy));
                }
                else if(e.Length > 0)
                {
                    //
                    // We use a substream, as in 2.x we will support large uploads streamed to disk,
                    //
                    HttpPostedFile sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
                    Files.Add(e.Name, sub);
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Decode body stream
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Decoded data.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Something unexpected failed.</exception>
        /// <exception cref="ArgumentNullException"><c>stream</c> is <c>null</c>.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            //multipart/form-data, boundary=AaB03x
            string boundry = contentType.Parameters["boundary"];

            if (boundry == null)
            {
                throw new FormatException("Missing boundary in content type.");
            }

            var multipart = new HttpMultipart(stream, boundry, encoding);

            var form = new DecodedData();

            /*
             * FileStream stream1 = new FileStream("C:\\temp\\mimebody.tmp", FileMode.Create);
             * byte[] bytes = new byte[stream.Length];
             * stream.Read(bytes, 0, bytes.Length);
             * stream1.Write(bytes, 0, bytes.Length);
             * stream1.Flush();
             * stream1.Close();
             */

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

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

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

                    // Generate a filename
                    string originalFileName = element.Filename;
                    //string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
                    string internetCache = Utils.Instance.InternetCacheDir;

                    // 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);

                    var file = new HttpFile
                    {
                        Name             = element.Name,
                        OriginalFileName = originalFileName,
                        ContentType      = element.ContentType,
                        TempFileName     = element.Filename
                    };
                    form.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int)element.Length);

                    form.Parameters.Add(HttpUtility.UrlDecode(element.Name), encoding.GetString(buffer));
                }
            }

            return(form);
        }
Ejemplo n.º 25
0
        public void Should_limit_the_number_of_boundaries()
        {
            // Given
            var stream = BuildInputStream(null, StaticConfiguration.RequestQueryFormMultipartLimit + 10);
            var multipart = new HttpMultipart(stream, Boundary);

            // When
            var boundaries = multipart.GetBoundaries();

            // Then
            boundaries.Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Deserialize the content from the stream.
        /// </summary>
        /// <param name="contentType">Used to identify the object which is about to be deserialized. Specified by the <c>Serialize()</c> method when invoked in the other end point.</param>
        /// <param name="source">Stream that contains the object to deserialize.</param>
        /// <returns>Created object</returns>
        /// <exception cref="SerializationException">Deserialization failed</exception>
        public object Deserialize(string contentType, Stream source)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (!contentType.StartsWith(MimeType, StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var result = new FormAndFilesResult()
            {
                Form  = new ParameterCollection(),
                Files = new HttpFileCollection()
            };
            var contentTypeHeader = new HttpHeaderValue(contentType);
            var encodingStr       = contentTypeHeader.Parameters["charset"];
            var encoding          = encodingStr != null?Encoding.GetEncoding(encodingStr) : Encoding.UTF8;

            //multipart/form-data, boundary=AaB03x
            var boundary = contentTypeHeader.Parameters.Get("boundary");

            if (boundary == null)
            {
                throw new DecoderFailureException("Missing boundary in content type: " + contentType);
            }

            var multipart = new HttpMultipart(source, boundary.Value, encoding);

            HttpMultipart.Element element;

            while ((element = multipart.ReadNextElement()) != null)
            {
                if (string.IsNullOrEmpty(element.Name))
                {
                    throw new DecoderFailureException(string.Format("Missing value name.\nElement: {0}", element));
                }

                if (!string.IsNullOrEmpty(element.Filename))
                {
                    if (string.IsNullOrEmpty(element.ContentType))
                    {
                        throw new DecoderFailureException(string.Format("Value '{0}' lacks a content type.",
                                                                        element.Name));
                    }

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

                    // Generate a filename

                    var applicationData = Windows.Storage.ApplicationData.Current;
                    var temporaryFolder = applicationData.LocalCacheFolder;

                    var originalFileName = element.Filename;

                    // if the internet path doesn't exist, assume mono and /var/tmp
                    var path = string.IsNullOrEmpty(temporaryFolder.Path)
                        ? Path.Combine("var", "tmp")
                        : Path.Combine(temporaryFolder.Path.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);

                    var file = new HttpFile
                    {
                        Name             = element.Name,
                        OriginalFileName = originalFileName,
                        ContentType      = element.ContentType,
                        TempFileName     = element.Filename
                    };
                    result.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    source.Seek(element.Start, SeekOrigin.Begin);
                    source.Read(buffer, 0, (int)element.Length);

                    result.Form.Add(Uri.UnescapeDataString(element.Name), encoding.GetString(buffer));
                }
            }

            return(result);
        }
Ejemplo n.º 27
0
        public AuthenticationModule(IBootstrapInjection injection)
        {
            _authService = injection.Services.Authentication;

            #region utilities
            Get["JustdoIt"] = p =>
            {
                HelperService.RepairNames(injection);
                return("");
            };


            Get["Repair"] = p =>
            {
                var ms       = injection.Repositories.Match.GetAll();
                var toRelace = new List <Match>();
                var toEnter  = true;
                foreach (var m in ms)
                {
                    if (m.Id == "5bb4556acab1201a6c6c954a")
                    {
                        toEnter = false;
                    }
                    if (!toEnter)
                    {
                        toRelace.Add(m);
                    }
                    if (m.Id == "5bb48214cab1201a6c6c97c3")
                    {
                        break;
                    }
                }
                var i = 0;
                Parallel.ForEach(toRelace, m =>
                {
                    i++;
                    injection.Services.Match.UpdateMatch(m.PlayersTeamWinner, m.PlayersTeamLooser, "Barreto",
                                                         m.Id);
                });

                var parou = "";
                return("ok");
            };

            Get["MatchDate"] = p =>
            {
                var options = new ParallelOptions();
                options.MaxDegreeOfParallelism = 20;
                var regex = new System.Text.RegularExpressions.Regex(@"\d{4}:\d{2}:\d{2} \d{2}:\d{2}:\d{2}");
                Parallel.ForEach(
                    System.IO.Directory.GetFiles("C:\\temp\\match")
                    .ToList(), options, f =>
                {
                    try
                    {
                        var date = DateTime.ParseExact(regex.Match(System.IO.File.ReadAllText(f)).Value, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture);
                        var id   = new FileInfo(f).Name.Split('.')[0];
                        injection.Repositories.Match.Upsert(
                            Match.Factory.From(injection.Repositories.Match.GetById(id))
                            .WithDate(date)
                            .Instance);
                    }
                    catch (Exception)
                    {
                        var cagou = "";
                    }
                });



                return("ok");
            };

            #endregion
            Post[EndpointConfigurationEnum.LOGIN] = p =>
            {
                var    body = Request.Body.AsString();
                var    auth = JsonConvert.DeserializeObject <AuthDTO>(body);
                string id;
                if (_authService.AuthUser(auth.Username, auth.Password))
                {
                    id = _authService.GetUserIdByUsername(auth.Username);
                    Request.Cookies["logged"] = "true";
                }
                else
                {
                    return(HttpStatusCode.Unauthorized);
                }
                return(Response.AsJson(id, HttpStatusCode.Accepted));
            };



            Post[EndpointConfigurationEnum.REGISTER_USER] = p =>
            {
                try
                {
                    var userRegister = JsonConvert.DeserializeObject <UserRegisterDTO>(Request.Body.AsString());
                    _authService.RegisterUser(userRegister.Username, userRegister.Password, userRegister.Email);
                    return(HttpStatusCode.Created);
                }
                catch (UserAlreadyExistException ex)
                {
                    return("User already exist");
                }
                catch (Exception)
                {
                    return("whoooops.");
                }
            };


            Put[EndpointConfigurationEnum.GET_IMAGE_USER] = p =>
            {
                var contentTypeRegex = new System.Text.RegularExpressions.Regex("^multipart/form-data;\\s*boundary=(.*)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                var boundary         = contentTypeRegex.Match(Request.Headers.ContentType).Groups[1].Value;
                var multipart        = new HttpMultipart(this.Request.Body, boundary);
                var bodyStream       = multipart.GetBoundaries().First(b => b.Name == "image").Value;
                var teamId           = p.userId;
                _authService.SubmitUserImage(teamId, bodyStream);
                return(HttpStatusCode.OK);
            };

            Get[EndpointConfigurationEnum.GET_IMAGE_USER_BY_NICK] = p =>
            {
                try
                {
                    Stream imagem = _authService.GetImageFromNick(p.nickname);
                    if (imagem == null)
                    {
                        throw new ArgumentException("Não existe");
                    }
                    return(Response.FromStream(imagem, "image/jpg"));
                }
                catch (ArgumentException)
                {
                    return(HttpStatusCode.NotFound);
                }
                catch (Exception)
                {
                    return(HttpStatusCode.InternalServerError);
                }
            };

            Get[EndpointConfigurationEnum.GET_IMAGE_USER] = p =>
            {
                try
                {
                    Stream imagem = _authService.GetImage(p.userId);
                    if (imagem == null)
                    {
                        throw new ArgumentException("Não existe");
                    }
                    return(Response.FromStream(imagem, "image/jpg"));
                }
                catch (ArgumentException)
                {
                    return(HttpStatusCode.NotFound);
                }
                catch (Exception)
                {
                    return(HttpStatusCode.InternalServerError);
                }
            };

            Get["oi"] = p =>
            {
                return(Thread.CurrentThread.ManagedThreadId);
            };

            Get[EndpointConfigurationEnum.GET_NICKS_BY_ID] = p =>
            {
                string result = _authService.GetNicknameById(p.userId.ToString());
                return(Response.AsJson(result));
            };
        }