Example #1
0
        private void save_button_Click(object sender, RoutedEventArgs e)
        {
            HttpQuery query = new HttpQuery();
            //query.RequestCookies.Add(ClientSession.SessionCookie);
            Json json = new Json();

            json["username"] = textbox_username.Text;
            json["password"] = textbox_password.Password;
            json["nickname"] = textbox_nickname.Text;
            json["email"]    = textbox_email.Text;
            json["phone"]    = textbox_phone.Text;
            try
            {
                var response = Json.Decode(query.Post(ClientConfig.ServerUrl + "user/registe", json.Encode()));
                if (response["status"] == 0)
                {
                    MessageBox.Show("注册成功!");

                    this.Close();
                }
                else
                {
                    MessageBox.Show(response["error"], "注册失败!");
                }
            }
            catch
            {
                MessageBox.Show("注册失败!");
            }
        }
        /// <summary>
        /// Retrieves a list of achievements and the completion a subject has towards the achievements. The returned list will also contain earned achievement records when present.
        /// </summary>
        /// <param name="subjectId">Unique subject the progress is associated with</param>
        /// <param name="includeAchievements">Include related achievements</param>
        /// <param name="includeCriteria">Include related criteria</param>
        /// <param name="includeAwards">Include related awards</param>
        /// <returns></returns>
        public Task <List <Progress> > GetProgress(string subjectId, bool includeAchievements = false, bool includeCriteria = false, bool includeAwards = false)
        {
            var query = new HttpQuery();

            query.Add("subject", subjectId);

            //Including criteria or awards requires also including achievements
            if (includeAwards || includeCriteria)
            {
                includeAchievements = true;
            }
            if (includeAchievements)
            {
                query.Add("include", "achievement");
            }
            if (includeCriteria)
            {
                query.Add("include", "criterion");
            }
            if (includeAwards)
            {
                query.Add("include", "award");
            }
            return(this.m_httpClient.GetAll <Progress>(ENDPOINT, query: query.ToString()));
        }
        /// <summary>
        /// SpeechRecognizerState HTTP query handler
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private IEnumerator <ITask> SpeechRecognizerStateHttpQueryHandler(HttpQuery query)
        {
            // Send SpeechRecognizerStateQuery message to own service
            SpeechRecognizerStateQuery srStateQuery = new SpeechRecognizerStateQuery();

            _mainPort.Post(srStateQuery);

            DsspResponsePort <sr.SpeechRecognizerState> srStateResponse = srStateQuery.ResponsePort;

            yield return((Choice)srStateResponse);

            Fault srStateFault = (Fault)srStateResponse;

            if (srStateFault != null)
            {
                LogError(srStateFault);
                query.ResponsePort.Post(new HttpResponseType(
                                            HttpStatusCode.InternalServerError,
                                            srStateFault
                                            ));
                yield break;
            }

            // Return SpeechRecognizerStateQuery result
            query.ResponsePort.Post(new HttpResponseType(
                                        HttpStatusCode.OK,
                                        (sr.SpeechRecognizerState)srStateResponse
                                        ));
            yield break;
        }
Example #4
0
        static bool InsertHttpAttack(MySqlCommand cmd, ulong countryId, HttpAttack item)
        {
            lock (cmd)
            {
                HttpQuery d = new HttpQuery()
                {
                    Post = item.Post,
                    Get  = item.Get
                };

                string query = JsonHelper.Serialize(d);
                string url   = NotNull(item.HttpUrl);
                string host  = NotNull(item.HttpHost);
                string crc   = HashHelper.HashHex(HashHelper.EHashType.Md5, host + "\n" + url + "\n" + query);

                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("HOST", countryId);
                cmd.Parameters.AddWithValue("PORT", item.Port);
                cmd.Parameters.AddWithValue("TYPE", item.Type.ToString());
                cmd.Parameters.AddWithValue("DATE", item.Date.Substring(0, 10));
                cmd.Parameters.AddWithValue("HOUR", item.Date.Substring(11, 5));
                cmd.Parameters.AddWithValue("HTTP_QUERY", query);
                cmd.Parameters.AddWithValue("HTTP_URL", url);
                cmd.Parameters.AddWithValue("HTTP_HOST", host);
                cmd.Parameters.AddWithValue("HTTP_CRC", crc);
                cmd.CommandText = "INSERT IGNORE INTO attacks_http(HOST,PORT,TYPE,DATE,HOUR,HTTP_HOST,HTTP_URL,HTTP_QUERY,HTTP_CRC)VALUES(@HOST,@PORT,@TYPE,@DATE,@HOUR,@HTTP_HOST,@HTTP_URL,@HTTP_QUERY,@HTTP_CRC);";
                cmd.ExecuteNonQuery();
                return(true);
            }
        }
