Example #1
0
        public override ScrapedPage ScrapeVideos(SearchParameters sparam = null)
        {
            var rootUrl = RootUrl;

            if (sparam != null)
            {
                if (!String.IsNullOrEmpty(sparam.Url))
                {
                    rootUrl = sparam.Url;
                }
                var ub = new Uri(rootUrl);
                if (!String.IsNullOrEmpty(sparam.Query))
                {
                    ub = ub.AddQuery("k", sparam.Query);
                    ub = ub.AddQuery("sort", sparam.SortBy == VideoSortby.Relevance ? "relevance"
                        : (sparam.SortBy == VideoSortby.Rating ? "rating" : "uploaddate"));
                    ub = ub.AddQuery("durf", sparam.Duration == VideoDuration.All ? "allduration" : (sparam.Duration == VideoDuration.Long ? "10min_more" :
                                                                                                     (sparam.Duration == VideoDuration.Short ? "1-3min" : "3-10min")));
                    ub = ub.AddQuery("datef", sparam.Period == VideoPeriod.Anytime ? "all" : (sparam.Period == VideoPeriod.Today ? "today" :
                                                                                              ((sparam.Period == VideoPeriod.ThisWeek ? "week" : "month"))));
                    rootUrl = ub.AbsoluteUri;
                }
            }

            var page = new ScrapedPage();
            var elem = GotoUrl(rootUrl);

            page.Videos = ScrapThumbnailVideos(elem);
            //get next page
            var pages = SelectItems(elem, ".pagination.small.top a").ToList();

            foreach (var p in pages)
            {
                bool selected = p.Attributes["class"] != null && p.Attributes["class"].Value == "sel";
                page.Links.Add(new PagingLink
                {
                    Url        = selected? rootUrl : new Uri(new Uri(RootUrl), p.Attributes["href"].Value).AbsoluteUri,
                    IsSelected = selected,
                    Text       = p.InnerText
                });
            }


            var showMore = SelectItem(elem, ".showMore a");

            if (showMore != null)
            {
                page.Links.Add(new PagingLink
                {
                    Url  = String.Format("{0}{1}", RootUrl, showMore.Attributes["href"].Value),
                    Text = showMore.InnerText,
                });
            }

            return(page);
        }
Example #2
0
        public void AddQuery_DuplicateQuery_QueryValueMatchesLastAddedValue()
        {
            //arrange
            string expectedUri = "https://google.com/?name=value2";
            Uri    baseUri     = new Uri("https://google.com");

            //act
            string actualUri = baseUri.AddQuery("name", "value1").ToString();

            actualUri = baseUri.AddQuery("name", "value2").ToString();

            //assert
            actualUri.Should().Be(expectedUri);
        }
Example #3
0
        private IEnumerable <Uri> GetUrls(string searchTerm, int index)
        {
            var index1 = ((index - 1) * 20 + 1).ToString();
            var index2 = ((index - 1) * 20 + 11).ToString();

            var url = new Uri(_options.BaseUrl)
                      .AddQuery("cx", _options.Cx)
                      .AddQuery("q", searchTerm)
                      .AddQuery("key", _options.ApiKey)
                      .AddQuery("filter", "1")
                      .AddQuery("imgColorType", "trans")
                      .AddQuery("searchType", "image");

            return(new[] { url.AddQuery("start", index1), url.AddQuery("start", index2) });
        }
Example #4
0
        public void TestAddQueryNullableBool()
        {
            UriQueryStringBuilder uribuilder1 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder2 = new Uri("/subpath/subsubpath/", UriKind.Relative);
            UriQueryStringBuilder uribuilder3 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder4 = new Uri("/subpath/subsubpath/", UriKind.Relative);
            UriQueryStringBuilder uribuilder5 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder6 = new Uri("/subpath/subsubpath/", UriKind.Relative);

            bool?boolvalue1 = true;
            bool?boolvalue2 = false;
            bool?boolvalue3 = null;

            UriQueryStringBuilder uribuilder1After = uribuilder1.AddQuery("boolvalue", boolvalue1);
            UriQueryStringBuilder uribuilder2After = uribuilder2.AddQuery("boolvalue", boolvalue1);
            UriQueryStringBuilder uribuilder3After = uribuilder3.AddQuery("boolvalue", boolvalue2);
            UriQueryStringBuilder uribuilder4After = uribuilder4.AddQuery("boolvalue", boolvalue2);
            UriQueryStringBuilder uribuilder5After = uribuilder5.AddQuery("boolvalue", boolvalue3);
            UriQueryStringBuilder uribuilder6After = uribuilder6.AddQuery("boolvalue", boolvalue3);

            Assert.Equal("https://www.domain.tld/?boolvalue=true", ((Uri)uribuilder1After).ToString());
            Assert.Equal("/subpath/subsubpath/?boolvalue=true", ((Uri)uribuilder2After).ToString());
            Assert.Equal("https://www.domain.tld/?boolvalue=false", ((Uri)uribuilder3After).ToString());
            Assert.Equal("/subpath/subsubpath/?boolvalue=false", ((Uri)uribuilder4After).ToString());
            Assert.Equal("https://www.domain.tld/", ((Uri)uribuilder5After).ToString());
            Assert.Equal("/subpath/subsubpath/", ((Uri)uribuilder6After).ToString());
        }
