コード例 #1
0
        public ActionResult Login(string returnUrl)
        {
            if (!User.Identity.IsAuthenticated)
            {
                // User is not authenticated.
                // WSFederationAuthenticationModule is configured to kick in
                // when in EndRequest a request indicates "unauthorized access".
                // Therefore, the following call will start the login process,
                // and after completion, will come back to this address.
                return new HttpUnauthorizedResult();
            }

            // The user successfully authenticated.

            string nameIdentifier = this.GetUserNameIdentifier();
            if (!_userRepo.IsExistingUser(nameIdentifier))
            {
                // New user. Redirect to page for recording user name.
                var queryString = new QueryString { { "returnUrl", returnUrl } };
                return new RedirectResult("/Account/UserData" + queryString);
            }

            // user exists.
            // Redirect back to the page the user was querying.
            return new RedirectResult(returnUrl);
        }
コード例 #2
0
    public virtual IPromise<IHttpResponse> Execute(string method, string baseUrl, QueryString queryString, System.Net.ICredentials credentials, bool async, Action<IHttpRequest> configure)
    {
      var uri = baseUrl + (queryString == null ? "" : queryString.ToString());

      var req = (HttpWebRequest)System.Net.WebRequest.Create(uri);
      req.AllowAutoRedirect = this.AllowAutoRedirect;
      if (this.AutomaticDecompression) req.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);
      if (this.StoreCookies) req.CookieContainer = _cookieContainer;
      req.Method = method;
      req.ReadWriteTimeout = 300000;
      req.Timeout = DefaultTimeout;
      if (method == "POST")
      {
        req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
      }
      req.Credentials = credentials;
      var result = new WebRequest(req, this.Compression);
      if (configure != null) configure.Invoke(result);

      var st = Stopwatch.StartNew();
      return result.Execute(async).Convert(r => {
        if (r.Core.Cookies.Count > 0) SetCookies(r.Core.Cookies);
        return (IHttpResponse)r;
      }).Always(() => {
        st.Stop();
        _httpTracing.TraceData(TraceEventType.Verbose, 0, st.ElapsedMilliseconds);
      });
    }
コード例 #3
0
            public void Creating_from_empty_map()
            {
                var args = new Dictionary<string, string>();
                var qs = new QueryString(args);

                qs.ToString().ShouldBe(string.Empty);
            }
コード例 #4
0
        public ActionResult Process(HttpRequestBase request, ModelStateDictionary modelState)
        {
            IpnVerificationBinder binder = new IpnVerificationBinder();
            Transaction tx = binder.Bind(request.Form, modelState);

            ContentResult cr = new ContentResult();
            cr.ContentEncoding = Encoding.UTF8;
            cr.ContentType = "text/html";
            cr.Content = "INVALID";

            if (tx != null)
            {
                Transaction dbTx = m_txRepository.GetAll().Where(x => x.Tx == tx.Tx).FirstOrDefault();
                if (dbTx != null)
                {
                    string expected = dbTx.ToIpnQueryString().ToString();
                    QueryString actualQs = new QueryString();
                    actualQs.Add(request.Form);
                    actualQs.Remove("cmd");
                    string actual = actualQs.ToString();

                    if (expected == actual)
                    {
                        cr.Content = "VERIFIED";
                    }
                }
            }

            return cr;
        }
コード例 #5
0
        /// <summary>
        /// Combines the given URI components into a string that is properly encoded for use in HTTP headers.
        /// Note that unicode in the HostString will be encoded as punycode.
        /// </summary>
        /// <param name="scheme">http, https, etc.</param>
        /// <param name="host">The host portion of the uri normally included in the Host header. This may include the port.</param>
        /// <param name="pathBase">The first portion of the request path associated with application root.</param>
        /// <param name="path">The portion of the request path that identifies the requested resource.</param>
        /// <param name="query">The query, if any.</param>
        /// <param name="fragment">The fragment, if any.</param>
        /// <returns></returns>
        public static string BuildAbsolute(
            string scheme,
            HostString host,
            PathString pathBase = new PathString(),
            PathString path = new PathString(),
            QueryString query = new QueryString(),
            FragmentString fragment = new FragmentString())
        {
            var combinedPath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/";

            var encodedHost = host.ToString();
            var encodedQuery = query.ToString();
            var encodedFragment = fragment.ToString();

            // PERF: Calculate string length to allocate correct buffer size for StringBuilder.
            var length = scheme.Length + SchemeDelimiter.Length + encodedHost.Length
                + combinedPath.Length + encodedQuery.Length + encodedFragment.Length;

            return new StringBuilder(length)
                .Append(scheme)
                .Append(SchemeDelimiter)
                .Append(encodedHost)
                .Append(combinedPath)
                .Append(encodedQuery)
                .Append(encodedFragment)
                .ToString();
        }
コード例 #6
0
        public void MyFact()
        {
            var queryString = new QueryString();

            queryString.Add("q", "mcdonald");

            Assert.Equal("q=mcdonald", queryString.ToString());
        }
コード例 #7
0
 /// <summary>
 /// Combines the given URI components into a string that is properly encoded for use in HTTP headers.
 /// </summary>
 /// <param name="pathBase"></param>
 /// <param name="path"></param>
 /// <param name="query"></param>
 /// <param name="fragment"></param>
 /// <returns></returns>
 public static string Encode(PathString pathBase = new PathString(),
     PathString path = new PathString(),
     QueryString query = new QueryString(),
     FragmentString fragment = new FragmentString())
 {
     string combinePath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/";
     return combinePath + query + fragment;
 }
コード例 #8
0
        public void AppendOtherObjectsWithCanBeConvertedToStrings()
        {
            string actual = new QueryString().
                Append("foo", 10).
                Append("bar", "20.00").ToString();

            Assert.AreEqual("foo=10&bar=20.00", actual);
        }
コード例 #9
0
ファイル: QueryStringTests.cs プロジェクト: Vanaheimr/Hermod
        public void ParseQueryString_001()
        {
            var QueryString = new QueryString("abc?a=b");

            Assert.AreEqual(1,   QueryString.Count());
            Assert.AreEqual("a", QueryString.First().Key);
            Assert.AreEqual("b", QueryString.First().Value.First());
        }
コード例 #10
0
            public void With_no_parameters()
            {
                var uri = new Uri("http://foo/bar");
                var qs = new QueryString(uri);

                qs.ToString().ShouldBe(string.Empty);
                qs.ToString(canonical: true).ShouldBe(string.Empty);
            }
コード例 #11
0
ファイル: QueryStringTests.cs プロジェクト: Vanaheimr/Hermod
        public void ParseQueryString_002()
        {
            var QueryString = new QueryString("?a=b&a=c");

            Assert.AreEqual(1, QueryString.Count());
            Assert.AreEqual("a", QueryString.First().Key);
            Assert.AreEqual("b", QueryString.First().Value.First());
            Assert.AreEqual("c", QueryString.First().Value.Skip(1).First());
        }
コード例 #12
0
        public void ShouldNotEncodeWhenAdding()
        {
            // arrange
            QueryString qs = new QueryString();
            qs.Add("1", "http://");

            // act and assert
            Assert.AreEqual("http://", qs["1"]);
        }
コード例 #13
0
        public void ShouldEncodeWhenConvertingToString()
        {
            // arrange
            QueryString qs = new QueryString();
            qs.Add("1", "http://");

            // act and assert
            Assert.AreEqual("?1=http%3a%2f%2f", qs.ToString());
        }
コード例 #14
0
        public void ShouldDecodeWhenGettingValue()
        {
            // arrange
            QueryString qs = new QueryString();
            qs.Add("1", "http%3a%2f%2f");

            // act and assert
            Assert.AreEqual("http://", qs["1"]);
        }
コード例 #15
0
 /// <summary>
 /// Combines the given URI components into a string that is properly encoded for use in HTTP headers.
 /// Note that unicode in the HostString will be encoded as punycode.
 /// </summary>
 /// <param name="scheme"></param>
 /// <param name="host"></param>
 /// <param name="pathBase"></param>
 /// <param name="path"></param>
 /// <param name="query"></param>
 /// <param name="fragment"></param>
 /// <returns></returns>
 public static string Encode(string scheme,
     HostString host,
     PathString pathBase = new PathString(),
     PathString path = new PathString(),
     QueryString query = new QueryString(),
     FragmentString fragment = new FragmentString())
 {
     string combinePath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/";
     return scheme + "://" + host + combinePath + query + fragment;
 }