Example #5
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            HttpQuery query = new HttpQuery();
            //query.RequestCookies.Add(ClientSession.SessionCookie);
            Json json = new Json();

            json["username"] = textUserName.Text;
            json["password"] = textPassWord.Password;
            try
            {
                var response = Json.Decode(query.Post(ClientConfig.ServerUrl + "user/checkLogin", json.Encode()));
                if (response["status"] == 0)
                {
                    ClientSession.user_info     = response["info"]["user_info"].ConvertTo <UserInfo>();
                    ClientSession.SessionCookie = query.ResponseCookies[0];

                    var main = new Main();
                    main.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show(response["error"], "登录失败!");
                }
            }
            catch
            {
                MessageBox.Show("登录失败!");
            }
        }
Example #6
0
        public void OnHttpQuery(HttpQuery query)
        {
            string session = query.Body.Query["Session"];

            if (string.IsNullOrEmpty(session))
            {
                query.ResponsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state, _transform));
                return;
            }

            if (!_waitingNotifications.ContainsKey(session))
            {
                _waitingNotifications.Add(session, new Queue <DsspOperation>());
            }

            Queue <DsspOperation> queue = _waitingNotifications[session];
            HttpNotification      notification;

            if (queue.Count == 0)
            {
                notification           = new HttpNotification();
                notification.Operation = "None";
            }
            else
            {
                DsspOperation operation = queue.Dequeue();
                notification = HttpNotification.FromOperation(operation);
            }

            query.ResponsePort.Post(new HttpResponseType(notification));
        }
Example #7
0
        public static bool SendSMS()
        {
            var http = new HttpQuery();

            http.timeout = 120;
            http.Post(serverAddress + "tickers/sendSms", "");
            return(true);
        }
Example #8
0
        public static bool ReceiveMail()
        {
            var http = new HttpQuery();

            http.timeout = 120;
            http.Post(serverAddress + "tickers/receiveMail", "");
            return(true);
        }
 public void DepthCamHttpQueryHandler(HttpQuery query)
 {
     this.RedirectHttpRequest(
         depthcam.Contract.Identifier,
         this.depthCamPartner,
         query.Body.Context,
         query.ResponsePort);
 }
        /// <summary>
        /// Executes the <see cref="HttpQuery"/> asynchronously and returns the corresponding <see cref="HttpAnswer"/>
        /// </summary>
        /// <param name="query"><see cref="HttpQuery"/> to execute</param>
        /// <returns></returns>
        public static async Task <HttpAnswer> ExecuteAsync(HttpQuery query)
        {
            HttpResponseMessage response = await client.GetAsync(query.Uri);

            string html = await response.Content.ReadAsStringAsync();

            return(new HttpAnswer(html, ExtractHtmlTitle(html), response.StatusCode));
        }
Example #11
0
        public void ToString_UrlEncodesParameterKeysAndValues()
        {
            var query = new HttpQuery();

            query.Add("key 1", "value 1");

            Assert.Equal("key%201=value%201", query.ToString());
        }
