コード例 #1
0
        /// <summary>
        /// Creates a UrlMap resource in the specified project using the data included in the request.
        /// Documentation https://developers.google.com/compute/alpha/reference/urlMaps/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Compute service.</param>
        /// <param name="project">Project ID for this request.</param>
        /// <param name="body">A valid Compute alpha body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>OperationResponse</returns>
        public static Operation Insert(ComputeService service, string project, UrlMap body, UrlMapsInsertOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (project == null)
                {
                    throw new ArgumentNullException(project);
                }

                // Building the initial request.
                var request = service.UrlMaps.Insert(body, project);

                // Applying optional parameters to the request.
                request = (UrlMapsResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request UrlMaps.Insert failed.", ex);
            }
        }
コード例 #2
0
 public string GetCode([FromBody] string url)
 {
     if (!string.IsNullOrEmpty(url))
     {
         string code      = RandomHelper.GetURL();
         var    oldUrlMap = _db.UrlMaps.Where(p => p.Url == url || p.Code == code).ToList();
         if (oldUrlMap != null && oldUrlMap.Count > 0)
         {
             if (oldUrlMap.Any(p => p.Url == url))
             {
                 code = oldUrlMap.Where(p => p.Url == url).Select(p => p.Code).FirstOrDefault();
                 return(code);
             }
             else
             {
                 code = GetUniqueCode(RandomHelper.GetURL());
             }
         }
         UrlMap urlMap = new UrlMap
         {
             Code         = code,
             CreatedOn    = DateTime.Now,
             Id           = Guid.NewGuid(),
             Url          = url,
             VisitorCount = 0
         };
         _db.UrlMaps.Add(urlMap);
         _db.SaveChanges();
         return(code);
     }
     else
     {
         return("");
     }
 }
コード例 #3
0
        public void Should_Be_Nestable()
        {
            var map = new UrlMap(new Dictionary <string, object> {
                { "/foo",
                  new UrlMap(new Dictionary <string, object> {
                        { "/bar",
                          new UrlMap(new Dictionary <string, object> {
                                { "/quux",
                                  DetachedApplication.Create(env =>
                                                             new dynamic[] { 200, new Hash
                                                                             {
                                                                                 { "Content-Type", "text/plain" },
                                                                                 { "X-Position", "/foo/bar/quux" },
                                                                                 { "X-PathInfo", env["PATH_INFO"] },
                                                                                 { "X-ScriptName", env["SCRIPT_NAME"] }
                                                                             }, string.Empty }) }
                            }) }
                    }) }
            });

            var res = new MockRequest(map).Get("/foo/bar");

            Assert.AreEqual(404, res.Status);

            res = new MockRequest(map).Get("/foo/bar/quux");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/foo/bar/quux", res["X-Position"]);
            Assert.AreEqual(string.Empty, res["X-PathInfo"]);
            Assert.AreEqual("/foo/bar/quux", res["X-ScriptName"]);
        }
コード例 #4
0
        /// <summary>
        /// Creates a UrlMap resource in the specified project using the data included in the request.
        /// Documentation https://developers.google.com/compute/v1/reference/urlMaps/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated compute service.</param>
        /// <param name="project">Project ID for this request.</param>
        /// <param name="body">A valid compute v1 body.</param>
        /// <returns>OperationResponse</returns>
        public static Operation Insert(computeService service, string project, UrlMap body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (project == null)
                {
                    throw new ArgumentNullException(project);
                }

                // Make the request.
                return(service.UrlMaps.Insert(body, project).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request UrlMaps.Insert failed.", ex);
            }
        }
