// Constructor.
	public ApplicationDirectory(String name)
			{
				if(name == null)
				{
					throw new ArgumentNullException("name");
				}
				parser = new UrlParser(name);
			}
        void GoHome(bool needCheckEtag = false)
        {
            if (string.IsNullOrEmpty(Native?.Url))
            {
                return;
            }
            var naturl = UrlParser.Parse(Native.Url);

            if (naturl.AbsoluteUrl == homeUrl)
            {
                return;
            }
            WebViewer.Uri = homeUrl;
            LoadUrl(needCheckEtag: needCheckEtag);
        }
Esempio n. 3
0
        public void RestoreHistory()
        {
            var url = new UrlParser(UrlUtil.Url);
            var recentQueryHashCode = url.GetQueryParam("recentQuery");

            if (PerDatabaseState.QueryHistoryManager.IsHistoryLoaded)
            {
                ApplyQueryState(recentQueryHashCode);
            }
            else
            {
                PerDatabaseState.QueryHistoryManager.WaitForHistoryAsync()
                .ContinueOnUIThread(_ => ApplyQueryState(recentQueryHashCode));
            }
        }
Esempio n. 4
0
        private void NavigateToPage(int pageOffset)
        {
            var skip1 = Skip + pageOffset * PageSize;

            Skip = (short)skip1;

            if (IsSkipBasedOnTheUrl)
            {
                var urlParser = new UrlParser(UrlUtil.Url);
                urlParser.SetQueryParam("skip", Skip);
                UrlUtil.Navigate(urlParser.BuildUrl());
            }

            OnPagerChanged();
        }
Esempio n. 5
0
        public void ShouldReturnNodesThatMatchTheRoute()
        {
            ParameterInfo captureParameter = CreateParameter <string>("capture");

            IMatchNode[]    nodes    = this.builder.Parse("/literal/{capture}/", new[] { captureParameter });
            StringSegment[] segments = UrlParser.GetSegments("/literal/string_value").ToArray();

            NodeMatchResult literal = nodes[0].Match(segments[0]);
            NodeMatchResult capture = nodes[1].Match(segments[1]);

            Assert.That(nodes, Has.Length.EqualTo(2));
            Assert.That(literal.Success, Is.True);
            Assert.That(capture.Success, Is.True);
            Assert.That(capture.Value, Is.EqualTo("string_value"));
        }
        public void ValidateProcessedRedirectsIncludingNotMatchingNewUrl()
        {
            var configuration =
                TestData.TestData.DefaultConfiguration;
            var urlFormatter = new UrlFormatter();
            var urlParser    = new UrlParser();
            var urlHelper    = new UrlHelper(
                configuration,
                urlParser,
                urlFormatter);
            var processedRedirectValidator =
                new ProcessedRedirectValidator(
                    configuration,
                    urlHelper);

            var validProcessedRedirects = _processedRedirects
                                          .Where(x => processedRedirectValidator.IsValid(x, true))
                                          .ToList();

            Assert.AreEqual(
                2,
                validProcessedRedirects.Count);

            var urlResponseResult1 = validProcessedRedirects[0]
                                     .Results
                                     .OfType <UrlResponseResult>()
                                     .FirstOrDefault(r => r.Url != null && r.Url != null);

            Assert.AreEqual(
                "http://www.test2.local/url3",
                validProcessedRedirects[0].ParsedRedirect.OldUrl.Formatted);
            Assert.AreEqual(
                "http://www.test2.local/url9",
                urlResponseResult1.Url);

            var urlResponseResult2 = validProcessedRedirects[1]
                                     .Results
                                     .OfType <UrlResponseResult>()
                                     .FirstOrDefault(r => r.Url != null && r.Url != null);

            Assert.IsNotNull(urlResponseResult2);
            Assert.AreEqual(
                "http://www.test2.local/url4",
                validProcessedRedirects[1].ParsedRedirect.OldUrl.Formatted);
            Assert.AreEqual(
                "http://www.test2.local/url10",
                urlResponseResult2.Url);
        }