Example #5
0
        static void Main(string[] args)
        {
            ILogger log = ConfigLogger();

            string urlArg = args.SingleOrDefault(x => x.StartsWith("-url="));
            //urlArg = "-url=http://tillers.dynu.com/WarframeTracker/Task/Test";
            string passphraseArg = args.SingleOrDefault(x => x.StartsWith("-passphrase="));
            //passphraseArg = "-passphrase=towerframe";

            string url        = urlArg.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries).Last();
            string passphrase = passphraseArg.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries).Last();

            string message = new EasyCryptAES().Encrypt(passphrase, DateTime.Now.ToString());

            Uri uri          = new Uri(url);
            Uri uriWithQuery = uri.AddQuery("message", message);

            using HttpClientHandler httpClientHandler = new HttpClientHandler();
            httpClientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            using HttpClient httpClient = new HttpClient(httpClientHandler);

            HttpResponseMessage response = httpClient.GetAsync(uriWithQuery).Result;

            if (response.IsSuccessStatusCode)
            {
                log.Information($"{uri} - StatusCode: {(int)response.StatusCode} {response.ReasonPhrase}");
            }
            else
            {
                log.Error($"{uri} - StatusCode: {(int)response.StatusCode} {response.ReasonPhrase}");
            }
        }
Example #6
0
        public async Task <double> TrolleyCalculator(TrolleyItems items)
        {
            Uri endpointUri = new Uri(_readConfig.ReadBaseUrl() + _readConfig.ReadTrollyCaclulator());

            endpointUri = endpointUri.AddQuery("Token", _readConfig.UserId());
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, endpointUri)
            {
                Content = new StringContent(_serializer.Serialise(items), Encoding.UTF8, "application/json")
            };

            _logger.Information("Sending request to {uri}", endpointUri);
            var response = await _client.SendAsync(requestMessage);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                _logger.Error("Error while sending request to {uri}", endpointUri);
                throw new HttpResponseException(response);
            }
            var contents = await response.Content.ReadAsStringAsync();

            double total;

            double.TryParse(contents, out total);
            return(total);
        }
Example #7
0
        public async Task LoadHttpResponseBySearchValue(string searchValue)
        {
            var requestUri = new Uri(ConstantHelpers.Http.Google.Url.SearchEngine.SEARCH);

            requestUri = requestUri.AddQuery("q", searchValue);

            await LoadHttpResponse(requestUri);
        }
Example #8
0
        public async Task LoadHttpResponseBySearchValue(string searchValue)
        {
            var requestUri = new Uri(Service.Http.Yahoo.Url.SearchEngine.SEARCH);

            requestUri = requestUri.AddQuery("q", searchValue);

            await LoadHttpResponse(requestUri);
        }