コード例 #16
0
        public void ShouldContainClassNamesFromQueryString()
        {
            var uri = new Uri("/TestHarness.htm?xap=One&Class=NS.Class&class=  Class2.&CLASS=  &class=Class3  ", UriKind.Relative);
            var model = new QueryString(uri.GetQueryString());
            model.ClassNames.Count().ShouldBe(3);

            model.ClassNames.ElementAt(0).ShouldBe("NS.Class");
            model.ClassNames.ElementAt(1).ShouldBe("Class2.");
            model.ClassNames.ElementAt(2).ShouldBe("Class3");
        }
コード例 #17
0
        public void ShouldBuildHttpPostString()
        {
            // arrange
            QueryString qs = new QueryString();
            qs.Add("1", "2");
            qs.Add("3", "4");

            // act and assert
            Assert.AreEqual("1=2&3=4", qs.ToString(HttpAction.Post));
        }
コード例 #18
0
 /// <summary>
 /// Create a new HTTP request.
 /// </summary>
 public HTTPRequestBuilder()
 {
     this.HTTPStatusCode  = HTTPStatusCode.OK;
     this.HTTPMethod      = HTTPMethod.GET;
     this.UrlPath         = "/";
     this._QueryString    = new QueryString();
     this.Accept          = new AcceptTypes();
     this.ProtocolName    = "HTTP";
     this.ProtocolVersion = new HTTPVersion(1, 1);
 }
コード例 #19
0
ファイル: JsonView.cs プロジェクト: igorfrance/sage
        /// <summary>
        /// Renders the meta view of the view associated with the specified <paramref name="viewContext"/> 
        /// and <paramref name="writer"/>.
        /// </summary>
        /// <param name="viewContext">The view context.</param>
        /// <param name="writer">The writer to write to.</param>
        public override void Render(ViewContext viewContext, TextWriter writer)
        {
            SageController controller = (SageController) viewContext.Controller;
            XmlDocument requestXml = controller.PrepareViewXml(viewContext);

            QueryString query = new QueryString(viewContext.HttpContext.Request.QueryString);
            bool prettyPrint = query.HasValid("pretty", "1|true|yes");
            viewContext.HttpContext.Response.ContentType = this.Info.ContentType;
            writer.Write(requestXml.DocumentElement.ToJson(prettyPrint));
        }
コード例 #20
0
ファイル: QueryStringTests.cs プロジェクト: Vanaheimr/Hermod
        public void ParseQueryString_003()
        {
            var QueryString = new QueryString("a=b&c=d");

            Assert.AreEqual(2, QueryString.Count());
            Assert.AreEqual("a", QueryString.First().Key);
            Assert.AreEqual("b", QueryString.First().Value.First());
            Assert.AreEqual("c", QueryString.Skip(1).First().Key);
            Assert.AreEqual("d", QueryString.Skip(1).First().Value.First());
        }
コード例 #21
0
ファイル: DotvvmMiddleware.cs プロジェクト: holajan/dotvvm
        /// <summary>
        /// Attempts to recognize request made by Googlebot in its effort to crawl links for AJAX SPAs.
        /// </summary>
        /// <param name="queryString">
        /// The query string of the request to try to match the Googlebot hashbang escaped fragment on.
        /// </param>
        /// <param name="url">
        /// The plain URL string that the hasbang escaped fragment represents.
        /// </param>
        /// <returns>
        /// <code>true</code>, if the URL contains valid Googlebot hashbang escaped fragment; otherwise <code>false</code>.
        /// </returns>
        /// <seealso cref="https://developers.google.com/webmasters/ajax-crawling/docs/getting-started"/>
        private bool TryParseGooglebotHashbangEscapedFragment(QueryString queryString, out string url)
        {
            if (queryString.Value.StartsWith(GooglebotHashbangEscapedFragment, StringComparison.Ordinal))
            {
                url = queryString.Value.Substring(GooglebotHashbangEscapedFragment.Length);
                return true;
            }

            url = null;
            return false;
        }
コード例 #22
0
            public void Creating_from_map()
            {
                var args = new Dictionary<string, string>()
            {
                { "foo", "bar" },
                { "abc", "123" },
            };
                var qs = new QueryString(args);

                qs.ToString().ShouldBe("abc=123&foo=bar");
            }
コード例 #23
0
        public Task<Stream> MonitorEventsAsync(MonitorDockerEventsParameters parameters, CancellationToken cancellationToken)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            const string path = "events";
            IQueryString queryParameters = new QueryString<MonitorDockerEventsParameters>(parameters);
            return this.Client.MakeRequestForStreamAsync(this.Client.NoErrorHandlers, HttpMethod.Get, path, queryParameters, null, cancellationToken);
        }
コード例 #24
0
        public void AppendWithRequest()
        {
            Request request = new CreditCardRequest
            {
                CVV = "123",
                CardholderName = "Drew"
            };

            string actual = new QueryString().Append("[credit_card]", request).ToString();
            Assert.AreEqual("%5bcredit_card%5d%5bcardholder_name%5d=Drew&%5bcredit_card%5d%5bcvv%5d=123", actual);
        }
コード例 #25
0
        public void AppendEmptyStringOrNulls()
        {
            string actual = new QueryString().
                Append("foo", "f").
                Append("", "b").
                Append("bar", "").
                Append("boom", null).
                Append("", "c").ToString();

            Assert.AreEqual("foo=f&bar=", actual);
        }
        private async Task HandleLike(ToastNotificationActionTriggerDetail details, QueryString args)
        {
            // Get the conversation the toast is about
            int conversationId = int.Parse(args["conversationId"]);

            // In a real app, this would be making a web request, sending the like command
            await Task.Delay(TimeSpan.FromSeconds(1.1));

            // In a real app, you most likely should NOT notify your user that the request completed (only notify them if there's an error)
            SendToast("Your like has been sent!");
        }
コード例 #27
0
        public void ShouldContainXapFilesFromQueryString()
        {
            var uri = new Uri("/TestHarness.htm?xap=One&XAP=Two...xap&xap=Three.&xap=Four.XAP&xap=  ", UriKind.Relative);
            var model = new QueryString(uri.GetQueryString());
            model.XapFiles.Count().ShouldBe(4);

            model.XapFiles.ElementAt(0).ShouldBe("One");
            model.XapFiles.ElementAt(1).ShouldBe("Two");
            model.XapFiles.ElementAt(2).ShouldBe("Three");
            model.XapFiles.ElementAt(3).ShouldBe("Four");
        }
コード例 #28
0
        public static string RetrieveQueryString(QueryString queryString)
        {
            string message = string.Empty;

            if (queryString.HasValue)
            {
                message = queryString.Value;
            }

            return message;
        }
コード例 #29
0
        /// <summary>
        /// 删除一个Catalog
        /// </summary>
        /// <param name="catalogId">Catalog的唯一标识</param>
        public void Delete(Int32 catalogId)
        {
            var qs = new QueryString();
            qs.Add("catalogId", catalogId.ToString());
            var deleteCata = client.HttpPost("/catalog/delete.api", qs);
            var jo = JObject.Parse(deleteCata);

            if (jo["statusCode"].ToString().CompareTo("0") != 0)
            {
                throw new PispowerAPIException(System.Int32.Parse(jo["statusCode"].ToString()), jo["message"].ToString());
            }
        }
コード例 #30
0
        public async Task<IList<ContainerListResponse>> ListContainersAsync(ListContainersParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            string path = "containers/json";
            IQueryString queryParameters = new QueryString<ListContainersParameters>(parameters);
            DockerApiResponse response = await this.Client.MakeRequestAsync(this.Client.NoErrorHandlers, HttpMethod.Get, path, queryParameters);
            return this.Client.JsonSerializer.DeserializeObject<ContainerListResponse[]>(response.Body);
        }
コード例 #31
0
            internal RequestState(HttpRequestMessage request, PathString pathBase, IHttpApplication <Context> application)
            {
                _request              = request;
                _application          = application;
                _responseTcs          = new TaskCompletionSource <HttpResponseMessage>();
                _requestAbortedSource = new CancellationTokenSource();
                _pipelineFinished     = false;

                if (request.RequestUri.IsDefaultPort)
                {
                    request.Headers.Host = request.RequestUri.Host;
                }
                else
                {
                    request.Headers.Host = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
                }

                var contextFeatures = new FeatureCollection();

                contextFeatures.Set <IHttpRequestFeature>(new RequestFeature());
                _responseFeature = new ResponseFeature();
                contextFeatures.Set <IHttpResponseFeature>(_responseFeature);
                Context = application.CreateContext(contextFeatures);
                var httpContext = Context.HttpContext;

                var serverRequest = httpContext.Request;

                serverRequest.Protocol = "HTTP/" + request.Version.ToString(2);
                serverRequest.Scheme   = request.RequestUri.Scheme;
                serverRequest.Method   = request.Method.ToString();

                var        fullPath = PathString.FromUriComponent(request.RequestUri);
                PathString remainder;

                if (fullPath.StartsWithSegments(pathBase, out remainder))
                {
                    serverRequest.PathBase = pathBase;
                    serverRequest.Path     = remainder;
                }
                else
                {
                    serverRequest.PathBase = PathString.Empty;
                    serverRequest.Path     = fullPath;
                }

                serverRequest.QueryString = QueryString.FromUriComponent(request.RequestUri);

                foreach (var header in request.Headers)
                {
                    serverRequest.Headers.Append(header.Key, header.Value.ToArray());
                }
                var requestContent = request.Content;

                if (requestContent != null)
                {
                    foreach (var header in request.Content.Headers)
                    {
                        serverRequest.Headers.Append(header.Key, header.Value.ToArray());
                    }
                }

                _responseStream                 = new ResponseStream(ReturnResponseMessage, AbortRequest);
                httpContext.Response.Body       = _responseStream;
                httpContext.Response.StatusCode = 200;
                httpContext.RequestAborted      = _requestAbortedSource.Token;
            }