Esempio n. 7
0
        public override void LoadModelParameters(string parameters)
        {
            var url = new UrlParser(UrlUtil.Url);

            if (url.GetQueryParam("mode") == "new")
            {
                Mode = DocumentMode.New;
                return;
            }

            var docId = url.GetQueryParam("id");

            if (string.IsNullOrWhiteSpace(docId) == false)
            {
                Mode = DocumentMode.DocumentWithId;
                SetCurrentDocumentKey(docId);
                DatabaseCommands.GetAsync(docId)
                .ContinueOnSuccessInTheUIThread(newdoc =>
                {
                    if (newdoc == null)
                    {
                        HandleDocumentNotFound();
                        return;
                    }
                    document.Value = newdoc;
                    isLoaded       = true;
                })
                .Catch();
                return;
            }

            var projection = url.GetQueryParam("projection");

            if (string.IsNullOrWhiteSpace(projection) == false)
            {
                Mode = DocumentMode.Projection;
                try
                {
                    var newdoc = RavenJObject.Parse(projection).ToJsonDocument();
                    document.Value = newdoc;
                }
                catch
                {
                    HandleDocumentNotFound();
                    throw;                     // Display why we couldn't parse the projection from the URL correctly
                }
            }
        }
Esempio n. 8
0
        private async Task HandleRequest(IOwinContext context)
        {
            var headers = new HeaderCollection();

            context.Request.Headers.ForEach(header => headers[header.Key] = new Header(header.Key, header.Value));
            var requestInfo = new RequestInfo(
                Verb.Parse(context.Request.Method),
                (HttpUrl)UrlParser.Parse(context.Request.Uri.AbsoluteUri.TrimEnd('/')),
                context.Request.Body,
                new OwinPrincipal(context.Authentication.User),
                headers);

            System.Runtime.Remoting.Messaging.CallContext.HostContext = requestInfo;
            ResponseInfo response;

            try
            {
                response = await _requestHandler.HandleRequestAsync(requestInfo);
            }
            finally
            {
                System.Runtime.Remoting.Messaging.CallContext.HostContext = null;
            }

            if ((IsResponseNoMatchingRouteFoundException(response)) && (Next != null))
            {
                await Next.Invoke(context);

                return;
            }

            context.Response.StatusCode = (int)response.Status;
            foreach (var header in response.Headers)
            {
                switch (header.Name)
                {
                case Header.ContentLength:
                    context.Response.ContentLength = response.Body.Length;
                    break;

                default:
                    context.Response.Headers.Add(header.Name, header.Values.Select(headerValue => headerValue.ToString()).ToArray());
                    break;
                }
            }

            response.Body.CopyTo(context.Response.Body);
        }
        public void DetectOnlyCyclicRedirect()
        {
            // create redirect processor
            var configuration = new Configuration
            {
                ForceHttpHostPatterns = new[]
                {
                    "www\\.test\\.local"
                }
            };
            var urlParser         = new UrlParser();
            var urlFormatter      = new UrlFormatter();
            var redirectProcessor = new RedirectProcessor(
                configuration,
                new UrlHelper(
                    configuration,
                    urlParser,
                    urlFormatter),
                new TestHttpClient(),
                urlParser,
                urlFormatter,
                new RedirectHelper(
                    configuration,
                    urlParser,
                    urlFormatter));

            // parsed redirects
            var redirects = TestData.TestData.GetParsedRedirects();

            // preload redirects
            redirectProcessor.PreloadParsedRedirects(
                redirects);

            // process redirects using redirect processor
            var processedRedirects = TestData.TestData.GetProcessedRedirects(
                redirects,
                new[] { redirectProcessor });

            // verify cyclic redirect is detected
            var cyclicRedirect = processedRedirects
                                 .FirstOrDefault(pr => pr.Results.Any(r => r.Type.Equals(ResultTypes.CyclicRedirect)));

            Assert.IsNotNull(cyclicRedirect);
            var optimizedRedirect = processedRedirects
                                    .FirstOrDefault(pr => pr.Results.Any(r => r.Type.Equals(ResultTypes.OptimizedRedirect)));

            Assert.IsNull(optimizedRedirect);
        }