Example #9
0
        public async Task <string> ExchangeCodeForTokens(
            string tokenUri,
            IDictionary <string, string> queryParams,
            string socialName)
        {
            if (string.IsNullOrEmpty(tokenUri))
            {
                logger.LogError("Token uri is null or empty");

                var errorExplanation = new ErrorModel
                {
                    Error            = "Trying to use unregistered social network",
                    ErrorDescription = "This social service is not currently available"
                };

                throw new AuthorizationCodeExchangeException(errorExplanation);
            }

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
            };

            Uri requestUri = new Uri(tokenUri);

            foreach (KeyValuePair <string, string> queryParam in queryParams)
            {
                requestUri = requestUri.AddQuery(queryParam.Key, queryParam.Value);
            }

            httpRequestMessage.RequestUri = requestUri;

            HttpResponseMessage response;

            try
            {
                response = await httpClient.SendAsync(httpRequestMessage);
            }
            catch (HttpRequestException exception)
            {
                logger.LogError("The request failed due to an underlying issue such as " +
                                "network connectivity, DNS failure, server certificate validation or timeout");
                throw new AuthorizationCodeExchangeException($"Unable to retrieve response from the {socialName}", exception);
            }

            try
            {
                response.EnsureSuccessStatusCode(); // throws HttpRequestException if StatusCode unsuccessful
            }
            catch (HttpRequestException exception)
            {
                logger.LogError($"Response StatusCode from the {socialName} " +
                                "is unsuccessful when trying to exchange code for tokens");
                throw await HandleUnsuccessfulStatusCode(response, exception, socialName);
            }

            return(await response.Content.ReadAsStringAsync());
        }
Example #10
0
        public static Uri AddQuery(this Uri uri, string name, DateTime?value)
        {
            if (!value.HasValue)
            {
                return(uri);
            }

            return(uri.AddQuery(name, value.Value.ToUnixTimestamp().ToString()));
        }
Example #11
0
        /// <summary>
        /// getUpdates
        ///     Use this method to receive incoming updates using long polling(wiki). An Array of Update objects is returned.
        ///
        ///     Notes
        ///         1. This method will not work if an outgoing webhook is set up.
        ///         2. In order to avoid getting duplicate updates, recalculate offset after each server response.
        /// </summary>
        /// <param name="offset">Optional Identifier of the first update to be returned.Must be greater by one than the highest among the identifiers of previously received updates.By default, updates starting with the earliest unconfirmed update are returned.An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id.The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue.All previous updates will forgotten.</param>
        /// <param name="limit">Optional Limits the number of updates to be retrieved.Values between 1—100 are accepted. Defaults to 100.</param>
        /// <param name="timeout">Optional Timeout in seconds for long polling. Defaults to 0, i.e.usual short polling</param>
        public async Task <Updates> GetUpdatesAsync(UInt64?offset = null, UInt64?limit = null, UInt64?timeout = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            Uri uri = new Uri($"https://api.telegram.org/bot{_AuthToken}/getUpdates");

            if (offset.HasValue)
            {
                uri = uri.AddQuery("offset", offset.Value.ToString());
            }
            if (limit.HasValue)
            {
                uri = uri.AddQuery("limit", limit.Value.ToString());
            }
            if (timeout.HasValue)
            {
                uri = uri.AddQuery("timeout", timeout.Value.ToString());
            }
            return(Newtonsoft.Json.JsonConvert.DeserializeObject <Updates>(await _GetAsync(uri, cancellationToken)));
        }
Example #12
0
        /// <summary>
        /// Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts.
        /// If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
        /// </summary>
        /// <param name="url">HTTPS url to send updates to. Use an empty string to remove webhook integration</param>
        /// <param name="certificate">Upload your public key certificate so that the root certificate in use can be checked.</param>
        public async Task <Result> SetWebhookAsync(string url = null, InputFile certificate = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            Uri uri = new Uri($"https://api.telegram.org/bot{_AuthToken}/setWebhook");

            if (!string.IsNullOrEmpty(url))
            {
                uri = uri.AddQuery("url", url);
            }
            return(Newtonsoft.Json.JsonConvert.DeserializeObject <Result>(await _GetAsync(uri, cancellationToken)));
        }
Example #13
0
        public void AddQuery_SingleQuery_ExpectedQueryMatchesActual()
        {
            //arrange
            string expectedUri = "https://google.com/?name=value";
            Uri    baseUri     = new Uri("https://google.com");

            //act
            string actualUri = baseUri.AddQuery("name", "value").ToString();

            //assert
            actualUri.Should().Be(expectedUri);
        }
Example #14
0
        public void TestChainedConversions()
        {
            Uri baseUri = new Uri("/subpath/subsubpath/", UriKind.Relative);

            Uri newUri1 = baseUri.AddQuery("key1", "val1")
                          .AddQuery("key2", "val2")
                          .AddQuery("key3", "val3")
                          .AddQuery("key4", "val4");

            Uri newUri2 =
                (
                    (Uri)
                    ((Uri)baseUri.AddQuery("key1", "val1").AddQuery("key2", "val2")
                    )
                    .AddQuery("key3", "val3")
                )
                .AddQuery("key4", "val4");

            Assert.Equal(newUri2, newUri1);
            Assert.Equal(newUri2.ToString(), newUri1.ToString());
        }