コード例 #32
0
ファイル: App.xaml.cs プロジェクト: agrucza/woadialer
        public async void OnToastNotificationActivated(ToastActivationType activationType, string args)
        {
            QueryString query          = QueryString.Parse(args);
            uint        activeCallID   = 0;
            uint        incomingCallID = 0;
            Call        activeCall     = null;
            Call        incomingCall   = null;
            Frame       frame          = null;

            switch (query[NotificationSystem.ACTION])
            {
            case NotificationSystem.END:
                activeCallID = uint.Parse(query[NotificationSystem.ACTIVE_CALL_ID]);
                activeCall   = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == activeCallID);
                //if (activeCall?.AvailableActions.EndCallAvailable ?? false)
                //{
                activeCall?.End();
                //}
                //else
                //{
                //    //LOG
                //}
                break;

            case NotificationSystem.REJECT:
                incomingCallID = uint.Parse(query[NotificationSystem.INCOMING_CALL_ID]);
                incomingCall   = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == incomingCallID);
                incomingCall?.RejectIncoming();
                break;

            case NotificationSystem.TEXT_REPLY:
                incomingCallID = uint.Parse(query[NotificationSystem.INCOMING_CALL_ID]);

                break;

            case NotificationSystem.END_AND_ANSWER:
                activeCallID = uint.Parse(query[NotificationSystem.ACTIVE_CALL_ID]);
                activeCall   = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == activeCallID);
                //if (activeCall?.AvailableActions.EndCallAvailable ?? false)
                //{
                activeCall?.End();
                //}
                //else
                //{
                //    //LOG
                //}
                goto case NotificationSystem.ANSWER;

            case NotificationSystem.HOLD_AND_ANSWER:
                activeCallID = uint.Parse(query[NotificationSystem.ACTIVE_CALL_ID]);
                activeCall   = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == activeCallID);
                //if (activeCall?.AvailableActions.HoldAvailable ?? false)
                //{
                activeCall?.SetHold(true);
                //}
                //else
                //{
                //    //LOG
                //}
                goto case NotificationSystem.ANSWER;

            case NotificationSystem.ANSWER:
                incomingCallID = uint.Parse(query[NotificationSystem.INCOMING_CALL_ID]);
                incomingCall   = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == incomingCallID);
                //if (incomingCall?.AvailableActions.AnswerAvailable ?? false)
                //{
                incomingCall?.AcceptIncomingEx();
                //}
                //else
                //{
                //    //LOG
                //}
                if (activationType == ToastActivationType.Foreground)
                {
                    goto case NotificationSystem.SHOW_CALL_UI;
                }
                else
                {
                    break;
                }

            case NotificationSystem.SHOW_CALL_UI:
                CompactOverlayId = await CallUIPage.ShowInCallUI();

                //frame = Window.Current.Content as Frame;
                //frame.Navigate(typeof(InCallUI));
                break;

            case NotificationSystem.SHOW_INCOMING_CALL_UI:
                frame = Window.Current.Content as Frame;
                frame.Navigate(typeof(IncomingCallUI));
                break;
            }
        }
コード例 #33
0
        /// <summary>
        /// This adapts HttpRequestMessages to ASP.NET Core requests, dispatches them through the pipeline, and returns the
        /// associated HttpResponseMessage.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var contextBuilder = new HttpContextBuilder(_application);

            Stream responseBody   = null;
            var    requestContent = request.Content ?? new StreamContent(Stream.Null);
            var    body           = await requestContent.ReadAsStreamAsync();

            contextBuilder.Configure(context =>
            {
                var req = context.Request;

                req.Protocol = "HTTP/" + request.Version.ToString(fieldCount: 2);
                req.Method   = request.Method.ToString();

                req.Scheme = request.RequestUri.Scheme;

                foreach (var header in request.Headers)
                {
                    req.Headers.Append(header.Key, header.Value.ToArray());
                }

                if (req.Host == null || !req.Host.HasValue)
                {
                    // If Host wasn't explicitly set as a header, let's infer it from the Uri
                    req.Host = HostString.FromUriComponent(request.RequestUri);
                    if (request.RequestUri.IsDefaultPort)
                    {
                        req.Host = new HostString(req.Host.Host);
                    }
                }

                req.Path     = PathString.FromUriComponent(request.RequestUri);
                req.PathBase = PathString.Empty;
                if (req.Path.StartsWithSegments(_pathBase, out var remainder))
                {
                    req.Path     = remainder;
                    req.PathBase = _pathBase;
                }
                req.QueryString = QueryString.FromUriComponent(request.RequestUri);

                if (requestContent != null)
                {
                    foreach (var header in requestContent.Headers)
                    {
                        req.Headers.Append(header.Key, header.Value.ToArray());
                    }
                }

                if (body.CanSeek)
                {
                    // This body may have been consumed before, rewind it.
                    body.Seek(0, SeekOrigin.Begin);
                }
                req.Body = body;

                responseBody = context.Response.Body;
            });

            var httpContext = await contextBuilder.SendAsync(cancellationToken);

            var response = new HttpResponseMessage();

            response.StatusCode     = (HttpStatusCode)httpContext.Response.StatusCode;
            response.ReasonPhrase   = httpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase;
            response.RequestMessage = request;

            response.Content = new StreamContent(responseBody);

            foreach (var header in httpContext.Response.Headers)
            {
                if (!response.Headers.TryAddWithoutValidation(header.Key, (IEnumerable <string>)header.Value))
                {
                    bool success = response.Content.Headers.TryAddWithoutValidation(header.Key, (IEnumerable <string>)header.Value);
                    Contract.Assert(success, "Bad header");
                }
            }
            return(response);
        }
コード例 #34
0
ファイル: RequestInfo.cs プロジェクト: MihaMarkic/Cyanometer
 protected bool Equals(RequestInfo other)
 {
     return(string.Equals(UserAgent, other.UserAgent) && string.Equals(HttpMethod, other.HttpMethod) && IsSecure == other.IsSecure && string.Equals(Host, other.Host) && Port == other.Port && string.Equals(Path, other.Path) && string.Equals(Referrer, other.Referrer) && string.Equals(ClientIpAddress, other.ClientIpAddress) && Cookies.CollectionEquals(other.Cookies) && QueryString.CollectionEquals(other.QueryString) && Equals(Data, other.Data));
 }