コード例 #5
0
        /// <summary>Snippet for UpdateAsync</summary>
        public async Task UpdateAsync()
        {
            // Snippet: UpdateAsync(string, string, string, UrlMap, CallSettings)
            // Additional: UpdateAsync(string, string, string, UrlMap, CancellationToken)
            // Create client
            RegionUrlMapsClient regionUrlMapsClient = await RegionUrlMapsClient.CreateAsync();

            // Initialize request argument(s)
            string project        = "";
            string region         = "";
            string urlMap         = "";
            UrlMap urlMapResource = new UrlMap();
            // Make the request
            lro::Operation <Operation, Operation> response = await regionUrlMapsClient.UpdateAsync(project, region, urlMap, urlMapResource);

            // Poll until the returned long-running operation is complete
            lro::Operation <Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation <Operation, Operation> retrievedResponse = await regionUrlMapsClient.PollOnceUpdateAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
コード例 #6
0
        public void Intercept(IInvocation invocation)
        {
            logger.LogInformation("发起远程调用...");
            var returnValue = httpClientInvoker.Call(UrlMap.GetValueOrDefault(invocation.Method.DeclaringType), invocation.Method, invocation.Arguments);

            invocation.ReturnValue = returnValue;
            logger.LogInformation("远程调用结束...");
        }
コード例 #7
0
        public async Task CreateMap(UrlMap map)
        {
            if (map == null)
            {
                throw new ArgumentNullException(nameof(map));
            }

            await _context.UrlMaps.AddAsync(map);
        }
コード例 #8
0
        public void Should_Dispatch_Hosts_Correctly()
        {
            var mapping = new KeyValuePair <string, object> [4];

            mapping[0] = GetMapForDispatchTest("http://foo.org/", "foo.org");
            mapping[1] = GetMapForDispatchTest("http://subdomain.foo.org/", "subdomain.foo.org");
            mapping[2] = GetMapForDispatchTest("http://bar.org/", "bar.org");
            mapping[3] = GetMapForDispatchTest("/", "default.org");

            var mappingDictionary = mapping.ToDictionary(pair => pair.Key, pair => pair.Value);

            var map = new UrlMap(mappingDictionary);

            var res = new MockRequest(map).Get("/");

            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("default.org", res["X-Position"]);

            res = new MockRequest(map).Get("/", new Dictionary <string, object> {
                { "HTTP_HOST", "bar.org" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("bar.org", res["X-Position"]);

            res = new MockRequest(map).Get("/", new Dictionary <string, object> {
                { "HTTP_HOST", "foo.org" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("foo.org", res["X-Position"]);

            res = new MockRequest(map).Get("/",
                                           new Dictionary <string, object> {
                { "HTTP_HOST", "subdomain.foo.org" }, { "SERVER_NAME", "foo.org" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("subdomain.foo.org", res["X-Position"]);

            res = new MockRequest(map).Get("http://foo.org/");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("foo.org", res["X-Position"]);

            res = new MockRequest(map).Get("/", new Dictionary <string, object> {
                { "HTTP_HOST", "example.org" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("default.org", res["X-Position"]);

            res = new MockRequest(map).Get("/",
                                           new Dictionary <string, object> {
                { "HTTP_HOST", "example.org:9292" }, { "SERVER_PORT", "9292" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("default.org", res["X-Position"]);
        }
コード例 #9
0
 /// <summary>Snippet for Get</summary>
 public void Get()
 {
     // Snippet: Get(string, string, CallSettings)
     // Create client
     UrlMapsClient urlMapsClient = UrlMapsClient.Create();
     // Initialize request argument(s)
     string project = "";
     string urlMap  = "";
     // Make the request
     UrlMap response = urlMapsClient.Get(project, urlMap);
     // End snippet
 }
コード例 #10
0
 /// <summary>Snippet for Insert</summary>
 public void Insert()
 {
     // Snippet: Insert(string, UrlMap, CallSettings)
     // Create client
     UrlMapsClient urlMapsClient = UrlMapsClient.Create();
     // Initialize request argument(s)
     string project        = "";
     UrlMap urlMapResource = new UrlMap();
     // Make the request
     Operation response = urlMapsClient.Insert(project, urlMapResource);
     // End snippet
 }
コード例 #11
0
        public async Task <ActionResult <UrlMapReadDto> > CreateUrlMap(UrlMapCreateDto urlMapCreateDto)
        {
            // Extract Id from JWT token
            var accountId = Int32.Parse(User.FindFirst(ClaimTypes.Name)?.Value);

            // Generate a 8 character key to be used as a shortened url
            var shortUrlGen = KeyGenerator.GetUniqueKey(8);

            if (urlMapCreateDto.redirectType != 301 &&
                urlMapCreateDto.redirectType != 302 &&
                urlMapCreateDto.redirectType != 0)
            {
                return(BadRequest(new { message = "Invalid redirect type provided." }));
            }

            // Check if the same map already exists in the database
            if (await _repository.UrlMapExists(accountId, urlMapCreateDto.url))
            {
                return(Conflict(new { message = "Url map with the same configuration already exists." }));
            }

            // If there is a conflick on short url return 500
            if (await _repository.ShortUrlExists(shortUrlGen))
            {
                return(StatusCode(500, new { message = "Short url with the same generated name already exists. Please try again." }));
            }

            var response = new UrlMapReadDto()
            {
                shortUrl = $"{Request.Scheme}://{Request.Host}/{shortUrlGen}"
            };

            var map = new UrlMap()
            {
                Url          = urlMapCreateDto.url,
                ShortUrl     = shortUrlGen,
                RedirectType = (urlMapCreateDto.redirectType == 0) ? 302 : urlMapCreateDto.redirectType,
                AccountId    = accountId
            };

            try
            {
                await _repository.CreateMap(map);

                await _repository.SaveChanges();
            }
            catch (System.Exception)
            {
                return(StatusCode(500, new { message = "Unexpected server error has occured." }));
            }

            return(Ok(response));
        }
コード例 #12
0
        public void PaginaControladoraDeveEstarMapeada()
        {
            UrlMap     obj     = UrlMap.Instance;
            UrlMapItem objITEM = obj.Itens.Find(i => i.Key == Map.FrontController.Controller);

            Assert.IsNotNull(objITEM);

            Assert.IsTrue(Checar.MaiorouIgual(objITEM.ID));
            Assert.IsNotNullOrEmpty(objITEM.Key);
            Assert.IsNotNullOrEmpty(objITEM.Url);
            //Assert.IsNotNullOrEmpty(objITEM.Titulo);
            Assert.IsTrue(objITEM.Ocultar);
        }
コード例 #13
0
 /// <summary>Snippet for Update</summary>
 public void Update()
 {
     // Snippet: Update(string, string, string, UrlMap, CallSettings)
     // Create client
     RegionUrlMapsClient regionUrlMapsClient = RegionUrlMapsClient.Create();
     // Initialize request argument(s)
     string project        = "";
     string region         = "";
     string urlMap         = "";
     UrlMap urlMapResource = new UrlMap();
     // Make the request
     Operation response = regionUrlMapsClient.Update(project, region, urlMap, urlMapResource);
     // End snippet
 }
コード例 #14
0
        /// <summary>Snippet for InsertAsync</summary>
        public async Task InsertAsync()
        {
            // Snippet: InsertAsync(string, UrlMap, CallSettings)
            // Additional: InsertAsync(string, UrlMap, CancellationToken)
            // Create client
            UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync();

            // Initialize request argument(s)
            string project        = "";
            UrlMap urlMapResource = new UrlMap();
            // Make the request
            Operation response = await urlMapsClient.InsertAsync(project, urlMapResource);

            // End snippet
        }
コード例 #15
0
 /// <summary>Snippet for Get</summary>
 public void GetRequestObject()
 {
     // Snippet: Get(GetUrlMapRequest, CallSettings)
     // Create client
     UrlMapsClient urlMapsClient = UrlMapsClient.Create();
     // Initialize request argument(s)
     GetUrlMapRequest request = new GetUrlMapRequest
     {
         Project = "",
         UrlMap  = "",
     };
     // Make the request
     UrlMap response = urlMapsClient.Get(request);
     // End snippet
 }
コード例 #16
0
        /// <summary>Snippet for GetAsync</summary>
        public async Task GetAsync()
        {
            // Snippet: GetAsync(string, string, CallSettings)
            // Additional: GetAsync(string, string, CancellationToken)
            // Create client
            UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync();

            // Initialize request argument(s)
            string project = "";
            string urlMap  = "";
            // Make the request
            UrlMap response = await urlMapsClient.GetAsync(project, urlMap);

            // End snippet
        }
コード例 #17
0
        public UrlMap Add(UrlMap urlMap)
        {
            try
            {
                var newUrlMap = UrlMap.Add(urlMap);

                this.SaveChanges();

                return(newUrlMap);
            }
            catch (Exception)
            {
                // todo: log, then rethrow (caller must expect and handle errors from repo)
                return(null);
            }
        }
コード例 #18
0
ファイル: UrlMapOutput.cs プロジェクト: sabbiryan/url-shorten
        public UrlMapOutput(UrlMap model)
        {
            Id           = model.Id;
            Identity     = model.Identity;
            Title        = model.Title;
            Description  = model.Description;
            ShortenUrl   = model.ShortenUrl;
            RawUrl       = model.RawUrl;
            HitCount     = model.HitCount;
            CreationTime = model.CreationTime;
            IsDeleted    = model.IsDeleted;

            if (model.HitLogs != null)
            {
                HitLogs = model.HitLogs.ToList().ConvertAll(x => new HitLogOutput(x));
            }
        }
コード例 #19
0
        /// <summary>Snippet for UpdateAsync</summary>
        public async Task UpdateAsync()
        {
            // Snippet: UpdateAsync(string, string, string, UrlMap, CallSettings)
            // Additional: UpdateAsync(string, string, string, UrlMap, CancellationToken)
            // Create client
            RegionUrlMapsClient regionUrlMapsClient = await RegionUrlMapsClient.CreateAsync();

            // Initialize request argument(s)
            string project        = "";
            string region         = "";
            string urlMap         = "";
            UrlMap urlMapResource = new UrlMap();
            // Make the request
            Operation response = await regionUrlMapsClient.UpdateAsync(project, region, urlMap, urlMapResource);

            // End snippet
        }
コード例 #20
0
        /// <summary>Snippet for GetAsync</summary>
        public async Task GetRequestObjectAsync()
        {
            // Snippet: GetAsync(GetUrlMapRequest, CallSettings)
            // Additional: GetAsync(GetUrlMapRequest, CancellationToken)
            // Create client
            UrlMapsClient urlMapsClient = await UrlMapsClient.CreateAsync();

            // Initialize request argument(s)
            GetUrlMapRequest request = new GetUrlMapRequest
            {
                Project = "",
                UrlMap  = "",
            };
            // Make the request
            UrlMap response = await urlMapsClient.GetAsync(request);

            // End snippet
        }
コード例 #21
0
        private void RemoveFromMaps(ILiaraFormatter item)
        {
            if (item.GetType().IsSubclassOf(typeof(LiaraFormatter)))
            {
                var fm = (LiaraFormatter)item;
                foreach (var supportedMediaType in fm.SupportedMediaTypes)
                {
                    MediaMap.RemoveValue(supportedMediaType.ToString().ToLower(), item);
                }

                foreach (var supportedUrlExtension in fm.SupportedUrlExtensions)
                {
                    UrlMap.RemoveValue(
                        supportedUrlExtension.ToLower(),
                        item);
                }
            }
        }
コード例 #22
0
        public void Should_Not_Squeeze_Slashes()
        {
            var mapping = new KeyValuePair <string, object> [2];

            mapping[0] = GetMapForRootRouteTest("/", "root");
            mapping[1] = GetMapForRootRouteTest("/foo", "foo");

            var mappingDictionary = mapping.ToDictionary(pair => pair.Key, pair => pair.Value);

            var map = new UrlMap(mappingDictionary);

            var mock = new MockRequest(map);

            var res = mock.Get("/http://example.org/bar");

            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("root", res["X-Position"]);
            Assert.AreEqual("/http://example.org/bar", res["X-PathInfo"]);
            Assert.AreEqual(string.Empty, res["X-ScriptName"]);
        }
コード例 #23
0
        public async stt::Task GetRequestObjectAsync()
        {
            moq::Mock <RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock <RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetRegionUrlMapRequest request = new GetRegionUrlMapRequest
            {
                Region  = "regionedb20d96",
                Project = "projectaa6ff846",
                UrlMap  = "url_map3ccdbf57",
            };
            UrlMap expectedResponse = new UrlMap
            {
                Id   = 11672635353343658936UL,
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                CreationTimestamp  = "creation_timestamp235e59a1",
                Tests              = { new UrlMapTest(), },
                Region             = "regionedb20d96",
                Fingerprint        = "fingerprint009e6052",
                PathMatchers       = { new PathMatcher(), },
                HostRules          = { new HostRule(), },
                HeaderAction       = new HttpHeaderAction(),
                DefaultUrlRedirect = new HttpRedirectAction(),
                DefaultService     = "default_serviceb867731a",
                DefaultRouteAction = new HttpRouteAction(),
                Description        = "description2cf9da67",
                SelfLink           = "self_link7e87f12d",
            };

            mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <UrlMap>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            RegionUrlMapsClient client  = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null);
            UrlMap responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            UrlMap responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
コード例 #24
0
        public UrlMapDetailOutput(UrlMap model)
        {
            Id          = model.Id;
            Identity    = model.Identity;
            Title       = model.Title;
            Description = model.Description;
            ShortenUrl  = model.ShortenUrl;
            RawUrl      = model.RawUrl;
            HitCount    = model.HitCount;

            CreationTime     = model.CreationTime;
            ModificationTime = model.ModificationTime;
            IsDeleted        = model.IsDeleted;
            DeletionTime     = model.DeletionTime;
            IpAddress        = model.IpAddress;
            DeviceInfo       = model.DeviceInfo;

            if (model.HitLogs != null)
            {
                HitLogs = model.HitLogs.ToList().ConvertAll(x => new HitLogOutput(x));
            }
        }
コード例 #25
0
        public void Get()
        {
            moq::Mock <UrlMaps.UrlMapsClient> mockGrpcClient = new moq::Mock <UrlMaps.UrlMapsClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetUrlMapRequest request = new GetUrlMapRequest
            {
                Project = "projectaa6ff846",
                UrlMap  = "url_map3ccdbf57",
            };
            UrlMap expectedResponse = new UrlMap
            {
                Id   = 11672635353343658936UL,
                Kind = "kindf7aa39d9",
                Name = "name1c9368b0",
                CreationTimestamp  = "creation_timestamp235e59a1",
                Tests              = { new UrlMapTest(), },
                Region             = "regionedb20d96",
                Fingerprint        = "fingerprint009e6052",
                PathMatchers       = { new PathMatcher(), },
                HostRules          = { new HostRule(), },
                HeaderAction       = new HttpHeaderAction(),
                DefaultUrlRedirect = new HttpRedirectAction(),
                DefaultService     = "default_serviceb867731a",
                DefaultRouteAction = new HttpRouteAction(),
                Description        = "description2cf9da67",
                SelfLink           = "self_link7e87f12d",
            };

            mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            UrlMapsClient client   = new UrlMapsClientImpl(mockGrpcClient.Object, null);
            UrlMap        response = client.Get(request.Project, request.UrlMap);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
コード例 #26
0
        public ActionResult Index(PageViewModel vm)
        {
            List <int> alltime = new List <int>();
            UrlMap     urlmap  = new UrlMap
            {
                Url = vm.url
            };

            db.UrlMaps.Add(urlmap);
            db.SaveChanges();

            Uri    uri    = new Uri(vm.url);
            string urlxml = uri.Scheme + "://" + uri.Host + "/sitemap.xml";

            IEnumerable <string> XmlMap = XmlReadMap(urlxml);

            if (XmlMap == null)

            {
                string data = GetHtmlPageText(vm.url);

                string pattern = "<a href=\"(.*?)\">";

                Regex           regex   = new Regex(pattern);
                MatchCollection matches = regex.Matches(data);

                foreach (Match matche in matches)
                {
                    string[] words = matche.Value.Split('"');
                    string[] check = vm.url.Split('/');
                    if (check.Length > 1)
                    {
                        if ((words[1].StartsWith("http") && (words[1].Contains(check[3]))) || (words[1].StartsWith("http") && (words[1].Contains(check[2]))) || (words[1].StartsWith("/") && !(words[1].EndsWith("."))))
                        {
                            Map smap = new Map()
                            {
                                SiteMap = words[1],

                                UrlMapId = urlmap.id
                            };

                            if (words[1].StartsWith("http"))
                            {
                                int time = PageResponce(words[1]);
                                smap.Time = time;
                            }
                            if (words[1].StartsWith("/"))
                            {
                                int time = PageResponce(vm.url + words[1]);
                                smap.Time = time;
                            }
                            alltime.Add(smap.Time);



                            db.Maps.Add(smap);
                            db.SaveChanges();
                        }
                    }
                }
            }
            else
            {
                foreach (var item in XmlMap)
                {
                    Map smap = new Map()
                    {
                        SiteMap = item,

                        UrlMapId = urlmap.id
                    };
                    int time = PageResponce(item);
                    smap.Time = time;
                    alltime.Add(smap.Time);
                    db.Maps.Add(smap);
                    db.SaveChanges();
                }
            }


            Time seconds = new Time
            {
                MaxTime  = alltime.Max(),
                MinTime  = alltime.Min(),
                UrlMapId = urlmap.id
            };
            Quality quality = new Quality
            {
                Assessment = true,
                UrlMapId   = urlmap.id
            };

            db.Times.Add(seconds);
            db.Qualities.Add(quality);
            db.SaveChanges();

            PageViewModel pv = new PageViewModel
            {
                UrlMaps   = db.UrlMaps.ToList(),
                Maps      = db.Maps.ToList(),
                Times     = db.Times.ToList(),
                Qualities = db.Qualities.ToList()
            };

            pv.Maps = db.Maps.OrderByDescending(x => x.Time);


            return(View(pv));
        }
コード例 #27
0
        public void Should_Dispatch_Paths_Correctly()
        {
            var app = DetachedApplication.Create
                          (env =>
                          new dynamic[] { 200,
                                          new Hash
                                          {
                                              { "X-ScriptName", env["SCRIPT_NAME"] },
                                              { "X-PathInfo", env["PATH_INFO"] },
                                              { "Content-Type", "text/plain" }
                                          },
                                          string.Empty });

            var map = new UrlMap(new Dictionary <string, object>
            {
                { "http://foo.org/bar", app },
                { "/foo", app },
                { "/foo/bar", app }
            });

            var res = new MockRequest(map).Get("/");

            Assert.AreEqual(404, res.Status);

            res = new MockRequest(map).Get("/qux");
            Assert.AreEqual(404, res.Status);

            res = new MockRequest(map).Get("/foo");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/foo", res["X-ScriptName"]);
            Assert.AreEqual(string.Empty, res["X-PathInfo"]);

            res = new MockRequest(map).Get("/foo/");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/foo", res["X-ScriptName"]);
            Assert.AreEqual("/", res["X-PathInfo"]);

            res = new MockRequest(map).Get("/foo/bar");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/foo/bar", res["X-ScriptName"]);
            Assert.AreEqual(string.Empty, res["X-PathInfo"]);

            res = new MockRequest(map).Get("/foo/bar/");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/foo/bar", res["X-ScriptName"]);
            Assert.AreEqual("/", res["X-PathInfo"]);

            res = new MockRequest(map).Get("/foo///bar//quux");
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/foo/bar", res["X-ScriptName"]);
            Assert.AreEqual("//quux", res["X-PathInfo"]);

            res = new MockRequest(map).Get("/foo/quux", new Dictionary <string, object> {
                { "SCRIPT_NAME", "/bleh" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/bleh/foo", res["X-ScriptName"]);
            Assert.AreEqual("/quux", res["X-PathInfo"]);

            res = new MockRequest(map).Get("/bar", new Dictionary <string, object> {
                { "HTTP_HOST", "foo.org" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/bar", res["X-ScriptName"]);
            Assert.AreEqual(string.Empty, res["X-PathInfo"]);

            res = new MockRequest(map).Get("/bar/", new Dictionary <string, object> {
                { "HTTP_HOST", "foo.org" }
            });
            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("/bar", res["X-ScriptName"]);
            Assert.AreEqual("/", res["X-PathInfo"]);
        }