Example #15
0
        public void AddQuery_NullQueryParamValue_QueryMatchesExpected()
        {
            //arrange
            string expectedUri = "https://google.com/";
            Uri    baseUri     = new Uri("https://google.com");

            //act
            string actualUri = baseUri.AddQuery("name", null).ToString();

            //assert
            actualUri.Should().Be(expectedUri);
        }
Example #16
0
        private Uri GetDownloadURI()
        {
            var uri = new Uri(
                Config.RemoteBaseURL
                .Replace("{feature_version}", Config.FeatureVersion.ToString())
                .Replace("{release_type}", Config.ReleaseType)
                );

            if (!string.IsNullOrWhiteSpace(Config.Architecture))
            {
                uri = uri.AddQuery("architecture", Config.Architecture);
            }

            if (!string.IsNullOrWhiteSpace(Config.ImageType))
            {
                uri = uri.AddQuery("image_type", Config.ImageType);
            }

            if (!string.IsNullOrWhiteSpace(Config.JVMImpl))
            {
                uri = uri.AddQuery("jvm_impl", Config.JVMImpl);
            }

            if (!string.IsNullOrWhiteSpace(Config.OS))
            {
                uri = uri.AddQuery("os", Config.OS);
            }

            if (Config.PageSize >= 1)
            {
                uri = uri.AddQuery("page_size", Config.PageSize.ToString());
            }

            if (!string.IsNullOrWhiteSpace(Config.Project))
            {
                uri = uri.AddQuery("project", Config.Project);
            }

            if (!string.IsNullOrWhiteSpace(Config.SortOrder))
            {
                uri = uri.AddQuery("sort_order", Config.SortOrder);
            }

            if (!string.IsNullOrWhiteSpace(Config.Vendor))
            {
                uri = uri.AddQuery("vendor", Config.Vendor);
            }

            return(uri);
        }
Example #17
0
        public void TestAddQueryInt()
        {
            UriQueryStringBuilder uribuilder1 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder2 = new Uri("/subpath/subsubpath/", UriKind.Relative);

            int intvalue = 23;

            UriQueryStringBuilder uribuilder1After = uribuilder1.AddQuery("intvalue", intvalue);
            UriQueryStringBuilder uribuilder2After = uribuilder2.AddQuery("intvalue", intvalue);

            Assert.Equal("https://www.domain.tld/?intvalue=23", ((Uri)uribuilder1After).ToString());
            Assert.Equal("/subpath/subsubpath/?intvalue=23", ((Uri)uribuilder2After).ToString());
        }
Example #18
0
        public async Task LoadApiResponseBySearchValue(string searchValue)
        {
            var requestUri = new Uri($"{ConstantHelpers.Api.Google.Url.CustomSearch.CUSTOMSEARCH}{ConstantHelpers.Api.Google.Request.KEY}&cx=017576662512468239146:omuauf_lfve");

            requestUri = requestUri.AddQuery("key", searchValue);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);

            httpWebRequest.ContentType = ConstantHelpers.WebRequest.Api.CONTENT_TYPE;
            httpWebRequest.Timeout     = ConstantHelpers.WebRequest.TIMEOUT;

            await LoadResponse(httpWebRequest);
        }
Example #19
0
        public void TestAddQueryString()
        {
            UriQueryStringBuilder uribuilder1 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder2 = new Uri("/subpath/subsubpath/", UriKind.Relative);

            string strvalue = "foo";

            UriQueryStringBuilder uribuilder1After = uribuilder1.AddQuery("strvalue", strvalue);
            UriQueryStringBuilder uribuilder2After = uribuilder2.AddQuery("strvalue", strvalue);

            Assert.Equal("https://www.domain.tld/?strvalue=foo", ((Uri)uribuilder1After).ToString());
            Assert.Equal("/subpath/subsubpath/?strvalue=foo", ((Uri)uribuilder2After).ToString());
        }