コード例 #35
0
ファイル: App.xaml.cs プロジェクト: stijnvanhulle/BobApp
        //Als de gebruiker op de toast/notification klikt
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            //De rootframe ophalen
            Frame rootFrame = Window.Current.Content as Frame;



            //TODO: initialiseren van root frame, net als in OnLaunched

            //Toast Activation opvangen
            if (e is ToastNotificationActivatedEventArgs)
            {
                var toastActivationArgs = e as ToastNotificationActivatedEventArgs;


                QueryString args = QueryString.Parse(toastActivationArgs.Argument);

                //Kijk welke actie gevraagd is
                switch (args["action"])
                {
                case "viewBob":
                    Dialog dialog = new Dialog()
                    {
                        Message   = args["message"],
                        Ok        = args["ok"],
                        Nok       = args["nok"],
                        ViewOk    = JsonConvert.DeserializeObject <Type>(args["viewOk"]),
                        ViewNok   = JsonConvert.DeserializeObject <Type>(args["viewNok"]),
                        ParamView = JsonConvert.DeserializeObject <object>(args["paramView"]),
                        Cb        = args["cb"],
                        Data      = args["data"]
                    };
                    Task task = ShowDialog(dialog.Message, dialog.Ok, dialog.Nok, dialog.ViewOk, dialog.ViewNok, dialog.ParamView, dialog.Cb, dialog.Data);
                    break;

                case "ok":
                    string ok        = args["value"];
                    Type   viewOk    = JsonConvert.DeserializeObject <Type>(args["viewOk"]);
                    object paramView = JsonConvert.DeserializeObject <object>(args["paramView"]);
                    object data      = JsonConvert.DeserializeObject <object>(args["data"]);
                    string cb        = args["cb"];

                    if (viewOk != null)
                    {
                        Frame mainFrame = MainViewVM.MainFrame as Frame;
                        mainFrame.Navigate(viewOk, paramView);
                    }
                    if (cb != null)
                    {
                        Messenger.Default.Send <NavigateTo>(new NavigateTo()
                        {
                            Name      = cb,
                            Result    = true,
                            ParamView = paramView,
                            Data      = data
                        });
                    }

                    break;

                case "nok":
                    string nok        = args["value"];
                    Type   viewNok    = JsonConvert.DeserializeObject <Type>(args["viewNok"]);
                    object _paramView = JsonConvert.DeserializeObject <object>(args["paramView"]);
                    object _data      = JsonConvert.DeserializeObject <object>(args["data"]);
                    string _cb        = args["cb"];

                    if (viewNok != null)
                    {
                        Frame mainFrame = MainViewVM.MainFrame as Frame;
                        mainFrame.Navigate(viewNok, _paramView);
                    }

                    if (_cb != null)
                    {
                        Messenger.Default.Send <NavigateTo>(new NavigateTo()
                        {
                            Name      = _cb,
                            Result    = false,
                            ParamView = _paramView,
                            Data      = _data
                        });
                    }

                    break;

                //Open de application
                case "openBobApp":
                    //Nog uitzoeken hoe je dat moet doen, nog niet zo heel belangrijk
                    break;

                //Open het scherm waar je toestemming geeft om je locatie te gebruiken.
                case "openLocationServices":
                    await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));

                    break;
                }
            }

            //Maak zeker dat het scherm nu actief is
            Window.Current.Activate();
        }
コード例 #36
0
ファイル: App.xaml.cs プロジェクト: SunboX/windows-universal
        protected override async Task OnActivateApplicationAsync(IActivatedEventArgs args)
        {
            ActivatedEventArgs = args;
            await base.OnActivateApplicationAsync(args);

            // Remove unnecessary notifications whenever the app is used.
            ToastNotificationManager.History.RemoveGroup(ToastNotificationService.SyncAction);

            // Handle toast activation
            var eventArgs = args as ToastNotificationActivatedEventArgs;

            if (eventArgs != null)
            {
                var toastActivationArgs = eventArgs;
                // Parse the query string
                var query = QueryString.Parse(toastActivationArgs.Argument);
                // See what action is being requested
                switch (query["action"])
                {
                // Nothing to do here
                case ToastNotificationService.SyncAction:
                    NavigationService.Navigate(PageToken.DirectoryList.ToString(), null);
                    break;

                // Open Status Page
                case ToastNotificationService.SyncConflictAction:
                    ToastNotificationManager.History.RemoveGroup(ToastNotificationService.SyncConflictAction);
                    NavigationService.Navigate(PageToken.SyncStatus.ToString(), null);
                    break;
                }
            }
            else
            {
                switch (args.Kind)
                {
                case ActivationKind.Protocol:
                    var protocolArgs = args as ProtocolActivatedEventArgs;

                    if (protocolArgs != null && protocolArgs.Uri.AbsolutePath == "/share")
                    {
                        var pageParameters = new ShareTargetPageParameters()
                        {
                            ActivationKind = ActivationKind.ShareTarget,
                            FileTokens     = new List <string>()
                        };

                        if (protocolArgs.Data.ContainsKey("FileTokens"))
                        {
                            var tokens = protocolArgs.Data["FileTokens"] as string[];
                            if (tokens != null)
                            {
                                foreach (var token in tokens)
                                {
                                    pageParameters.FileTokens.Add(token);
                                }
                            }
                        }

                        CheckSettingsAndContinue(PageToken.ShareTarget, pageParameters);
                    }
                    break;

                case ActivationKind.FileSavePicker:
                case ActivationKind.CachedFileUpdater:
                    CheckSettingsAndContinue(PageToken.FileSavePicker, null);
                    break;

                case ActivationKind.File:
                    if (args is FileActivatedEventArgs activatedEventArgs)
                    {
                        var sorageItems    = activatedEventArgs.Files;
                        var pageParameters = new ShareTargetPageParameters()
                        {
                            //ShareOperation = activatedEventArgs.ShareOperation,
                            ActivationKind = ActivationKind.ShareTarget,
                            FileTokens     = new List <string>()
                        };
                        StorageApplicationPermissions.FutureAccessList.Clear();
                        foreach (var storageItem in sorageItems)
                        {
                            var token = StorageApplicationPermissions.FutureAccessList.Add(storageItem);
                            pageParameters.FileTokens.Add(token);
                        }
                        CheckSettingsAndContinue(PageToken.ShareTarget, pageParameters);
                    }
                    break;
                }
            }
        }
コード例 #37
0
        public static string AddQueryStringVariable(this string Url, string QueryStringPairs)
        {
            // Common variables
            char[] Separator = new char[1];
            string Path;
            string QueryString;
            string NewQueryString = "";

            // Split url into path and querystring
            if (Url.IndexOf("?") > -1)
            {
                Separator[0] = '?';
                string[] UrlParts = Url.Split(Separator, 100);
                Path        = UrlParts[0];
                QueryString = UrlParts[1];
            }
            else
            {
                Path        = Url;
                QueryString = "";
            }

            // Split QueryStrings into pairs
            Separator[0] = '&';
            string[] NewQueryStringPairs = QueryStringPairs.Split(Separator);
            string[] OldQueryStringPairs = QueryString.Split(Separator);

            // Loop through old querystring
            for (int i = 0; i < OldQueryStringPairs.Length; i++)
            {
                // Get name/value pairs
                Separator[0] = '=';
                string[] OldNameValuePair = OldQueryStringPairs[i].Split(Separator);

                // Loop through new querystring looking for same name
                bool PairExists = false;
                for (int j = 0; j < NewQueryStringPairs.Length; j++)
                {
                    // Get name/value pairs
                    string[] NewNameValuePair = NewQueryStringPairs[j].Split(Separator);

                    if (NewNameValuePair[0] == OldNameValuePair[0])
                    {
                        PairExists = true;
                    }
                }

                // Add non-existent pair to new QueryString
                if (!PairExists)
                {
                    NewQueryString += OldQueryStringPairs[i] + "&";
                }
            }

            // Add new querystring
            NewQueryString += QueryStringPairs;

            // Remove leading ampersand (&)
            if (NewQueryString.IndexOf("&") == 0)
            {
                NewQueryString = NewQueryString.Substring(1, NewQueryString.Length - 1);
            }

            // Return new Url
            return(Path + "?" + NewQueryString);
        }
コード例 #38
0
        public override async Task <IEnumerable <T> > GetAllPages <T>(string url, int limit = 50, QueryString query = null)
        {
            var result = new IteratorBasedPage <T>()
            {
                Values = new List <T>()
            };
            IRestResponse <IteratorBasedPage <T> > response = null;

            var request = new BitbucketRestRequest(url, Method.GET);
            var page    = response?.Data?.Next;

            request.AddQueryParameter("pagelen", limit.ToString());

            if (page != null)
            {
                request.AddQueryParameter("page", page);
            }

            if (query != null)
            {
                foreach (var par in query)
                {
                    request.AddQueryParameter(par.Key, par.Value);
                }
            }

            response = await this.ExecuteTaskAsync <IteratorBasedPage <T> >(request);

            if (response.Data?.Values != null)
            {
                result.Values.AddRange(response.Data.Values);
            }


            while (response.Data?.Next != null)
            {
                request  = new BitbucketRestRequest(response.Data.Next, Method.GET);
                response = await this.ExecuteTaskAsync <IteratorBasedPage <T> >(request);

                if (response.Data?.Values != null)
                {
                    result.Values.AddRange(response.Data.Values);
                }
            }

            return(result.Values);
        }
コード例 #39
0
        public void CreateNameValue_Success(string name, string value, string exepcted)
        {
            var query = QueryString.Create(name, value);

            Assert.Equal(exepcted, query.Value);
        }