Example #12
0
        public void ToString_UrlEncodesEmojiAndUnicodeKeysAndValues()
        {
            var query = new HttpQuery();

            query.Add("🔥key🔥", "тест 🔥value🔥 тест");

            Assert.Equal("%F0%9F%94%A5key%F0%9F%94%A5=%D1%82%D0%B5%D1%81%D1%82%20%F0%9F%94%A5value%F0%9F%94%A5%20%D1%82%D0%B5%D1%81%D1%82", query.ToString());
        }
Example #13
0
        public void ToString_UrlEncodesSpecialSymbolsInKeysAndValues()
        {
            var query = new HttpQuery();

            query.Add("key=", "value=");

            Assert.Equal("key%3D=value%3D", query.ToString());
        }
Example #14
0
        public static bool AddMessage()
        {
            var http = new HttpQuery();

            http.timeout = 120;
            http.Post(serverAddress + "tickers/addMessage", "");
            return(true);
        }
 public IEnumerator <ITask> OnWebcamHttpQuery(HttpQuery query)
 {
     return(this.webCamPort.HttpQueryHelper(
                query,
                this.webCamState,
                this.webCamTransform,
                this.utilitiesPort));
 }
Example #16
0
 /// <summary>
 /// Cancel the HTTP query specified and set its reference to null,
 /// if needed.
 /// </summary>
 protected void ClearHttpQuery(ref HttpQuery query)
 {
     if (query != null)
     {
         query.Cancel();
         query = null;
     }
 }
Example #17
0
        public void MultipleParameterPairs_ToString_ConcatenatesPairs()
        {
            var query = new HttpQuery();

            query.Add("key1", "value1");
            query.Add("key2", "value2");

            Assert.Equal("key1=value1&key2=value2", query.ToString());
        }
Example #18
0
        public void MultipleParameterPairs_ToString_DoesntProduceTrailingAmpersand()
        {
            var query = new HttpQuery();

            query.Add("key1", "value1");
            query.Add("key2", "value2");

            Assert.False(query.ToString().EndsWith("&"));
        }
Example #19
0
 /// <summary>
 /// Updates one navigation control at a time with the related <see cref="HttpQuery"/>
 /// </summary>
 /// <param name="navigationControl">Either the backward or the forward <see cref="Button"/></param>
 /// <param name="query">Current corresponding <see cref="HttpQuery"/> or null</param>
 private void UpdateNavigationControls(Button navigationControl, HttpQuery query)
 {
     navigationControl.Enabled = query != null;
     if (query != null)
     {
         this.generatedToolTips.Add(new ToolTip());
         this.generatedToolTips[this.generatedToolTips.Count - 1]
         .SetToolTip(navigationControl, query.Title);
     }
 }
        /// <summary>
        /// Handlers http query request for raw binary format.
        /// </summary>
        /// <param name="query">The http query</param>
        /// <param name="state">Depth camera state</param>
        /// <param name="transform"> XSLT transform to be applied</param>
        /// <param name="utilitiesPort">Utitilise port to post the response</param>
        /// <returns>CCR Task Chunk</returns>
        private static IEnumerator <ITask> HttpQueryHelperRawFormat(
            HttpQuery query,
            DepthCamSensorState state,
            string transform,
            DsspHttpUtilitiesPort utilitiesPort)
        {
            var type = query.Body.Query[QueryType];

            byte[] imageByteArray = null;
            switch (type.ToLowerInvariant())
            {
            case DepthPlusRgb:
                imageByteArray =
                    ConvertVisibleAndDepthToByteArray(
                        state.VisibleImage,
                        state.DepthImage);
                break;

            case Rgb:
                imageByteArray = state.VisibleImage;
                break;

            case Depth:
                imageByteArray = new byte[state.DepthImage.Length * sizeof(short)];
                Buffer.BlockCopy(state.DepthImage, 0, imageByteArray, 0, imageByteArray.Length);
                break;

            case Ir:
                imageByteArray = state.VisibleImage;
                break;
            }

            if (imageByteArray == null)
            {
                query.ResponsePort.Post(
                    new HttpResponseType(
                        HttpStatusCode.OK,
                        state,
                        transform));
            }
            else
            {
                using (var mem = new MemoryStream(imageByteArray))
                {
                    var response = new WriteResponseFromStream(
                        query.Body.Context,
                        mem,
                        OctetStream);
                    utilitiesPort.Post(response);

                    yield return(response.ResultPort.Choice());
                }
            }
        }
 /// <summary>
 /// Add an <see cref="HttpQuery"/> to history
 /// </summary>
 /// <param name="entry"></param>
 /// <exception cref="ArgumentNullException">When the provided <see cref="HttpQuery"/> is <see cref="null"/></exception>
 /// <exception cref="EntryDoesntExistException">When the provided <see cref="HttpQuery"/> already exists in the history</exception>
 public void Add(HttpQuery entry)
 {
     if (entry == null)
     {
         throw new ArgumentNullException();
     }
     if (this.entries.Keys.Contains(entry.TimestampIssuedAt))
     {
         throw new EntryAlreadyExistsException();
     }
     this.entries.Add(entry.TimestampIssuedAt, entry);
 }