Example #20
0
        public void TestAddQueryBool()
        {
            UriQueryStringBuilder uribuilder1 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder2 = new Uri("/subpath/subsubpath/", UriKind.Relative);

            bool boolvalue = true;

            UriQueryStringBuilder uribuilder1After = uribuilder1.AddQuery("boolvalue", boolvalue);
            UriQueryStringBuilder uribuilder2After = uribuilder2.AddQuery("boolvalue", boolvalue);

            Assert.Equal("https://www.domain.tld/?boolvalue=true", ((Uri)uribuilder1After).ToString());
            Assert.Equal("/subpath/subsubpath/?boolvalue=true", ((Uri)uribuilder2After).ToString());
        }
Example #21
0
        public void SetPageUrl(string value)
        {
            var uri = new Uri(PageManager.Current.BaseUrl, value);

            if (QueryStrings.Count > 0)
            {
                foreach (var kvp in QueryStrings)
                {
                    uri = uri.AddQuery(kvp.Key, kvp.Value);
                }
            }

            PageUrl = uri.ToString();
        }
Example #22
0
        public IssueCollection FetchIssues(int max = 10, int start = 0, IEnumerable <string> returnFields = null)
        {
            var collection = new IssueCollection();
            var connection = new Connection("mcneel.myjetbrains.com", 80, false, "youtrack");

            Authenticate(connection);

            var uri = new Uri("http://mcneel.myjetbrains.com/issue");

            uri = uri.AddQuery("filter", this.ToString());
            uri = uri.AddQuery("max", max.ToString());
            uri = uri.AddQuery("after", start.ToString());
            if (returnFields != null)
            {
                foreach (var field in returnFields)
                {
                    uri = uri.AddQuery("with", field);
                }
            }

            var request  = connection.CreateHttpRequest();
            var command  = connection._uriConstructor.ConstructBaseUri(uri.PathAndQuery.TrimStart("/".ToCharArray()));
            var response = request.Get(command);

            var dyn = Newtonsoft.Json.Linq.JObject.Parse(response.RawText);

            foreach (var d in dyn)
            {
                foreach (var i in d.Value)
                {
                    collection.Add(Issue.FromJObject(i));
                }
            }

            return(collection);
        }
Example #23
0
        public async Task LoadApiResponseBySearchValue(string searchValue)
        {
            var requestUri = new Uri(ConstantHelpers.Api.Bing.Url.BingSearchV7.SEARCH);

            requestUri = requestUri.AddQuery("q", searchValue);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);

            httpWebRequest.ContentType = ConstantHelpers.WebRequest.Api.CONTENT_TYPE;
            httpWebRequest.Headers["Ocp-Apim-Trace"]            = "true";
            httpWebRequest.Headers["Ocp-Apim-Subscription-Key"] = ConstantHelpers.Api.Bing.Request.V7.KEY1;
            httpWebRequest.Headers["UserAgent"] = ConstantHelpers.WebRequest.USER_AGENT;
            httpWebRequest.Timeout = ConstantHelpers.WebRequest.TIMEOUT;

            await LoadResponse(httpWebRequest);
        }
Example #24
0
        public void TestAddQueryKeysVals()
        {
            UriQueryStringBuilder uribuilder1 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            UriQueryStringBuilder uribuilder2 = new Uri("/subpath/subsubpath/", UriKind.Relative);

            List <KeyValuePair <string, string> > keysvals = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("key1", "val1"),
                new KeyValuePair <string, string>("key2", "val2")
            };

            UriQueryStringBuilder uribuilder1After = uribuilder1.AddQuery("keysvals", keysvals);
            UriQueryStringBuilder uribuilder2After = uribuilder2.AddQuery("keysvals", keysvals);

            Assert.Equal("https://www.domain.tld/?keysvals=key1=val1;key2=val2", ((Uri)uribuilder1After).ToString());
            Assert.Equal("/subpath/subsubpath/?keysvals=key1=val1;key2=val2", ((Uri)uribuilder2After).ToString());
        }