コード例 #40
0
        private Net.WebRequest Generate(Request r, int retry)
        {
            // need to sign the request
            // we use a method similar to AWS signature version 2 (with a few changes to better support JSON and not sort the qs)
            Net.WebRequest request = null;

            // log id
            r.AddQuery("logid", GenLogId(r, retry));

            // timestamp
            if (Time.Valid)
            {
                r.AddQuery("ts", Time.Now);
            }

            if (retry > 0)
            {
                r.AddQuery("retry", retry);
            }

            if (r.isPost)
            {
                if (r.data.ContainsKey("nonce") == false)
                {
                    r.AddData("nonce", EB.Sparx.Nonce.Generate());
                }
                // post as json
                string json = JSON.Stringify(r.data);
                byte[] body = Encoding.GetBytes(json);

                string sig = Sign(r, "POST", json);
                r.AddQuery("sig", sig);

                Hashtable headers = Johny.HashtablePool.Claim();
                headers["Content-Type"] = "application/json";
                if (!string.IsNullOrEmpty(_cookie))
                {
                    headers["Cookie"] = _cookie;
                }

                EB.Debug.Log("<color=#42fe79>[Post]</color>: " + r.url + "\n" + json);

                request = new Net.WebRequest(r.url, body, headers);
            }
            else
            {
                r.query.Remove("sig");
                string sig = Sign(r, "GET", QueryString.StringifySorted(r.query));
                r.AddQuery("sig", sig);

                EB.Debug.Log("<color=#42fe79>[Get]</color>: " + r.url);

                if (!string.IsNullOrEmpty(_cookie))
                {
                    Hashtable headers = Johny.HashtablePool.Claim();
                    headers["Cookie"] = _cookie;
                    request           = new Net.WebRequest(r.url, headers);
                }
                else
                {
                    request = new Net.WebRequest(r.url);
                }
            }

            request.OnDataCallback = r.dataCallback;
            request.OnHeaders      = r.headersCallback;

            request.Start();
            return(request);
        }
コード例 #41
0
        protected override Result <UserOAuth> Callback(string content)
        {
            //https://graph.qq.com/oauth2.0/token
            //var content = response.Content;
            var result = new Result <UserOAuth>();

            if (content.Contains("callback"))
            {
                var lpos = content.IndexOf('(');
                var rpos = content.IndexOf(')');
                content = content.Substring(lpos + 1, rpos - lpos - 1);

                JToken error;
                var    data = JObject.Parse(content);

                if (data.TryGetValue(ErrorKey, out error))
                {
                    result.Message = error.Value <string>();
                    return(result);
                }
            }

            var param = QueryHelpers.ParseQuery(content);

            var user        = new UserOAuth();
            var accessToken = param[AccessTokenKey];
            var expiresIn   = Convert.ToInt32(param[ExpiresInKey]);

            user.AccessToken  = accessToken;
            user.RefreshToken = param[RefreshTokenKey];
            user.ExpiredOn    = DateTime.Now.AddSeconds(expiresIn);

            if (!string.IsNullOrEmpty(accessToken))
            {
                var qs = QueryString.Create(AccessTokenKey, accessToken).ToString();

                content = Client.GetStringAsync(Provider.UserEndpoint + qs).Result;

                /*
                 * var request = new RestRequest(OAuth.UserInfoResource);
                 * request.AddParameter(AccessTokenKey, accessToken);
                 * content = Client.Execute(request).Content;
                 *
                 * var lpos = content.IndexOf('(');
                 * var rpos = content.IndexOf(')');
                 * content = content.Substring(lpos + 1, rpos - lpos - 1);
                 */
                try
                {
                    JToken error;
                    var    data = JObject.Parse(content);

                    if (data.TryGetValue(ErrorKey, out error))
                    {
                        result.Message = error.Value <string>();
                        return(result);
                    }

                    user.OpenId = data["openid"].Value <string>();

                    result.Data   = user;
                    result.Status = true;
                }
                catch (Exception e)
                {
                    result.Message = e.Message + content;
                }
            }

            return(result);
        }
コード例 #42
0
 public QueryTransformContext(HttpRequest request)
 {
     _request                 = request ?? throw new ArgumentNullException(nameof(request));
     _originalQueryString     = request.QueryString;
     _modifiedQueryParameters = null;
 }
コード例 #43
0
        internal static Mock <HttpRequest> CreateHttpRequestMockObject(PathString path, QueryString queryString,
                                                                       string method)
        {
            var mockObject = new Mock <HttpRequest>();

            mockObject.SetupProperty(x => x.Path, path);
            mockObject.SetupProperty(x => x.QueryString, queryString);
            mockObject.SetupProperty(x => x.Method, method);
            return(mockObject);
        }
コード例 #44
0
 /// <inheritdoc />
 public IAndHttpRequestBuilder WithQueryString(QueryString queryString)
 {
     this.request.QueryString = queryString;
     return(this);
 }
コード例 #45
0
        public override void OnActivated(string arguments, NotificationUserInput userInput, string appUserModelId)
        {
            try
            {
                Application.Current.Dispatcher.Invoke(delegate
                {
                    // Tapping on the top-level header launches with empty args
                    if (arguments.Length == 0)
                    {
                        // Perform a normal launch
                        OpenWindowIfNeeded();
                        return;
                    }

                    // Parse the query string (using NuGet package QueryString.NET)
                    QueryString args = QueryString.Parse(arguments);


                    foreach (var i in args)
                    {
                        if (i.Name == "On")
                        {
                            MainWindow.MBoostBtn.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
                        }
                        else
                        if (i.Name == "Off")
                        {
                            MainWindow.MBoostBtn.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
                        }
                        else
                        if (i.Name == "Close")
                        {
                            Application.Current.MainWindow.Close();
                            Application.Current.Shutdown();
                        }
                    }
                    // See what action is being requested

                    switch (args["action"])
                    {
                    // Open the image

                    /*case "viewImage":
                     *
                     *  // The URL retrieved from the toast args
                     *  string imageUrl = args["imageUrl"];
                     *
                     *  // Make sure we have a window open and in foreground
                     *  OpenWindowIfNeeded();
                     *
                     *  // And then show the image
                     *  (App.Current.Windows[0] as MainWindow).ShowImage(imageUrl);
                     *
                     * break;
                     *
                     * // Background: Quick reply to the conversation
                     * case "reply":
                     *
                     *  // Get the response the user typed
                     *  string msg = userInput["tbReply"];
                     *
                     *  // And send this message
                     *  //SendMessage(msg);
                     *
                     *  // If there's no windows open, exit the app
                     *  if (App.Current.Windows.Count == 0)
                     * {
                     *     Application.Current.Shutdown();
                     * }
                     *
                     * break;*/


                    case "On":
                        //MessageBox.Show("On");
                        break;

                    case "Off":
                        //MessageBox.Show("Off");
                        break;
                    }
                });
            }
            catch (Exception)
            {
            }
        }
コード例 #46
0
        public void ToString_EncodesHash()
        {
            var query = new QueryString("?Hello=Wor#ld");

            Assert.Equal("?Hello=Wor%23ld", query.ToString());
        }
コード例 #47
0
        public async Task <IActionResult> Index(int pageIndex = 1, int maxResults = 5)
        {
            if (User.Identity.IsAuthenticated)
            {
                var userCredentials = await EnsureUserCreated();

                if (userCredentials is null || userCredentials.Role == "Desconosido")
                {
                    return(RedirectToAction("Register", "User"));
                }

                ViewBag.UserId    = userCredentials.Id;
                ViewBag.UserName  = userCredentials.Email.Split("@").First();
                ViewBag.UserRole  = userCredentials.Role;
                ViewBag.UserEmail = userCredentials.Email;
            }

            string currentPage      = (pageIndex < 1) ? "1" : pageIndex.ToString();
            string maxProjectsCount = (maxResults < 5) ? "5" : (maxResults > 100) ? "100" : maxResults.ToString();
            var    queryResult      = new Dictionary <string, string>
            {
                { nameof(pageIndex), currentPage },
                { nameof(maxResults), maxProjectsCount }
            };

            var projects = await CallApiGETAsync <ProjectListVM>(uri : "/api/projects/" + QueryString.Create(queryResult), isSecured : false);

            if (projects == null)
            {
                projects           = new ProjectListVM();
                projects.PageIndex = pageIndex;
            }

            return(View(projects));
        }
