public void should_keep_original_names()
        {
            //Given
            var headerOne = new Parameter
            {
                Description = "My description",
                DisplayName = "my Display name",
                Required    = true,
                Type        = "string",
                Repeat      = false,
                Example     = "An example"
            };
            var headerTwo = new Parameter
            {
                Description = "My description 2",
                DisplayName = "my-display-Name_2",
                Required    = false,
                Type        = "string",
                Repeat      = true,
                Example     = "Another example"
            };

            var headers = new[] { headerOne, headerTwo };

            var parsedParameters = HeadersParser.ConvertHeadersToProperties(headers);

            Assert.AreEqual("my Display name", parsedParameters.First(p => p.Name == "MyDisplayname").OriginalName);
            Assert.AreEqual("my-display-Name_2", parsedParameters.First(p => p.Name == "Mydisplayname_2").OriginalName);
        }
Example #2
0
 private void GetHeaders(string objectName, Method method, ClientGeneratorMethod generatedMethod)
 {
     if (method.Headers != null && method.Headers.Any())
     {
         var headerObject = HeadersParser.GetHeadersObject(generatedMethod, method, objectName);
         generatedMethod.Header = headerObject;
         headerObjects.Add(headerObject.Name, headerObject);
     }
 }
Example #3
0
        public void should_parse_headers()
        {
            //Given
            var headerOne = new Parameter
            {
                Description = "My description",
                DisplayName = "My display name",
                Required    = true,
                Type        = "string",
                Repeat      = false,
                Example     = "An example"
            };
            var headerTwo = new Parameter
            {
                Description = "My description 2",
                DisplayName = "My display name 2",
                Required    = false,
                Type        = "string",
                Repeat      = true,
                Example     = "Another example"
            };

            var headers = new Dictionary <string, Parameter> {
                { "one", headerOne }, { "two", headerTwo }
            };

            //When
            var parsedParameters = HeadersParser.ConvertHeadersToProperties(headers);

            //Then
            Assert.AreEqual(headers.Count(), parsedParameters.Count, "The number of headers returned do not match with the number of headers sent");

            Assert.DoesNotThrow(
                () => parsedParameters.First(x => x.Type == headerOne.Type &&
                                             x.Description == headerOne.Description &&
                                             x.Example == headerOne.Example &&
                                             x.Required == headerOne.Required &&
                                             x.Name.Equals(headers.First().Key, StringComparison.InvariantCultureIgnoreCase)),
                "There should be one header with all the same properties as the original header");

            Assert.DoesNotThrow(
                () => parsedParameters.First(x => x.Type == headerTwo.Type &&
                                             x.Description == headerTwo.Description &&
                                             x.Example == headerTwo.Example &&
                                             x.Required == headerTwo.Required &&
                                             x.Name.Equals(headers.Last().Key, StringComparison.InvariantCultureIgnoreCase)),
                "There should be one header with all the same properties as the original header");
        }
Example #4
0
        public void ParseHeaders_TestData_ReturnsValidHeaders()
        {
            string testInput = "HEADER1:VALUE1\r\n" +
                               "header2 : VALUE2\r\n" +
                               "hEADER3: VALUE3\r\n" +
                               "badHeader\r\n";

            byte[] testBytes    = Encoding.ASCII.GetBytes(testInput);
            var    ms           = new MemoryStream(testBytes);
            var    streamReader = new StreamReader(ms, Encoding.ASCII);

            NameValueCollection headers = HeadersParser.ParseHeaders(streamReader);

            Assert.AreEqual(3, headers.Count);
            Assert.AreEqual("VALUE1", headers["HEADER1"]);
            Assert.AreEqual("VALUE2", headers["HEADER2"]);
            Assert.AreEqual("VALUE3", headers["HEADER3"]);
        }