Example #25
0
        public void TestMultipleAddQuery(string uriString, UriKind kind)
        {
            Uri uri1 = new Uri(uriString, kind);
            Uri uri2 = new Uri(uriString, kind);
            UriQueryStringBuilder uribuilder1 = new Uri(uriString, kind);
            UriQueryStringBuilder uribuilder2 = new Uri(uriString, kind);

            Uri uriAfter1 = uri1.AddQuery("strval", "foo").AddQuery("intval", 23);
            Uri uriAfter2 = uri2.AddQuery("intval", 23).AddQuery("strval", "foo");
            Uri uriAfter3 = uribuilder1.AddQuery("strval", "foo").AddQuery("intval", 23);
            Uri uriAfter4 = uribuilder2.AddQuery("intval", 23).AddQuery("strval", "foo");

            Assert.Equal(uriString + "?strval=foo&intval=23", uriAfter1.ToString());
            Assert.Equal(uriString + "?intval=23&strval=foo", uriAfter2.ToString());
            Assert.Equal(uriString + "?strval=foo&intval=23", uriAfter3.ToString());
            Assert.Equal(uriString + "?intval=23&strval=foo", uriAfter4.ToString());
        }
Example #26
0
        public async Task <List <Product> > GetProductsAsync()
        {
            Uri endpointUri = new Uri(_readConfig.ReadBaseUrl() + _readConfig.ReadProduct());

            endpointUri = endpointUri.AddQuery("Token", _readConfig.UserId());
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, endpointUri);

            _logger.Information("Sending request to {uri}", endpointUri);
            var response = await _client.SendAsync(requestMessage);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                _logger.Error("Product repository exception");
                throw new HttpResponseException(response);
            }
            var contents = await response.Content.ReadAsStringAsync();

            return(_deserializer.Deserialize <List <Product> >(contents));
        }
Example #27
0
        public void TestExtensionMethods()
        {
            Uri uri1 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            Uri uri2 = new Uri("https://www.domain.tld/", UriKind.Absolute);
            Uri uri3 = new Uri("/subpath/subsubpath/", UriKind.Relative);
            Uri uri4 = new Uri("/subpath/subsubpath/", UriKind.Relative);

            int    intvalue = 23;
            string strvalue = "foo";

            Uri uri1After = uri1.AddQuery("intvalue", intvalue);
            Uri uri2After = uri2.AddQuery("strvalue", strvalue);
            Uri uri3After = uri3.AddQuery("intvalue", intvalue);
            Uri uri4After = uri4.AddQuery("strvalue", strvalue);

            Assert.Equal("https://www.domain.tld/?intvalue=23", uri1After.ToString());
            Assert.Equal("https://www.domain.tld/?strvalue=foo", uri2After.ToString());
            Assert.Equal("/subpath/subsubpath/?intvalue=23", uri3After.ToString());
            Assert.Equal("/subpath/subsubpath/?strvalue=foo", uri4After.ToString());
        }
Example #28
0
        /// <summary>
        /// Execute the command.
        /// </summary>
        /// <param name="session">The user session.</param>
        /// <param name="parameters">The parameters (endpoint, title, message, state) to use while executing the command.</param>
        public void Execute(Sender session, Dictionary <string, InstructionParameter> parameters)
        {
            Uri endpoint = new Uri(parameters["endpoint"].ToString());

            parameters.Remove("endpoint");

            string title = "OAuth Request";

            if (parameters.ContainsKey("title"))
            {
                ;
                title = parameters["title"].ToString();
                parameters.Remove("title");
            }

            string message = "A service requires you to login for proper use.";

            if (parameters.ContainsKey("message"))
            {
                message = parameters["message"].ToString();
                parameters.Remove("message");
            }

            // Add left over parameters
            foreach (KeyValuePair <string, InstructionParameter> s in parameters)
            {
                if (s.Value.IsString())
                {
                    endpoint = endpoint.AddQuery(s.Key, s.Value.ToString());
                }
            }

            OAuthNotification notification = new OAuthNotification(endpoint.ToString(), title, message);

            if (parameters.ContainsKey("state"))
            {
                notification.State = parameters["state"].ToString();
            }
            Log.Notifier.Notify(notification);
        }
Example #29
0
        public void AddQuery_AddQueriesInLoop_QueryMatchesExpected()
        {
            //arrange
            string expectedUri = "https://google.com/?name1=value1&name2=value2";

            Uri baseUri = new Uri("https://google.com");
            Dictionary <string, string> queryParams = new Dictionary <string, string>
            {
                { "name1", "value1" },
                { "name2", "value2" }
            };

            //act
            foreach (KeyValuePair <string, string> queryParam in queryParams)
            {
                baseUri = baseUri.AddQuery(queryParam.Key, queryParam.Value);
            }
            string actualUri = baseUri.ToString();

            //assert
            actualUri.Should().Be(expectedUri);
        }