コード例 #48
0
        public virtual void ApplyRule(RewriteContext context)
        {
            var   path = context.HttpContext.Request.Path;
            Match initMatchResults;

            if (path == PathString.Empty)
            {
                initMatchResults = InitialMatch.Match(path.ToString());
            }
            else
            {
                initMatchResults = InitialMatch.Match(path.ToString().Substring(1));
            }

            if (initMatchResults.Success)
            {
                var result  = initMatchResults.Result(Replacement);
                var request = context.HttpContext.Request;

                if (StopProcessing)
                {
                    context.Result = RuleResult.SkipRemainingRules;
                }

                if (string.IsNullOrEmpty(result))
                {
                    result = "/";
                }

                if (result.IndexOf("://", StringComparison.Ordinal) >= 0)
                {
                    string         scheme;
                    HostString     host;
                    PathString     pathString;
                    QueryString    query;
                    FragmentString fragment;
                    UriHelper.FromAbsolute(result, out scheme, out host, out pathString, out query, out fragment);

                    request.Scheme      = scheme;
                    request.Host        = host;
                    request.Path        = pathString;
                    request.QueryString = query.Add(request.QueryString);
                }
                else
                {
                    var split = result.IndexOf('?');
                    if (split >= 0)
                    {
                        var newPath = result.Substring(0, split);
                        if (newPath[0] == '/')
                        {
                            request.Path = PathString.FromUriComponent(newPath);
                        }
                        else
                        {
                            request.Path = PathString.FromUriComponent('/' + newPath);
                        }
                        request.QueryString = request.QueryString.Add(
                            QueryString.FromUriComponent(
                                result.Substring(split)));
                    }
                    else
                    {
                        if (result[0] == '/')
                        {
                            request.Path = PathString.FromUriComponent(result);
                        }
                        else
                        {
                            request.Path = PathString.FromUriComponent('/' + result);
                        }
                    }
                }

                context.Logger?.RewrittenRequest(result);
            }
        }
コード例 #49
0
    public override void ApplyAction(RewriteContext context, BackReferenceCollection?ruleBackReferences, BackReferenceCollection?conditionBackReferences)
    {
        var pattern = Url !.Evaluate(context, ruleBackReferences, conditionBackReferences);
        var request = context.HttpContext.Request;

        if (string.IsNullOrEmpty(pattern))
        {
            pattern = "/";
        }

        if (EscapeBackReferences)
        {
            // because escapebackreferences will be encapsulated by the pattern, just escape the pattern
            pattern = Uri.EscapeDataString(pattern);
        }


        // TODO PERF, substrings, object creation, etc.
        if (pattern.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal) >= 0)
        {
            string         scheme;
            HostString     host;
            PathString     path;
            QueryString    query;
            FragmentString fragment;
            UriHelper.FromAbsolute(pattern, out scheme, out host, out path, out query, out fragment);

            if (query.HasValue)
            {
                if (QueryStringAppend)
                {
                    request.QueryString = request.QueryString.Add(query);
                }
                else
                {
                    request.QueryString = query;
                }
            }
            else if (QueryStringDelete)
            {
                request.QueryString = QueryString.Empty;
            }

            request.Scheme = scheme;
            request.Host   = host;
            request.Path   = path;
        }
        else
        {
            var split = pattern.IndexOf('?');
            if (split >= 0)
            {
                var path = pattern.Substring(0, split);
                if (path[0] == '/')
                {
                    request.Path = PathString.FromUriComponent(path);
                }
                else
                {
                    request.Path = PathString.FromUriComponent('/' + path);
                }

                if (QueryStringAppend)
                {
                    request.QueryString = request.QueryString.Add(
                        QueryString.FromUriComponent(
                            pattern.Substring(split)));
                }
                else
                {
                    request.QueryString = QueryString.FromUriComponent(
                        pattern.Substring(split));
                }
            }
            else
            {
                if (pattern[0] == '/')
                {
                    request.Path = PathString.FromUriComponent(pattern);
                }
                else
                {
                    request.Path = PathString.FromUriComponent('/' + pattern);
                }

                if (QueryStringDelete)
                {
                    request.QueryString = QueryString.Empty;
                }
            }
        }
        context.Result = Result;
    }
コード例 #50
0
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie.
            // If it can't be extracted, redirect the user to the login page.
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);

            if (result == null || !result.Succeeded)
            {
                // If the client application requested promptless authentication,
                // return an error indicating that the user is not logged in.
                if (request.HasPrompt(Prompts.None))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                    })));
                }

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // If prompt=login was specified by the client application,
            // immediately return the user agent to the login page.
            if (request.HasPrompt(Prompts.Login))
            {
                // To avoid endless login -> authorization redirects, the prompt=login flag
                // is removed from the authorization request payload before redirecting the user.
                var prompt = string.Join(" ", request.GetPrompts().Remove(Prompts.Login));

                var parameters = Request.HasFormContentType
                    ? Request.Form.Where(parameter => parameter.Key != Parameters.Prompt).ToList()
                    : Request.Query.Where(parameter => parameter.Key != Parameters.Prompt).ToList();

                parameters.Add(KeyValuePair.Create(Parameters.Prompt, new StringValues(prompt)));

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(parameters)
                }));
            }

            // If a max_age parameter was provided, ensure that the cookie is not too old.
            // If it's too old, automatically redirect the user agent to the login page.
            if (request.MaxAge != null && result.Properties?.IssuedUtc != null &&
                DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))
            {
                if (request.HasPrompt(Prompts.None))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                    })));
                }

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // Retrieve the profile of the logged in user.
            var user = await _userManager.GetUserAsync(result.Principal) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

            // Retrieve the permanent authorizations associated with the user and the calling client application.
            var authorizations = await _authorizationManager.FindAsync(
                subject : await _userManager.GetUserIdAsync(user),
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            // If the consent is external (e.g when authorizations are granted by a sysadmin),
            // immediately return an error if no authorization can be found in the database.
            case ConsentTypes.External when !authorizations.Any():
                return(Forbid(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "The logged in user is not allowed to access this client application."
                })));

            // If the consent is implicit or if an authorization was found,
            // return an authorization response without displaying the consent form.
            case ConsentTypes.Implicit:
            case ConsentTypes.External when authorizations.Any():
            case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
                var principal = await _signInManager.CreateUserPrincipalAsync(user);

                // Note: in this sample, the granted scopes match the requested scope
                // but you may want to allow the user to uncheck specific scopes.
                // For that, simply restrict the list of scopes before calling SetScopes.
                principal.SetScopes(request.GetScopes());
                principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());

                // Automatically create a permanent authorization to avoid requiring explicit consent
                // for future authorization or token requests containing the same scopes.
                var authorization = authorizations.LastOrDefault();
                if (authorization == null)
                {
                    authorization = await _authorizationManager.CreateAsync(
                        principal : principal,
                        subject : await _userManager.GetUserIdAsync(user),
                        client : await _applicationManager.GetIdAsync(application),
                        type : AuthorizationTypes.Permanent,
                        scopes : principal.GetScopes());
                }

                principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

            // At this point, no authorization was found in the database and an error must be returned
            // if the client application specified prompt=none in the authorization request.
            case ConsentTypes.Explicit when request.HasPrompt(Prompts.None):
            case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):
                return(Forbid(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "Interactive user consent is required."
                })));

            // In every other case, render the consent form.
            default:
                return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                    Scope = request.Scope
                }));
            }
        }