Example #5
0
        private void GetResponseHeaders(string objectName, ClientGeneratorMethod generatedMethod, Method method)
        {
            generatedMethod.ResponseHeaders = new Dictionary <HttpStatusCode, ApiObject>();
            foreach (var resp in method.Responses.Where(r => r.Headers != null && r.Headers.Any()))
            {
                var headerObject = HeadersParser.GetHeadersObject(generatedMethod, resp, objectName);
                generatedMethod.ResponseHeaders.Add(ParserHelpers.GetHttpStatusCode(resp.Code), headerObject);
                responseHeadersObjects.Add(headerObject.Name, headerObject);
            }

            if (!generatedMethod.ResponseHeaders.Any())
            {
                generatedMethod.ResponseHeaderType = defaultHeaderType;
            }
            else if (generatedMethod.ResponseHeaders.Count == 1)
            {
                generatedMethod.ResponseHeaderType = ClientGeneratorMethod.ModelsNamespacePrefix + generatedMethod.ResponseHeaders.First().Value.Name;
            }
            else
            {
                CreateMultipleType(generatedMethod);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            // Accepting user request

            // reading the query
            var fileNameQuery = context.Request.QueryString["file"];

            // validating the request
            if (string.IsNullOrEmpty(fileNameQuery))
            {
                InvalidRequest(context, "Invalid request! Specify file name in url e.g.: ResumableDownload.ashx?file=sample.zip");
                return;
            }

            // the physical file address path
            var fileName = context.Server.MapPath(fileNameQuery);

            if (!File.Exists(fileName))
            {
                InvalidRequest(context, "File does not exists!");
                return;
            }

            // reading file info
            var fileInfo   = new FileInfo(fileName);
            var fileLength = fileInfo.Length;

            // Download information class
            var downloadInfo = new DownloadDataInfo(fileName);

            // Reading request download range
            var requestedRanges = HeadersParser.ParseHttpRequestHeaderMultipleRange(context.Request, fileLength);

            // apply the ranges to the download info
            downloadInfo.InitializeRanges(requestedRanges);

            string etagMatched;
            int    outcomeStausCode = 200;

            // validating the ranges specified
            if (!HeadersParser.ValidatePartialRequest(context.Request, downloadInfo, out etagMatched, ref outcomeStausCode))
            {
                // the request is invalid, this is the invalid code
                context.Response.StatusCode = outcomeStausCode;

                // show to the client what is the real ETag
                if (!string.IsNullOrEmpty(etagMatched))
                {
                    context.Response.AppendHeader("ETag", etagMatched);
                }

                // stop the preoccess
                // but don't hassle with error messages
                return;
            }

            // user ID, or IP or anything you use to identify the user
            var userIP = context.Request.UserHostAddress;

            // limiting the download speed manager and the speed limit
            UserSpeedLimitManager.StartNewDownload(downloadInfo, userIP, DownloadLimit);

            // It is very important to destory the DownloadProcess object
            // Here the using block does it for us.
            using (var process = new DownloadProcess(downloadInfo))
            {
                // start the download
                var state = process.ProcessDownload(context.Response);

                // checking the state of the download
                if (state == DownloadProcess.DownloadProcessState.PartFinished)
                {
                    // all parts of download are finish, do something here!
                }
            }
        }
Example #7
0
 /// <summary>
 /// Automatically loads the data from the RC file
 /// </summary>
 /// <param name="aRcFile"></param>
 public StringResourceContext(RcFile aRcFile)
 {
     mHeaderParser = new HeadersParser(mHeaderContent);
     LoadStringResources(aRcFile);
     mIdGenerator = new IdGenerator(mEmptyRangeManager.GetEmptyRanges, mRcFileContent.MaximumId);
 }
Example #8
0
        /// <summary>
        /// Executes the CGI executable with the specified arguments
        /// </summary>
        /// <param name="fileName">The file to execute</param>
        /// <param name="queryString">The query string to pass</param>
        /// <param name="method">The HTTP method to use</param>
        /// <param name="contentData">Additional data</param>
        /// <returns></returns>
        public CGIResult Execute(string fileName, string queryString, HttpMethod method, string contentData = "")
        {
            string           result = "";
            Process          p      = new Process();
            ProcessStartInfo psi    = new ProcessStartInfo(Command);

            psi.UseShellExecute                  = false;
            psi.RedirectStandardError            = true;
            psi.RedirectStandardInput            = true;
            psi.RedirectStandardOutput           = true;
            psi.WindowStyle                      = ProcessWindowStyle.Hidden;
            psi.CreateNoWindow                   = true;
            psi.Environment["REDIRECT_STATUS"]   = "true";
            psi.Environment["GATEWAY_INTERFACE"] = "CGI/1.1";
            psi.Environment["SCRIPT_FILENAME"]   = fileName;
            psi.Environment["SERVER_SOFTWARE"]   = "fasthttps/1.0";
            switch (method)
            {//TODO implement post and other methods
            case HttpMethod.GET:
                psi.Environment["REQUEST_METHOD"] = "GET";
                break;
            }
            psi.Environment["QUERY_STRING"]   = queryString;
            psi.Environment["CONTENT_LENGTH"] = "0";
            p.StartInfo = psi;
            p.Start();
            int bytesRead = 0;

            char[]        buffer = new char[1024]; //1K buffer
            StringBuilder stdout = new StringBuilder();

            while ((bytesRead = p.StandardOutput.Read(buffer, 0, buffer.Length)) != 0)
            {
                if (bytesRead != buffer.Length)
                {
                    for (int i = 0; i < bytesRead; i++)
                    {
                        stdout.Append(buffer[i]);
                    }
                }
                else
                {
                    stdout.Append(buffer);
                }
            }
            p.WaitForExit(maxTimeout);
            var  document      = stdout.ToString();
            var  documentLines = document.Split('\n');
            bool headersFound  = false;
            var  headers       = "";

            for (int i = 0; i < documentLines.Length; i++)
            {
                string line = documentLines[i];
                if (!headersFound)
                {
                    if (line.Trim() == "")
                    {
                        headersFound = true;
                    }
                    headers += line + "\n";
                    continue;
                }
                else
                {
                    result += line + "\n";
                }
            }
            p.Dispose();
            //TODO [Completed] extract headers and feed them to web server
            return(new CGIResult {
                Headers = HeadersParser.Parse(headers), OutDocument = result
            });
        }
        public void ProcessRequest(HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            // Accepting user request
            var idStr = request.QueryString["id"];

            try
            {
                int id;
                if (!int.TryParse(idStr, out id))
                {
                    InvalidRequest(context, "Invalid request!");
                    return;
                }
                UploadedFile uploadedFile;
                using (var db = new UploadDb())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;
                    db.Configuration.ProxyCreationEnabled     = false;

                    var file = db.Files.FirstOrDefault(a => a.UploadedFileID == id);
                    if (file == null)
                    {
                        InvalidRequest(context, "File does not exists!");
                        response.StatusCode = 404;
                        return;
                    }
                    uploadedFile = file;
                }

                //SiteException.LogException(new Exception(
                //	string.Format("UploadedFileID:{0}, IsPublic:{1}, UploadDate:{2}, Filename:{3}",
                //		uploadedFile.UploadedFileID,
                //		uploadedFile.IsPublic,
                //		uploadedFile.UploadDate,
                //		uploadedFile.Filename)));

                if (uploadedFile.IsPublic == false)
                {
                    // check the owner
                    var user = UserManager.GetUser();
                    if (user == null)
                    {
                        var succeed = UserManager.BasicAuthorize(context);
                        if (!succeed)
                        {
                            return;
                        }
                        user = UserManager.GetUser();
                    }

                    // not the file owner!
                    if (user == null || user.UserID != uploadedFile.UserId)
                    {
                        context.Response.Clear();
                        context.Response.Write("You do not have access to download this file!");
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        context.Response.Flush();
                        context.Response.End();
                        return;
                    }
                }

                // file path
                var fileName = UploadedFileManager.MapToPhysicalPath(uploadedFile);

                // reading file info
                var fileInfo   = new FileInfo(fileName);
                var fileLength = fileInfo.Length;

                // Download information class
                using (var downloadInfo = new DownloadDataInfo(fileName))
                {
                    downloadInfo.DisplayFileName = UploadedFileManager.GetUrlFileName(uploadedFile);

                    // Reading request download range
                    var requestedRanges = HeadersParser.ParseHttpRequestHeaderMultipleRange(context.Request, fileLength);

                    // apply the ranges to the download info
                    downloadInfo.InitializeRanges(requestedRanges);

                    string etagMatched;
                    int    outcomeStausCode = 200;

                    // validating the ranges specified
                    if (!HeadersParser.ValidatePartialRequest(context.Request, downloadInfo, out etagMatched, ref outcomeStausCode))
                    {
                        // the request is invalid, this is the invalid code
                        context.Response.StatusCode = outcomeStausCode;

                        // show to the client what is the real ETag
                        if (!string.IsNullOrEmpty(etagMatched))
                        {
                            context.Response.AppendHeader("ETag", etagMatched);
                        }

                        // stop the preoccess
                        // but don't hassle with error messages
                        return;
                    }

                    // user ID, or IP or anything you use to identify the user
                    //var userIP = context.Request.UserHostAddress;

                    // Option 1: limiting the download speed for this file for this user!
                    //UserSpeedLimitManager.StartNewDownload(downloadInfo, userIP, DownloadLimit);

                    // Option 2: Limiting only this connection
                    downloadInfo.LimitTransferSpeed(DownloadLimit);

                    // It is very important to destory the DownloadProcess object
                    // Here the using block does it for us.
                    using (var process = new DownloadProcess(downloadInfo))
                    {
                        var state = DownloadProcess.DownloadProcessState.None;
                        try
                        {
                            // start the download
                            state = process.ProcessDownload(context.Response);
                        }
                        catch (HttpException)
                        {
                            // preventing:
                            // System.Web.HttpException (0x800703E3): The remote host closed the connection. The error code is 0x800703E3.
                        }

                        // checking the state of the download
                        if (state == DownloadProcess.DownloadProcessState.LastPartfinished)
                        {
                            // all parts of download are finish, do something here!
                            using (var db = new UploadDb())
                            {
                                var dbFile = db.Files.FirstOrDefault(a => a.UploadedFileID == uploadedFile.UploadedFileID);
                                if (dbFile != null)
                                {
                                    dbFile.Downloaded++;
                                    dbFile.LastDownload = DateTime.Now.ToUniversalTime();
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SiteException.LogException(ex, "ID: " + idStr);
                throw;
            }
        }