Example #22
0
        /// <summary>
        /// Submit the Freemium web query.
        /// </summary>
        private void SubmitHttpQuery()
        {
            String ws_url      = "https://" + KpsAddr + "/freemium/registration";
            String email       = HttpUtility.UrlEncode(KpsUserName);
            String pwd         = HttpUtility.UrlEncode(KpsUserPwd);
            String post_params = "email=" + email + "&pwd=" + pwd;

            m_httpQuery                   = new HttpQuery(new Uri(ws_url + "?" + post_params));
            m_httpQuery.UseCache          = false;
            m_httpQuery.OnHttpQueryEvent += HandleHttpQueryResult;
            m_httpQuery.StartQuery();
        }
Example #23
0
        static bool Prefix(
            ref bool __state,
            string reporterUserId,
            string reportedUserId,
            string reason,
            ref int reportedId,
            string reporterNickname,
            string reportedNickname,
            bool friendlyFire)
        {
            try
            {
                string pings = "";

                foreach (string s in ReportPing.Instance.Config.RoleId)
                {
                    pings += $"<@&{s}> ";
                }

                pings = Uri.EscapeDataString(pings);

                string payload = JsonSerializer.ToJsonString <DiscordWebhook>(new DiscordWebhook(
                                                                                  pings, CheaterReport.WebhookUsername,
                                                                                  CheaterReport.WebhookAvatar, false, new DiscordEmbed[1]
                {
                    new DiscordEmbed(CheaterReport.ReportHeader, "rich", CheaterReport.ReportContent,
                                     CheaterReport.WebhookColor, new DiscordEmbedField[10]
                    {
                        new DiscordEmbedField("Server Name", CheaterReport.ServerName, false),
                        new DiscordEmbedField("Server Endpoint", string.Format("{0}:{1}", (object)ServerConsole.Ip, (object)ServerConsole.Port), false),
                        new DiscordEmbedField("Reporter UserID", CheaterReport.AsDiscordCode(reporterUserId), false),
                        new DiscordEmbedField("Reporter Nickname", CheaterReport.DiscordSanitize(reporterNickname), false),
                        new DiscordEmbedField("Reported UserID", CheaterReport.AsDiscordCode(reportedUserId), false),
                        new DiscordEmbedField("Reported Nickname", CheaterReport.DiscordSanitize(reportedNickname), false),
                        new DiscordEmbedField("Reported ID", reportedId.ToString(), false),
                        new DiscordEmbedField("Reason", CheaterReport.DiscordSanitize(reason), false),
                        new DiscordEmbedField("Timestamp", TimeBehaviour.Rfc3339Time(), false),
                        new DiscordEmbedField("UTC Timestamp", TimeBehaviour.Rfc3339Time(DateTimeOffset.UtcNow), false)
                    })
                }));
                HttpQuery.Post(friendlyFire ? FriendlyFireConfig.WebhookUrl : CheaterReport.WebhookUrl, "payload_json=" + payload);
                __state = true;
            }
            catch (Exception ex)
            {
                ServerConsole.AddLog("Failed to send report by webhook: " + ex.Message, ConsoleColor.Gray);
                Debug.LogException(ex);
                __state = false;
            }

            return(false);
        }