コード例 #51
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                // Global Authorize Filter
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddRazorPages();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Events = new CookieAuthenticationEvents
                {
                    OnSigningOut = context =>
                    {
                        // Single Sign-Out
                        var casUrl      = new Uri(Configuration["Authentication:CAS:ServerUrlBase"]);
                        var links       = context.HttpContext.RequestServices.GetRequiredService <LinkGenerator>();
                        var serviceUrl  = links.GetUriByPage(context.HttpContext, "/Index");
                        var redirectUri = UriHelper.BuildAbsolute(
                            casUrl.Scheme,
                            new HostString(casUrl.Host, casUrl.Port),
                            casUrl.LocalPath, "/logout",
                            QueryString.Create("service", serviceUrl));

                        var logoutRedirectContext = new RedirectContext <CookieAuthenticationOptions>(
                            context.HttpContext,
                            context.Scheme,
                            context.Options,
                            context.Properties,
                            redirectUri
                            );
                        context.Response.StatusCode = 204; //Prevent RedirectToReturnUrl
                        context.Options.Events.RedirectToLogout(logoutRedirectContext);
                        return(Task.CompletedTask);
                    }
                };
            })
            .AddCAS(options =>
            {
                options.CasServerUrlBase = Configuration["Authentication:CAS:ServerUrlBase"];
                var protocolVersion      = Configuration.GetValue("Authentication:CAS:ProtocolVersion", 3);
                if (protocolVersion != 3)
                {
                    switch (protocolVersion)
                    {
                    case 1:
                        options.ServiceTicketValidator = new Cas10ServiceTicketValidator(options);
                        break;

                    case 2:
                        options.ServiceTicketValidator = new Cas20ServiceTicketValidator(options);
                        break;
                    }
                }
                options.Events = new CasEvents
                {
                    OnCreatingTicket = context =>
                    {
                        var assertion = context.Assertion;
                        if (assertion == null)
                        {
                            return(Task.CompletedTask);
                        }
                        if (!(context.Principal.Identity is ClaimsIdentity identity))
                        {
                            return(Task.CompletedTask);
                        }
                        // Map claims from assertion
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, assertion.PrincipalName));
                        if (assertion.Attributes.TryGetValue("display_name", out var displayName))
                        {
                            identity.AddClaim(new Claim(ClaimTypes.Name, displayName));
                        }
                        if (assertion.Attributes.TryGetValue("email", out var email))
                        {
                            identity.AddClaim(new Claim(ClaimTypes.Email, email));
                        }
                        return(Task.CompletedTask);
                    },
                    OnRemoteFailure = context =>
                    {
                        var failure = context.Failure;
                        var logger  = context.HttpContext.RequestServices.GetRequiredService <ILogger <CasEvents> >();
                        logger.LogError(failure, failure.Message);
                        context.Response.Redirect("/Account/ExternalLoginFailure");
                        context.HandleResponse();
                        return(Task.CompletedTask);
                    }
                };
            })
            .AddOAuth(OAuthDefaults.DisplayName, options =>
            {
                options.CallbackPath            = "/signin-oauth";
                options.ClientId                = Configuration["Authentication:OAuth:ClientId"];
                options.ClientSecret            = Configuration["Authentication:OAuth:ClientSecret"];
                options.AuthorizationEndpoint   = Configuration["Authentication:OAuth:AuthorizationEndpoint"];
                options.TokenEndpoint           = Configuration["Authentication:OAuth:TokenEndpoint"];
                options.UserInformationEndpoint = Configuration["Authentication:OAuth:UserInformationEndpoint"];
                options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                options.ClaimActions.MapJsonSubKey(ClaimTypes.Name, "attributes", "display_name");
                options.ClaimActions.MapJsonSubKey(ClaimTypes.Email, "attributes", "email");
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        // Get the OAuth user
                        using var request =
                                  new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", context.AccessToken);
                        using var response =
                                  await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted)
                                  .ConfigureAwait(false);

                        if (!response.IsSuccessStatusCode ||
                            response.Content?.Headers?.ContentType?.MediaType.StartsWith("application/json") != true)
                        {
                            throw new HttpRequestException(
                                $"An error occurred when retrieving OAuth user information ({response.StatusCode}). Please check if the authentication information is correct.");
                        }

                        await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
                        using var json         = await JsonDocument.ParseAsync(stream).ConfigureAwait(false);
                        context.RunClaimActions(json.RootElement);
                    },
                    OnRemoteFailure = context =>
                    {
                        var failure = context.Failure;
                        var logger  = context.HttpContext.RequestServices.GetRequiredService <ILogger <OAuthEvents> >();
                        logger.LogError(failure, failure.Message);
                        context.Response.Redirect("/Account/ExternalLoginFailure");
                        context.HandleResponse();
                        return(Task.CompletedTask);
                    }
                };
            });
コード例 #52
0
ファイル: App.xaml.cs プロジェクト: kallistam/Roamit
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            Debug.WriteLine("Activated.");

            Frame rootFrame = Window.Current.Content as Frame;

            bool isJustLaunched = (rootFrame == null);

            if (e is ToastNotificationActivatedEventArgs)
            {
                var toastActivationArgs = e as ToastNotificationActivatedEventArgs;

                // Parse the query string
                QueryString args = QueryString.Parse(toastActivationArgs.Argument);

                if (!args.Contains("action"))
                {
                    LaunchRootFrameIfNecessary(ref rootFrame, true);
                    return;
                }

                HistoryRow hr;
                switch (args["action"])
                {
                case "cloudClipboard":
                    LaunchRootFrameIfNecessary(ref rootFrame, false);
                    rootFrame.Navigate(typeof(ClipboardReceive), "CLOUD_CLIPBOARD");
                    break;

                case "clipboardReceive":
                    LaunchRootFrameIfNecessary(ref rootFrame, false);
                    rootFrame.Navigate(typeof(ClipboardReceive), args["guid"]);
                    break;

                case "fileProgress":
                    LaunchRootFrameIfNecessary(ref rootFrame, false);
                    if (rootFrame.Content is MainPage)
                    {
                        break;
                    }
                    rootFrame.Navigate(typeof(MainPage));
                    break;

                case "fileFinished":
                    LaunchRootFrameIfNecessary(ref rootFrame, false);
                    if (rootFrame.Content is MainPage)
                    {
                        break;
                    }
                    rootFrame.Navigate(typeof(MainPage), "history");
                    break;

                case "openFolder":
                    hr = await GetHistoryItemGuid(Guid.Parse(args["guid"]));

                    await LaunchOperations.LaunchFolderFromPathAsync((hr.Data as ReceivedFileCollection).StoreRootPath);

                    if (isJustLaunched)
                    {
                        Application.Current.Exit();
                    }
                    break;

                case "openFolderSingleFile":
                    hr = await GetHistoryItemGuid(Guid.Parse(args["guid"]));

                    await LaunchOperations.LaunchFolderFromPathAndSelectSingleItemAsync((hr.Data as ReceivedFileCollection).Files[0].StorePath, (hr.Data as ReceivedFileCollection).Files[0].Name);

                    if (isJustLaunched)
                    {
                        Application.Current.Exit();
                    }
                    break;

                case "openSingleFile":
                    hr = await GetHistoryItemGuid(Guid.Parse(args["guid"]));

                    await LaunchOperations.LaunchFileFromPathAsync((hr.Data as ReceivedFileCollection).Files[0].StorePath, (hr.Data as ReceivedFileCollection).Files[0].Name);

                    if (isJustLaunched)
                    {
                        Application.Current.Exit();
                    }
                    break;

                case "saveAsSingleFile":
                case "saveAs":
                    LaunchRootFrameIfNecessary(ref rootFrame, false);
                    rootFrame.Navigate(typeof(ProgressPage));
                    var guid = Guid.Parse(args["guid"]);
                    await ReceivedSaveAsHelper.SaveAs(guid);

                    if ((isJustLaunched) || (DeviceInfo.FormFactorType != DeviceInfo.DeviceFormFactorType.Desktop))
                    {
                        Application.Current.Exit();
                    }
                    else
                    {
                        rootFrame.GoBack();
                    }
                    break;

                default:
                    LaunchRootFrameIfNecessary(ref rootFrame, true);
                    break;
                }
            }
            else if (e.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs pEventArgs = e as ProtocolActivatedEventArgs;

                if ((pEventArgs.Uri.AbsoluteUri.ToLower() == "roamit://wake") || (pEventArgs.Uri.AbsoluteUri.ToLower() == "roamit://wake/"))
                {
                    Debug.WriteLine("Wake request received");
                    Application.Current.Exit();
                }
                else
                {
                    string clipboardData   = ParseFastClipboardUri(pEventArgs.Uri.AbsoluteUri);
                    string launchUriData   = ParseLaunchUri(pEventArgs.Uri.AbsoluteUri);
                    bool   isSettings      = ParseSettings(pEventArgs.Uri.AbsoluteUri);
                    bool   isReceiveDialog = ParseReceive(pEventArgs.Uri.AbsoluteUri);

                    if (isSettings)
                    {
                        if (rootFrame == null)
                        {
                            LaunchRootFrameIfNecessary(ref rootFrame, false);
                        }
                        rootFrame.Navigate(typeof(MainPage), "settings");
                    }
                    else if (isReceiveDialog)
                    {
                        if (rootFrame == null)
                        {
                            LaunchRootFrameIfNecessary(ref rootFrame, false);
                        }
                        rootFrame.Navigate(typeof(MainPage), "receiveDialog");
                    }
                    else if (clipboardData.Length > 0)
                    {
                        string[] parts = clipboardData.Split('?');
                        var      guid  = await TextReceiver.QuickTextReceivedAsync(parts[0].DecodeBase64(), parts[1].DecodeBase64());

                        LaunchRootFrameIfNecessary(ref rootFrame, false);
                        rootFrame.Navigate(typeof(ClipboardReceive), guid.ToString());
                    }
                    else if (launchUriData.Length > 0)
                    {
#if !DEBUG
                        App.Tracker.Send(HitBuilder.CreateCustomEvent("ExtensionCalled", "").Build());
#endif

                        string type = ExternalContentHelper.SetUriData(new Uri(launchUriData.DecodeBase64()));

                        SendDataTemporaryStorage.IsSharingTarget = true;

                        if (rootFrame == null)
                        {
                            LaunchRootFrameIfNecessary(ref rootFrame, false);
                            rootFrame.Navigate(typeof(MainPage), new ShareTargetDetails
                            {
                                Type = type,
                            });
                        }
                        else
                        {
                            MainPage.Current.BeTheShareTarget(new ShareTargetDetails
                            {
                                Type = type,
                            });
                        }
                    }
                    else
                    {
                        LaunchRootFrameIfNecessary(ref rootFrame, true);
                    }
                }
            }
            else
            {
                LaunchRootFrameIfNecessary(ref rootFrame, true);
            }

            base.OnActivated(e);
        }
        public ApplicationControllerTests()
        {
            defaultAppRegistryDataService = A.Fake <IAppRegistryDataService>();
            defaultMapper             = new ApplicationToPageModelMapper(defaultAppRegistryDataService);
            defaultLogger             = A.Fake <ILogger <ApplicationController> >();
            defaultApplicationService = A.Fake <IApplicationService>();
            defaultVersionedFiles     = A.Fake <IVersionedFiles>();
            defaultConfiguration      = A.Fake <IConfiguration>();
            defaultBaseUrlService     = A.Fake <IBaseUrlService>();
            neo4JService = A.Fake <INeo4JService>();

            defaultApplicationModel = new ApplicationModel
            {
                AppRegistrationModel = new AppRegistrationModel
                {
                    Path    = ChildAppPath,
                    Regions = new List <RegionModel>
                    {
                        new RegionModel
                        {
                            IsHealthy      = true,
                            PageRegion     = PageRegion.Body,
                            RegionEndpoint = "http://childApp/bodyRegion",
                        },
                    },
                },
            };
            defaultPostRequestViewModel = new ActionPostRequestModel
            {
                Path           = ChildAppPath,
                Data           = ChildAppData,
                FormCollection = new FormCollection(new Dictionary <string, StringValues>
                {
                    { "someKey", "someFormValue" },
                }),
            };
            childAppActionGetRequestModel = defaultPostRequestViewModel;
            A.CallTo(() => defaultApplicationService.GetApplicationAsync(childAppActionGetRequestModel)).Returns(defaultApplicationModel);

            var fakeHttpContext = new DefaultHttpContext {
                Request = { QueryString = QueryString.Create("test", "testvalue") }
            };

            defaultGetController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = fakeHttpContext,
                },
            };

            defaultPostController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        Request = { Method = "POST" },
                    },
                },
            };

            bearerTokenController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext {
                        User = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                            new Claim("bearer", "test")
                        }, "mock"))
                    },
                },
            };

            postBearerTokenController = new ApplicationController(defaultMapper, defaultLogger, defaultApplicationService, defaultVersionedFiles, defaultConfiguration, defaultBaseUrlService, neo4JService)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext {
                        User = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                            new Claim("bearer", "test")
                        }, "mock"))
                    },
                },
            };
        }