Esempio n. 10
0
        public static void NetSpider(string url)
        {
            //要爬取url
            Http.Get(url).OnSuccess((webheader, stream, response) =>
            {
                //1,获取文本内容
                var result = StreamDecoder.DecodeData(stream, response).ToLower();

                //2,存取关注数据 title..
                HtmlDocument htmldoc = new HtmlDocument();

                htmldoc.LoadHtml(result);

                var title  = new TitleParser(htmldoc).DoParser();
                dic[title] = url;
                Console.WriteLine(title + ":" + url);
                var urls = new UrlParser(htmldoc).DoParser();
                if (urls == null)
                {
                    return;
                }
                Queue <string> queue = new Queue <string>(urls);

                foreach (var item in queue)
                {
                    if (response.ResponseUri.Host != host)
                    {
                        return;
                    }
                    if (item.StartsWith("http"))
                    {
                        NetSpider(item.Trim());
                    }
                    else
                    {
                        string temp = "http://" + response.ResponseUri.Host + "/" + item.Trim();
                        NetSpider(temp);
                    }
                }

                //获取新的url地址
                //过滤url地址
                //将新的url地址加入到队列中
                //循环操作
            }).OnFail(action => {
                //状态码处理
            }).Go();
        }
        public void QueryStringIsCopied()
        {
            var value = CommonTestHelpers.GenerateList(5);
            var qs    = new FormUrlEncodedContent(value).ReadAsStringAsync().Result;

            var dictionary = CommonTestHelpers.GenerateDictionary(value);

            var httpRequest = new Mock <HttpRequest>();

            httpRequest.SetUrl(UrlParser.GenerateUri("/Home/Index?" + qs));
            httpRequest.Setup(p => p.Method).Returns("GET");

            var result = HttpRequestFactory.Create(httpRequest.Object);

            Assert.AreEqual(JsonSerializer.Serialize(value), JsonSerializer.Serialize(result.Properties.QueryString));
        }
Esempio n. 12
0
        public override void Execute(object parameter)
        {
            var urlParser = new UrlParser("/edit");

            if (string.IsNullOrEmpty(viewableDocument.Id))
            {
                var key = ProjectionData.Projections.First(x => x.Value == viewableDocument).Key;
                urlParser.SetQueryParam("projection", key);
            }
            else
            {
                urlParser.SetQueryParam("id", viewableDocument.Id);
            }

            UrlUtil.Navigate(urlParser.BuildUrl());
        }
Esempio n. 13
0
        public static DocumentNavigator FromUrl(UrlParser parser)
        {
            var mode = parser.GetQueryParam("navigationMode");

            if (mode == "allDocs")
            {
                return(AllDocumentsNavigator.AllDocumentsFromUrl(parser));
            }

            if (mode == "index")
            {
                return(IndexDocumentsNavigator.IndexNavigatorFromUrl(parser));
            }

            return(new SingleDocumentNavigator(parser.GetQueryParam("id")));
        }
Esempio n. 14
0
        public override void Execute(object parameter)
        {
            var urlParser = new UrlParser("/edit");

            if (string.IsNullOrEmpty(viewableDocument.Id))
            {
                var projection = viewableDocument.InnerDocument.ToJson().ToString(Formatting.None);
                urlParser.SetQueryParam("projection", projection);
            }
            else
            {
                urlParser.SetQueryParam("id", viewableDocument.Id);
            }

            UrlUtil.Navigate(urlParser.BuildUrl());
        }
        public void QueryStringIsCopiedFromUnvalidatedRequestValues()
        {
            var value            = KissLog.Tests.Common.CommonTestHelpers.GenerateList(5);
            var unvalidatedValue = KissLog.Tests.Common.CommonTestHelpers.GenerateList(5);

            var httpRequest = new Mock <HttpRequestBase>();

            httpRequest.Setup(p => p.Url).Returns(UrlParser.GenerateUri("/Home/Index"));
            httpRequest.Setup(p => p.HttpMethod).Returns("GET");
            httpRequest.Setup(p => p.QueryString).Returns(Helpers.GenerateNameValueCollection(value));
            httpRequest.Setup(p => p.Unvalidated.QueryString).Returns(Helpers.GenerateNameValueCollection(unvalidatedValue));

            var result = HttpRequestFactory.Create(httpRequest.Object);

            Assert.AreEqual(JsonSerializer.Serialize(unvalidatedValue), JsonSerializer.Serialize(result.Properties.QueryString));
        }
Esempio n. 16
0
        public override void LoadModelParameters(string parameters)
        {
            var urlParser = new UrlParser(parameters);

            IndexName = urlParser.Path.Trim('/');

            DatabaseCommands.GetIndexAsync(IndexName)
            .ContinueOnSuccessInTheUIThread(definition =>
            {
                if (definition == null)
                {
                    IndexDefinitionModel.HandleIndexNotFound(IndexName);
                    return;
                }
            }).Catch();
        }