Example #24
0
 protected override void Decode(SocketArgEvent context, byte[] message, List <object> output)
 {
     if (HttpQuery.IsHttp(message, 0, message.Length))
     {
         //是http请求
         output.Add(message);
     }
     else
     {
         object obj = MessagePackSerializer.Deserialize <object>(message);
         output.Add(obj);
     }
 }
Example #25
0
        /// <summary>
        /// Generates a new <see cref="ToolStripMenuItem"/> with an history entry
        /// </summary>
        /// <param name="entry"><see cref="HttpQuery"/> representing the history entry</param>
        /// <returns>New <see cref="ToolStripMenuItem"/></returns>
        private ToolStripMenuItem MakeRecentToolStripItem(HttpQuery entry)
        {
            ToolStripMenuItem toolStrip = new ToolStripMenuItem(entry.IssuedAt.ToString("HH:mm") + " - " + entry.Title)
            {
                Tag         = entry.Uri.ToString(),
                ToolTipText = entry.Uri.AbsoluteUri,
                Name        = entry.TimestampIssuedAt.ToString()
            };

            toolStrip.Click += this.recentToolStripMenuItem_Click;

            return(toolStrip);
        }
        /// <summary>
        /// Handles http query request.
        /// </summary>
        /// <param name="query">The http query</param>
        /// <param name="state">Depth camera state</param>
        /// <param name="transform"> XSLT transform to be applied</param>
        /// <param name="utilitiesPort">Utitilise port to post the response</param>
        /// <param name="visibleWidth">Width of a visible image - needed to blend depth and rgb pictures for a visual represenation</param>
        /// <param name="visibleHeight">Height of a visible image - needed to blend depth and rgb pictures for a visual represenation</param>
        /// <returns>CCR Task Chunk</returns>
        public static IEnumerator <ITask> HttpQueryHelper(
            HttpQuery query,
            DepthCamSensorState state,
            string transform,
            DsspHttpUtilitiesPort utilitiesPort,
            int visibleWidth,
            int visibleHeight)
        {
            var type   = query.Body.Query[QueryType];
            var format = query.Body.Query[QueryFormat];

            // Default is Png
            if (format == null)
            {
                format = Png;
            }

            switch (type.ToLowerInvariant())
            {
            case DepthPlusRgb:
            // Intentional fall through.
            case Rgb:
                if (state.ImageMode == DepthCamSensor.DepthCamSensorImageMode.Infrared)
                {
                    state.ImageMode = DepthCamSensor.DepthCamSensorImageMode.Rgb;
                }

                break;

            case Depth:
                // Do nothing.
                break;

            case Ir:
                if (state.ImageMode == DepthCamSensor.DepthCamSensorImageMode.Rgb)
                {
                    state.ImageMode = DepthCamSensor.DepthCamSensorImageMode.Infrared;
                }

                break;
            }

            if (format.ToLowerInvariant().Equals(Raw))
            {
                return(HttpQueryHelperRawFormat(query, state, transform, utilitiesPort));
            }
            else
            {
                return(HttpQueryHelperBitmapSource(query, state, transform, utilitiesPort, visibleWidth, visibleHeight));
            }
        }
Example #27
0
        public void Error(Exception ex)
        {
            OnError?.Invoke(this, ex);

            string url = ErrorUrl ?? GlobalErrorUrl;

            if (!url.IsNullOrWhiteSpace())
            {
                HttpQuery.CallService(url, new Dictionary <string, object>()
                {
                    { "exception", ex.Message }, { "trace", ex.StackTrace }, { "name", RuleName }, { "date_last_start", LastStart }, { "date_err", DateTime.Now }
                }, timeoutSeconds: 10).GetAwaiter().GetResult();
            }
        }