コード例 #54
0
 public HttpRequestMock WithQueryString(QueryString queryString)
 {
     RealInstance.QueryString = queryString;
     return(this);
 }
コード例 #55
0
        public async Task LoginOauth()
        {
            if (string.IsNullOrEmpty(Server))
            {
                return;
            }
            IsLoading = true;
            try
            {
                var appRegistration = await GetAppRegistration();

                var authClient = new AuthenticationClient(appRegistration);
                var oauthUrl   = authClient.OAuthUrl((string.Format(_serverRedirect, Server)));
                var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    new Uri(oauthUrl),
                    new System.Uri(string.Format(_serverRedirect, Server)));

                string result;
                string code = "";
                switch (webAuthenticationResult.ResponseStatus)
                {
                case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
                    // Successful authentication.
                    result = webAuthenticationResult.ResponseData.ToString();
                    var query    = QueryString.Parse(result);
                    var testCode = query.FirstOrDefault();
                    code = testCode?.Value;
                    break;

                case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
                    // HTTP error.
                    result = webAuthenticationResult.ResponseErrorDetail.ToString();
                    break;

                default:
                    // Other error.
                    result = webAuthenticationResult.ResponseData.ToString();
                    break;
                }

                if (string.IsNullOrEmpty(code))
                {
                    // TODO Add error screen
                }
                else
                {
                    var auth = await authClient.ConnectWithCode(code, string.Format(_serverRedirect, Server));

                    SettingsService.UserAuth = auth;
                    var client  = new MastodonClient(appRegistration, auth);
                    var account = await client.GetCurrentUser();

                    SettingsService.UserAccount             = account;
                    SettingsService.Instance.ServerInstance = Server;
                    IsLoggedIn = true;

                    if (App.IsTenFoot)
                    {
                        // NavigationService.Navigate(typeof(XboxViews.MainPage));
                    }
                    else
                    {
                        Views.Shell.Instance.ViewModel.IsLoggedIn = true;
                        NavigationService.Navigate(typeof(Views.MainPage));
                    }
                }
            }
            catch (Exception e)
            {
                await MessageDialogMaker.SendMessageDialogAsync(e.Message, false);
            }

            //var authUri = $"https://{Server}/oauth/authorize?response_type=code&client_id="

            IsLoading = false;
        }
コード例 #56
0
ファイル: UrlUtils.cs プロジェクト: akhumzi/bundling
        public static void FromRelative(string url, out PathString path, out QueryString query, out FragmentString fragment)
        {
            var uri = new Uri(s_dummyBaseUri, url);

            UriHelper.FromAbsolute(uri.ToString(), out _, out _, out path, out query, out fragment);
        }
コード例 #57
0
ファイル: App.xaml.cs プロジェクト: howardpaget/Doroish
        /* Write the note to a files dated yyyy-MM-dd.
         * Perform any http request secified in config.json. */
        protected override async void OnActivated(IActivatedEventArgs e)
        {
            if (e is ToastNotificationActivatedEventArgs)
            {
                var configFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("config.json", CreationCollisionOption.OpenIfExists);

                if (configFile != null)
                {
                    try {
                        var jsonConfigString = await FileIO.ReadTextAsync(configFile);

                        if (string.IsNullOrWhiteSpace(jsonConfigString))
                        {
                            jsonConfigString = "{}";
                        }

                        JObject jsonConfig = JObject.Parse(jsonConfigString);

                        StorageFolder docs;
                        if (jsonConfig["notes_folder"] == null)
                        {
                            docs = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Doroish", CreationCollisionOption.OpenIfExists);
                        }
                        else
                        {
                            docs = await StorageFolder.GetFolderFromPathAsync(jsonConfig["notes_folder"].ToString());

                            if (docs == null)
                            {
                                docs = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Doroish", CreationCollisionOption.OpenIfExists);
                            }
                        }

                        StorageFile output = await docs.CreateFileAsync(DateTime.Now.ToString("yyyy-MM-dd") + ".txt", CreationCollisionOption.OpenIfExists);

                        var ev   = e as ToastNotificationActivatedEventArgs;
                        var args = QueryString.Parse(ev.Argument);

                        if (!ev.UserInput.ContainsKey("tbNote"))
                        {
                            return;
                        }

                        List <string> lines = new List <string>()
                        {
                            DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " - " + args["dorotitle"] + ":",
                            "", ev.UserInput["tbNote"].ToString(), "", ""
                        };
                        await FileIO.AppendLinesAsync(output, lines);

                        if (jsonConfig["requests"] != null)
                        {
                            var requests = jsonConfig["requests"] as JArray;
                            foreach (var request in requests)
                            {
                                if (request["method"].ToString() == "POST")
                                {
                                    using (var client = new HttpClient()) {
                                        var content = new StringContent(string.Format(request["body"].ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm"), args["dorotitle"], ev.UserInput["tbNote"].ToString()));

                                        var response = await client.PostAsync(request["body"].ToString(), content);

                                        var responseString = await response.Content.ReadAsStringAsync();
                                    }
                                }

                                if (request["method"].ToString() == "GET")
                                {
                                    using (var client = new HttpClient()) {
                                        var url = string.Format(request["url"].ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm"), args["dorotitle"], ev.UserInput["tbNote"].ToString());

                                        var response = await client.GetAsync(url);

                                        var responseString = await response.Content.ReadAsStringAsync();
                                    }
                                }
                            }
                        }
                    } catch {
                        //var dialog = new MessageDialog("There was an error in the config.json file." + ex.Message);
                        //await dialog.ShowAsync();
                    }
                }
            }
        }
コード例 #58
0
 private string getName()
 {
     return(QueryString.Contains("name")
        ? QueryString["name"]
        : "");//"anon#" + getNum();
 }
コード例 #59
0
 public Task <T> GetAsync <T>(string route, QueryString queryString = null, Func <string, T> customDeserialization = null)
 {
     return(Task.FromResult(default(T)));
 }
コード例 #60
0
 /// <summary>
 /// Convert this <paramref name="queryString"/>-formatted string to a <see cref="QueryString"/>
 /// instance.
 /// </summary>
 /// <param name="queryString">The query string-formatted string to convert.</param>
 /// <returns>A <see cref="QueryString"/> based on this <paramref name="queryString"/>.</returns>
 public static QueryString ToQueryString(this string queryString)
 => QueryString.Parse(queryString);