Esempio n. 17
0
        public void PagesOutsideStartPage_AreReferenced_ThroughTheirRewrittenUrl()
        {
            host   = new Host(wrapper, 10, 1);
            parser = new UrlParser(persister, wrapper, host, new HostSection());

            CreateDefaultStructure();
            ContentItem root = CreateOneItem <PageItem>(10, "root", null);

            startItem.AddTo(root);
            ContentItem outside1 = CreateOneItem <PageItem>(11, "outside1", root);

            mocks.ReplayAll();

            Assert.AreEqual(parser.BuildUrl(root), root.FindPath(PathData.DefaultAction).RewrittenUrl.ToString());
            Assert.AreEqual(parser.BuildUrl(outside1), outside1.FindPath(PathData.DefaultAction).RewrittenUrl.ToString());
        }
Esempio n. 18
0
        private void Initialize()
        {
            if (DesignerProperties.IsInDesignTool)
            {
                return;
            }

            documentStore = new DocumentStore
            {
                Url = Url
            };

            var urlParser = new UrlParser(UrlUtil.Url);
            var apiKey    = urlParser.GetQueryParam("api-key");

            if (string.IsNullOrEmpty(apiKey) == false)
            {
                documentStore.ApiKey = apiKey;
            }

            documentStore.Initialize();

            // We explicitly enable this for the Studio, we rely on SL to actually get us the credentials, and that
            // already gives the user a clear warning about the dangers of sending passwords in the clear. I think that
            // this is sufficient warning and we don't require an additional step, so we can disable this check safely.
            documentStore.JsonRequestFactory.
            EnableBasicAuthenticationOverUnsecuredHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers
                =
                    true;

            documentStore.JsonRequestFactory.ConfigureRequest += (o, eventArgs) =>
            {
                if (onWebRequest != null)
                {
                    onWebRequest(eventArgs.Request);
                }
            };

            defaultDatabase = new[] { Constants.SystemDatabase };
            Databases.Set(defaultDatabase);
            SetCurrentDatabase(new UrlParser(UrlUtil.Url));

            //DisplayRawUrl();
            DisplayBuildNumber();
            DisplayLicenseStatus();
            TimerTickedAsync();
        }
Esempio n. 19
0
        public void Setup()
        {
            HttpUrl requestUrl   = (HttpUrl)UrlParser.Parse("/test");
            var     classMapping = new Mock <IClassMapping>(MockBehavior.Strict);

            classMapping.SetupGet(instance => instance.Uri).Returns(EntityConverter.Hydra.AddFragment("ApiDocumentation"));
            var mapping = new Mock <IEntityMapping>(MockBehavior.Strict);

            mapping.SetupGet(instance => instance.Classes).Returns(new[] { classMapping.Object });
            var mappings = new Mock <IMappingsRepository>(MockBehavior.Strict);

            mappings.Setup(instance => instance.MappingFor(typeof(IApiDocumentation))).Returns(mapping.Object);
            var classEntity     = new Mock <IClass>(MockBehavior.Strict);
            var baseUriSelector = new Mock <IBaseUriSelectionPolicy>(MockBehavior.Strict);

            baseUriSelector.Setup(instance => instance.SelectBaseUri(It.IsAny <EntityId>())).Returns(new Uri("http://temp.uri/"));
            var context = new Mock <IEntityContext>(MockBehavior.Strict);

            context.SetupGet(instance => instance.BaseUriSelector).Returns(baseUriSelector.Object);
            context.SetupGet(instance => instance.Mappings).Returns(mappings.Object);
            context.Setup(instance => instance.Create <IClass>(It.IsAny <EntityId>())).Returns(classEntity.Object);
            _apiDocumentation = new Mock <IApiDocumentation>(MockBehavior.Strict);
            _apiDocumentation.SetupGet(instance => instance.Context).Returns(context.Object);
            _apiDocumentation.SetupGet(instance => instance.SupportedClasses).Returns(new List <IClass>());
            _irrelevantApiDescriptionBuilder = new Mock <IApiDescriptionBuilder>(MockBehavior.Strict);
            _apiDescriptionBuilder           = new Mock <IApiDescriptionBuilder <TestController> >(MockBehavior.Strict);
            _apiDescriptionBuilder.Setup(instance => instance.BuildDescription(_apiDocumentation.Object, null));
            _apiDescriptionBuilderFactory = new Mock <IApiDescriptionBuilderFactory>(MockBehavior.Strict);
            _apiDescriptionBuilderFactory.Setup(instance => instance.Create(It.Is <Type>(type => type == typeof(TestController)))).Returns(_apiDescriptionBuilder.Object);
            string callUri;
            var    controllerDescription = new ControllerInfo <TestController>(
                EntryPoint,
                requestUrl.InsertSegments(0, ((HttpUrl)EntryPoint.Url).Segments),
                typeof(TestController).GetMethod("Add").ToOperationInfo(requestUrl.InsertSegments(0, ((HttpUrl)EntryPoint.Url).Segments).ToString(), Verb.GET, out callUri));

            _irrelevantControllerDescriptionBuilder = new Mock <IHttpControllerDescriptionBuilder>(MockBehavior.Strict);
            _controllerDescriptionBuilder           = new Mock <IHttpControllerDescriptionBuilder <TestController> >(MockBehavior.Strict);
            _controllerDescriptionBuilder.As <IHttpControllerDescriptionBuilder>().Setup(instance => instance.BuildDescriptor()).Returns(controllerDescription);
            var entryPointControllerDescription = new ControllerInfo <EntryPointDescriptionController>(null, UrlParser.Parse("/test"));

            _entryPointControllerDescriptionBuilder = new Mock <IHttpControllerDescriptionBuilder <EntryPointDescriptionController> >(MockBehavior.Strict);
            _entryPointControllerDescriptionBuilder.As <IHttpControllerDescriptionBuilder>().Setup(instance => instance.BuildDescriptor()).Returns(entryPointControllerDescription);
            _descriptionBuilder = new ApiEntryPointDescriptionBuilder(
                _apiDescriptionBuilderFactory.Object,
                new[] { _controllerDescriptionBuilder.Object, _irrelevantControllerDescriptionBuilder.Object, _entryPointControllerDescriptionBuilder.Object });
            _descriptionBuilder.EntryPoint = EntryPoint;
        }