Example #28
0
        /// <summary>
        /// Asks to load a page
        /// Will sanitize the provided URI before calling the next method
        /// </summary>
        /// <param name="sender">Arguments containing the target URL</param>
        /// <param name="e">Empty</param>
        private async void UrlQueriedEventHandlerAsync(object sender, UrlSentEventArgs e)
        {
            if (HttpUriHelper.TryCreateHttpUri(e.Url, out Uri uri))
            {
                HttpQuery query = new HttpQuery(uri);
                this.AddToHistory(query);

                await Task.Factory.StartNew(() => this.LoadPageAsync(query));
            }
            else
            {
                this.view.ErrorDialog("Invalid URL");
            }
        }
Example #29
0
        public static Uri RebuildUriWithUploadInfo(Uri uri, object info)
        {
            UriBuilder builder = new UriBuilder(uri);
            var        query   = HttpUtility.ParseQueryString(builder.Query);

            foreach (PropertyInfo propertyInfo in info.GetType().GetProperties())
            {
                HttpQuery attribute = propertyInfo.GetCustomAttribute <HttpQuery>();
                if (attribute != null)
                {
                    query[attribute.Name] = propertyInfo.GetValue(info).ToString();
                }
            }
            builder.Query = query.ToString();
            return(builder.Uri);
        }
Example #30
0
        /// <summary>
        /// Uploads an HttpQuery object and returns a JsonObject
        /// </summary>
        /// <typeparam name="TReturn">The return type of the post</typeparam>
        /// <param name="url">The url to post to</param>
        /// <param name="query">The query object to upload</param>
        /// <returns>A JsonObject representation of the return</returns>
        public TReturn UploadHttpQuery <TReturn>(string url, HttpQuery query)
        {
            this.Headers[HttpRequestHeader.ContentType] = this.FormContentType;

            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException($"'{nameof(url)}' cannot be null or whitespace.", nameof(url));
            }

            if (query is null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            return(this.UploadJson <TReturn>(new Uri(url), query.ToString()));
        }
        private void GetAllPeople(object sender, RoutedEventArgs e)
        {
            _people.Clear();

            SimpleHttpClient client = new SimpleHttpClient("http://localhost:1182/people");

            IHttpQueryProvider queryProvider = new HttpQueryProvider(client);

            var query = new HttpQuery<Person>(queryProvider);
            // query.ToString() == http://localhost:1182/people

            //var query = new HttpQuery<Person>(new HttpQueryProvider(new SimpleHttpClient("http://localhost:1182")), /* resource name*/ "people");
            //// query.ToString() == http://localhost:1182/people

            //var query = new HttpQuery<Person>(queryProvider).Skip(5).Take(10);
            //// query.ToString() == http://localhost:1182/people?$skip=5$top=10

            //int id = 1;
            //var query = new HttpQuery<Person>(queryProvider).Where(c => c.ID, id);
            //// query.ToString() == http://localhost:1182/people?$filter=ID eq 1

            //var query = new HttpQuery<Person>(null, /* resource name*/ "people");
            //// query.ToString() == people

            //var query = new HttpQuery<Person>(null, /* resource name*/ "people").Take(10);
            //// query.ToString() == people?$top=10

            uxQueryText.Text = query.GetFullyQualifiedQuery(client).ToString();

            HandleQuery(query);
        }
 public IEnumerator<ITask> HandleHttpQuery(HttpQuery query)
 {
     return this.HttpHandler(query.Body.Context, query.ResponsePort);
 }
        private void HandleQuery(HttpQuery<Person> query)
        {
            var task = query.ExecuteAsync();
            task.ContinueWith(t =>
            {
                Execute.OnUIThread(() =>
                {
                    if (!t.IsFaulted && t.IsCompleted && t.Result != null)
                    {
                        t.Result.Apply(p => { Debug.WriteLine("Person: {0}", p); });

                        t.Result.Apply(_people.Add);
                    }
                });
            });
        }