Example #30
0
        /// <summary>
        /// Uploads the UI5 Project int <see cref="ProjectDir"/> to the SAP system specified by <see cref="Credentials"/>. If <see cref="Credentials.Username"/> is <c>null</c>, a single sign on authentification is performed.
        /// </summary>
        public void Upload()
        {
            if (string.IsNullOrWhiteSpace(ProjectDir))
            {
                throw new InvalidOperationException("ProjectDir not set.");
            }
            if (!Directory.Exists(ProjectDir))
            {
                throw new InvalidOperationException("ProjectDir not set to a folder.");
            }
            if (Credentials == null)
            {
                throw new InvalidOperationException("Credentials not set.");
            }
            if (string.IsNullOrWhiteSpace(Credentials.System))
            {
                throw new InvalidOperationException("Credentials.System not set.");
            }
            if (string.IsNullOrWhiteSpace(AppName))
            {
                throw new InvalidOperationException("AppName not set.");
            }

            if (TestMode)
            {
                Log.Instance.Write("Test mode on!");
            }

            try
            {
                var uri = new Uri(this.Credentials.System);
                uri = uri.AddQuery("sap-client", Credentials.Mandant.ToString());
                uri = uri.AddQuery("sapui5applicationname", AppName);
                uri = uri.AddQuery("sapui5applicationdescription", AppDescription);
                uri = uri.AddQuery("sapui5applicationpackage", Package);
                uri = uri.AddQuery("workbenchrequest", TransportRequest);
                uri = uri.AddQuery("externalcodepage", ExternalCodepage);
                uri = uri.AddQuery("deltamode", DeltaMode ? "true" : "false");
                uri = uri.AddQuery("testmode", TestMode ? "true" : "false");

                if (IgnoreCertificateErrors)
                {
                    System.Net.ServicePointManager.ServerCertificateValidationCallback += ServerCertificateValidationIgnoreAll;
                }

                var cookieContainer = new System.Net.CookieContainer();
                //Try to Authenticate with a HEAD request and retrieve an authentification token cookie before uploading the whole application.
                var headRequest = System.Net.HttpWebRequest.Create(uri);
                headRequest.PreAuthenticate = false;
                headRequest.Timeout         = 10000;
                headRequest.Method          = System.Net.WebRequestMethods.Http.Head;
                ((System.Net.HttpWebRequest)headRequest).CookieContainer = cookieContainer;

                if (Credentials.Username != null)
                {
                    headRequest.Credentials = new System.Net.NetworkCredential(Credentials.Username, Credentials.Password);
                }
                else //SSO
                {
                    headRequest.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                    headRequest.Credentials        = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
                headRequest.GetResponse().Close();

                //The actual POST request with the ziped project.
                var request = System.Net.HttpWebRequest.Create(uri);
                request.Timeout               = Timeout * 1000;
                request.PreAuthenticate       = true;
                request.UseDefaultCredentials = false;
                ((System.Net.HttpWebRequest)request).CookieContainer = cookieContainer; //Contains the authentification token if acquired
                if (Credentials.Username != null)                                       //if not: credentials to reauthenficiate.
                {
                    request.Credentials = new System.Net.NetworkCredential(Credentials.Username, Credentials.Password);
                }
                else //SSO
                {
                    request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                    request.Credentials        = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
                Log.Instance.Write("Uploading project...");
                request.Method      = System.Net.WebRequestMethods.Http.Post;
                request.ContentType = "application/zip";
                using (var stream = request.GetRequestStream())
                {
                    using (var zipHelper = new ZipHelper(stream))
                    {
                        zipHelper.Zip(".Ui5RepositoryUploadParameters", Encoding.UTF8.GetBytes(cleanedConfigFileContent));
                        zipHelper.Zip(ProjectDir, new[] { ".Ui5Repository*", "WebContent" }, IgnoreMasks.ToArray());
                    }
                    stream.Close();
                }
                Log.Instance.Write("Installing App...");
                var response = (System.Net.HttpWebResponse)request.GetResponse();
                HandleResponse(response);
            }
            catch (System.Net.WebException ex)
            {
                if (ex.Response != null)
                {
                    HandleResponse((System.Net.HttpWebResponse)ex.Response);
                }
                else
                {
                    Log.Instance.Write(ex.ToString());
                    Log.Instance.Write("Upload failed!");
                    throw new UploadFailedException();
                }
            }
        }