Esempio n. 20
0
        private HttpProperties GetHttpProperties(bool includeResponse)
        {
            HttpProperties httpProperties = new HttpProperties(new HttpRequest(new HttpRequest.CreateOptions
            {
                HttpMethod = "GET",
                Url        = UrlParser.GenerateUri(null)
            }));

            if (includeResponse)
            {
                httpProperties.SetResponse(new HttpResponse(new HttpResponse.CreateOptions()
                {
                }));
            }

            return(httpProperties);
        }
Esempio n. 21
0
        public void TestLocalSourceAndDestination()
        {
            UrlParser       urlParser;
            UrlParserResult parserResult;

            urlParser    = new UrlParser(@"c:\source", new Location(new Uri("http://site2.com/img/"), @"c:\inetpub\site2.com\img"));
            parserResult = urlParser.Parse(new Uri("http://site2.com/img/400x400/test.jpg"));
            Assert.True(parserResult.Source == @"c:\source\test.jpg");
            Assert.True(parserResult.Destination == @"c:\inetpub\site2.com\img\400x400\test.jpg");
            Assert.True(parserResult.ImageType == ImageType.Jpeg);

            urlParser    = new UrlParser(@"c:\source\", new Location(new Uri("http://site2.com/img"), @"c:\inetpub\site2.com\img\"));
            parserResult = urlParser.Parse(new Uri("http://site2.com/img/path/400x400/test.jpeg"));
            Assert.True(parserResult.Source == @"c:\source\path\test.jpeg");
            Assert.True(parserResult.Destination == @"c:\inetpub\site2.com\img\path\400x400\test.jpeg");
            Assert.True(parserResult.ImageType == ImageType.Jpeg);

            urlParser    = new UrlParser(@"C:\Source", new Location(new Uri("http://site2.com/Img"), @"c:\Inetpub\Site2.com\Img"));
            parserResult = urlParser.Parse(new Uri("http://site2.com/Img/path/to/IMAGE/400x400/test.gif"));
            Assert.True(parserResult.Source == @"C:\Source\path\to\IMAGE\test.gif");
            Assert.True(parserResult.Destination == @"c:\Inetpub\Site2.com\Img\path\to\IMAGE\400x400\test.gif");
            Assert.True(parserResult.ImageType == ImageType.Gif);

            urlParser    = new UrlParser("/var/source", new Location(new Uri("https://site2.com/img"), @"/var/www/site2.com/img"));
            parserResult = urlParser.Parse(new Uri("https://site2.com/img/400x400/test.png"));
            Assert.True(parserResult.Source == "/var/source/test.png");
            Assert.True(parserResult.Destination == @"/var/www/site2.com/img/400x400/test.png");
            Assert.True(parserResult.ImageType == ImageType.Png);

            urlParser    = new UrlParser("/var/source/", new Location(new Uri("https://site2.com/img/"), @"/var/www/site2.com/img/"));
            parserResult = urlParser.Parse(new Uri("https://site2.com/img/path/400x400/test.jpg"));
            Assert.True(parserResult.Source == "/var/source/path/test.jpg");
            Assert.True(parserResult.Destination == @"/var/www/site2.com/img/path/400x400/test.jpg");
            Assert.True(parserResult.ImageType == ImageType.Jpeg);

            urlParser    = new UrlParser("/var/SOURCE", new Location(new Uri("https://site2.com/Img"), @"/var/www/Site2.com/Img"));
            parserResult = urlParser.Parse(new Uri("https://site2.com/Img/path/to/IMAGE/400x400/test.jpg"));
            Assert.True(parserResult.Source == "/var/SOURCE/path/to/IMAGE/test.jpg");
            Assert.True(parserResult.Destination == @"/var/www/Site2.com/Img/path/to/IMAGE/400x400/test.jpg");
            Assert.True(parserResult.ImageType == ImageType.Jpeg);

            Assert.Throws <UrlParserException>(() =>
            {
                parserResult = urlParser.Parse(new Uri("https://site2.com/incorrect/path/img/400x400/test.jpg"));
            });
        }
Esempio n. 22
0
        public override void Execute(object parameter)
        {
            var urlParser = new UrlParser(UrlUtil.Url);

            if (urlParser.GetQueryParam("database") == databaseName)
            {
                return;
            }
            if (navigateAfter)
            {
                urlParser = new UrlParser("/documents");
            }

            urlParser.SetQueryParam("database", databaseName);
            // MainPage.ContentFrame_Navigated takes care of actually responding to the db name change
            UrlUtil.Navigate(urlParser.BuildUrl());
        }
Esempio n. 23
0
        protected override async void OnViewLoaded()
        {
            if (firstLoad)
            {
                RegisterToDatabaseChange();
            }

            firstLoad = false;

            Status.Sections.Clear();
            OnPropertyChanged(() => CurrentDatabase);
            await DatabaseCommands.GetStatisticsAsync();

            Status.Sections.Add(new StatisticsStatusSectionModel());
            Status.Sections.Add(new LogsStatusSectionModel());
            Status.Sections.Add(new AlertsStatusSectionModel());
            Status.Sections.Add(new IndexesErrorsStatusSectionModel());
            Status.Sections.Add(new ReplicationStatisticsStatusSectionModel());
            Status.Sections.Add(new UserInfoStatusSectionModel());

            var url = new UrlParser(UrlUtil.Url);

            var id = url.GetQueryParam("id");

            if (string.IsNullOrWhiteSpace(id) == false)
            {
                switch (id)
                {
                case "indexes-errors":
                    Status.SelectedSection.Value = Status.Sections[3];
                    break;

                case "replication":
                    Status.SelectedSection.Value = Status.Sections[4];
                    break;

                default:
                    Status.SelectedSection.Value = Status.Sections[0];
                    break;
                }
            }
            else
            {
                Status.SelectedSection.Value = Status.Sections[0];
            }
        }
Esempio n. 24
0
        public IWebClient GetWebClient(string url)
        {
            IWebClient webClient;

            var uri = new UrlParser(url);
            if (uri.IsDebug)
            {
                webClient = new SandboxWebClient();
            }
            else
            {
                webClient = new HttpWebClient(new Uri(uri.Url));
            }

            _log.DebugFormat("Using WebClient: {0}", webClient.GetType());
            return webClient;
        }
        public void ReferrerIsCopied()
        {
            string referrer = $"Referer {Guid.NewGuid()}";

            var httpRequest = new Mock <HttpRequest>();

            httpRequest.SetUrl(UrlParser.GenerateUri("/Home/Index"));
            httpRequest.Setup(p => p.Method).Returns("GET");
            httpRequest.Setup(p => p.Headers).Returns(new CustomHeaderCollection(new Dictionary <string, StringValues>
            {
                { HeaderNames.Referer, referrer }
            }));

            var result = HttpRequestFactory.Create(httpRequest.Object);

            Assert.AreEqual(referrer, result.HttpReferer);
        }
Esempio n. 26
0
        /// <inheritdoc />
        protected override IpUrl CreateInstance(IEnumerable <string> segments, bool?requiresParameters = false)
        {
            StringBuilder  path        = new StringBuilder(Path.Length * 2);
            IList <string> newSegments = new List <string>(_segments.Length + 1);

            foreach (string segment in segments)
            {
                path.Append("/").Append(UrlParser.ToSafeString(segment, FtpUrlParser.PathAllowedChars));
                newSegments.Add(segment);
            }

            var parameters = (!requiresParameters.HasValue ? null :
                              (requiresParameters.Value ? (Parameters != null ? Parameters.Clone() : new ParametersCollection(";", "=")) : Parameters));
            string url = ToAbsoluteString(Scheme, UserName, Password, Host, Port, path.ToString(), parameters);

            return(new FtpUrl(url, Scheme, UserName, Password, Host, Port, path.ToString(), Parameters, segments.ToArray()));
        }
Esempio n. 27
0
 public static HttpRequest CreateHttpRequest()
 {
     return(new HttpRequest(new HttpRequest.CreateOptions
     {
         StartDateTime = DateTime.UtcNow.AddSeconds(-120),
         Url = UrlParser.GenerateUri(Guid.NewGuid().ToString()),
         HttpMethod = "GET",
         UserAgent = $"UserAgent {Guid.NewGuid()}",
         RemoteAddress = $"RemoteAddress {Guid.NewGuid()}",
         HttpReferer = $"HttpReferer {Guid.NewGuid()}",
         SessionId = $"SessionId {Guid.NewGuid()}",
         IsNewSession = true,
         IsAuthenticated = true,
         MachineName = $"MachineName {Guid.NewGuid()}",
         Properties = CreateRequestProperties()
     }));
 }
Esempio n. 28
0
            private void SaveDocument()
            {
                RavenJObject doc;
                RavenJObject metadata;

                try
                {
                    doc      = RavenJObject.Parse(document.JsonData);
                    metadata = RavenJObject.Parse(document.JsonMetadata);
                    if (document.Key != null && Seperator != null && metadata.Value <string>(Constants.RavenEntityName) == null)
                    {
                        var entityName = document.Key.Split(new[] { Seperator }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();

                        if (entityName != null && entityName.Length > 1)
                        {
                            metadata[Constants.RavenEntityName] = char.ToUpper(entityName[0]) + entityName.Substring(1);
                        }
                        else
                        {
                            metadata[Constants.RavenEntityName] = entityName;
                        }
                    }
                }
                catch (JsonReaderException ex)
                {
                    ErrorPresenter.Show(ex.Message);
                    return;
                }

                document.UpdateMetadata(metadata);
                ApplicationModel.Current.AddNotification(new Notification("Saving document " + document.Key + " ..."));
                var  url   = new UrlParser(UrlUtil.Url);
                var  docId = url.GetQueryParam("id");
                Guid?etag  = string.Equals(docId, document.Key, StringComparison.InvariantCultureIgnoreCase) ?
                             document.Etag : Guid.Empty;

                DatabaseCommands.PutAsync(document.Key, etag, doc, metadata)
                .ContinueOnSuccess(result =>
                {
                    ApplicationModel.Current.AddNotification(new Notification("Document " + result.Key + " saved"));
                    document.Etag = result.ETag;
                    document.SetCurrentDocumentKey(result.Key, dontOpenNewTag: true);
                })
                .ContinueOnSuccess(() => new RefreshDocumentCommand(document).Execute(null))
                .Catch(exception => ApplicationModel.Current.AddNotification(new Notification(exception.Message)));
            }
Esempio n. 29
0
        public override void LoadModelParameters(string parameters)
        {
            var urlParser = new UrlParser(parameters);

            ExecutionElapsedTime.Value = TimeSpan.Zero;
            GroupByField.Value         = "";
            ValueCalculations.Clear();

            UpdateAvailableIndexes();

            var newIndexName = urlParser.Path.Trim('/');

            if (string.IsNullOrEmpty(newIndexName))
            {
                if (AvailableIndexes.Any())
                {
                    NavigateToIndexReport(AvailableIndexes.FirstOrDefault());
                    return;
                }
            }

            IndexName = newIndexName;

            DatabaseCommands.GetIndexAsync(IndexName)
            .ContinueOnUIThread(task =>
            {
                if (task.IsFaulted || task.Result == null)
                {
                    if (AvailableIndexes.Any())
                    {
                        NavigateToIndexReport(AvailableIndexes.FirstOrDefault());
                    }
                    else
                    {
                        NavigateToIndexesList();
                    }

                    return;
                }

                var fields = task.Result.Fields;

                IndexFields.Match(fields);
                QueryIndexAutoComplete = new QueryIndexAutoComplete(fields, IndexName, FilterDoc);
            }).Catch();
        }
        public override void Execute(object parameter)
        {
            var urlParser = new UrlParser("/edit");
            var friendly  = (parameter as FriendlyDocument);

            if (friendly != null)
            {
                urlParser.SetQueryParam(friendly.IsProjection ? "projection" : "id", friendly.Id);

                if (friendly.NeighborsIds != null)
                {
                    urlParser.SetQueryParam("neighbors", string.Join(",", friendly.NeighborsIds));
                }
            }

            UrlUtil.Navigate(urlParser.BuildUrl());
        }
Esempio n. 31
0
        /// <inheritdoc />
        protected override IpUrl CreateInstance(IEnumerable <string> segments, bool?requiresParameters = false)
        {
            StringBuilder  path        = new StringBuilder(Path.Length * 2);
            IList <string> newSegments = new List <string>(_segments.Length + 1);

            foreach (string segment in segments)
            {
                path.Append("/").Append(UrlParser.ToSafeString(segment, HttpUrlParser.PathAllowedChars));
                newSegments.Add(segment);
            }

            string url   = (_isAbsolute ? ToAbsoluteString(Scheme, Host, Port, path.ToString(), _query, _fragment) : ToRelativeString(path.ToString(), _query, _fragment));
            var    query = (!requiresParameters.HasValue ? null :
                            (requiresParameters.Value ? (Query != null ? Query.Clone() : new ParametersCollection("&", "=")) : Query));

            return(new HttpUrl(_isAbsolute, url, Scheme, Host, Port, path.ToString(), query, Fragment, segments.ToArray()));
        }
Esempio n. 32
0
        private void HandleRequest(HttpContext context)
        {
            var headers = new HeaderCollection();

            context.Request.Headers.ForEach(headerName => ((IDictionary <string, string>)headers)[(string)headerName] = context.Request.Headers[(string)headerName]);
            var requestInfo = new RequestInfo(
                Verb.Parse(context.Request.HttpMethod),
                (HttpUrl)UrlParser.Parse(context.Request.Url.AbsoluteUri.TrimEnd('/')),
                context.Request.InputStream,
                new HttpContextPrincipal(context.User),
                headers);

            context.Items["URSA.Http.RequestInfo"] = requestInfo;
            ResponseInfo response;

            try
            {
                response = _requestHandler.HandleRequest(requestInfo);
            }
            finally
            {
                context.Items.Remove("URSA.Http.RequestInfo");
            }

            context.Response.ContentEncoding = context.Response.HeaderEncoding = response.Encoding;
            context.Response.StatusCode      = (int)response.Status;
            foreach (var header in response.Headers)
            {
                switch (header.Name)
                {
                case Header.ContentType:
                    context.Response.ContentType = header.Value;
                    break;

                case Header.ContentLength:
                    break;

                default:
                    context.Response.Headers.Add(header.Name, header.Value);
                    break;
                }
            }

            response.Body.CopyTo(context.Response.OutputStream);
        }
Esempio n. 33
0
	// Determine if we have a URL subset match.
	public bool Matches(UrlParser url)
			{
				// Compare the scheme and host information.
				if(String.Compare(scheme, url.Scheme, true) != 0)
				{
					return false;
				}
				if(String.Compare(userInfo, url.UserInfo, true) != 0)
				{
					return false;
				}
				if(!HostMatches(host, url.Host))
				{
					return false;
				}
				if(String.Compare(port, url.Port, true) != 0)
				{
					return false;
				}

				// Compare the "rest" fields.
				if(rest.EndsWith("*"))
				{
					String r = rest.Substring(0, rest.Length - 1);
					String ur = url.Rest;
					if(r.Length > ur.Length)
					{
						return false;
					}
					if(String.Compare(r, 0, ur, 0, r.Length, true) != 0)
					{
						return false;
					}
				}
				else
				{
					if(String.Compare(rest, url.Rest, true) != 0)
					{
						return false;
					}
				}
				return true;
			}
Esempio n. 34
0
 public override void EstablishContext()
 {
     UrlParser parser = new UrlParser();
     parts = parser.Parse("hello/index").ToArray();
 }
Esempio n. 35
0
 public override void EstablishContext()
 {
     var parser = new UrlParser();
     parts = parser.Parse("hello/{name}").ToArray();
 }