public async Task Ctor_OneUnicodeEntry_Encoded()
        {
            var data = new Dictionary<string, string>();
            data.Add("key", "valueク");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.Equal(18, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("key=value%E3%82%AF", result);
        }
        public async Task Ctor_TwoEntries_SeparatedByAnd()
        {
            var data = new Dictionary<string, string>();
            data.Add("key1", "value1");
            data.Add("key2", "value2");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.Equal(23, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("key1=value1&key2=value2", result);
        }
        public async Task Ctor_WithSpaces_EncodedAsPlus()
        {
            var data = new Dictionary<string, string>();
            data.Add("key 1", "val%20ue 1"); // %20 is a percent-encoded space, make sure it survives.
            data.Add("key 2", "val%ue 2");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.Equal(35, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("key+1=val%2520ue+1&key+2=val%25ue+2", result);
        }
Example #4
0
        //called when data for any output pin is requested
        public void Evaluate(int SpreadMax)
        {
            FOutput.SliceCount = SpreadMax;

            HttpClient client = new HttpClient();
            FormUrlEncodedContent form = new FormUrlEncodedContent(new Dictionary<string, string> { { "username", "username" }, { "password", "password" } });

            Task<HttpResponseMessage> message = client.PostAsync("https://services.open.xerox.com/api/Auth/OAuth2", form);
            String result = message.Result.Content.ReadAsStringAsync().Result;

            JObject obj = JObject.Parse(result);
            string token = (string)obj["access_token"];
            string refreshToken = (string)obj["refresh_token"];

            for (int i = 0; i < SpreadMax; i++)
                FOutput[i] = FInput[i] * 2;

            //FLogger.Log(LogType.Debug, "hi tty!");
        }
Example #5
0
        public async Task <IActionResult> ConnectCallback(string code)
        {
            string url = $"https://oauth.vk.com/access_token?" +
                         $"client_id={_configuration.GetValue<long>("VkApplicationId")}" +
                         $"&client_secret={_configuration.GetValue<string>("VkApplicationPassword")}" +
                         $"&redirect_uri={$"{_configuration.GetValue<string>("SiteUrl")}/Groups/ConnectCallback"}" +
                         $"&code={code}";

            string result = null;

            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(url, null);

                result = await response.Content.ReadAsStringAsync();

                Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Parse(result);
                //TODO: Добавить проверку на null у token
                var    token      = obj.Properties().FirstOrDefault(x => x.Name.StartsWith("access_token_"));
                var    idGroup    = long.Parse(token.Name.Split('_').Last());
                string tokenValue = token.Value.ToString();

                var group = await _context.Groups.Where(x => x.IdVk == idGroup).FirstOrDefaultAsync();

                if (group == null)
                {
                    group = new Groups()
                    {
                        IdVk = idGroup
                    };
                    await _context.Groups.AddAsync(group);
                }

                group.AccessToken = tokenValue;

                using (var vkGroupApi = new VkNet.VkApi())
                {
                    await vkGroupApi.AuthorizeAsync(new VkNet.Model.ApiAuthParams()
                    {
                        AccessToken = tokenValue,
                        Settings    = VkNet.Enums.Filters.Settings.Groups
                    });

                    group.CallbackConfirmationCode = await vkGroupApi.Groups.GetCallbackConfirmationCodeAsync((ulong)idGroup);

                    var groups = await vkGroupApi.Groups.GetByIdAsync(null, idGroup.ToString(), VkNet.Enums.Filters.GroupsFields.Description);

                    var groupInfo = groups.FirstOrDefault();

                    group.Name  = groupInfo.Name;
                    group.Photo = groupInfo.Photo50.ToString();
                }
                await _context.SaveChangesAsync();

                var idUser = _userHelperService.GetUserId(User);

                var groupAdmin = await _context.GroupAdmins.Where(x => x.IdUser == idUser && x.IdGroup == idGroup).FirstOrDefaultAsync();

                if (groupAdmin == null)
                {
                    groupAdmin = new GroupAdmins()
                    {
                        IdGroup   = idGroup,
                        IdUser    = idUser,
                        DtConnect = DateTime.UtcNow
                    };
                    await _context.GroupAdmins.AddAsync(groupAdmin);
                }
                else
                {
                    groupAdmin.DtConnect = DateTime.UtcNow;
                }
                await _context.SaveChangesAsync();

                url = $"https://api.vk.com/method/groups.getCallbackServers?" +
                      $"access_token={tokenValue}" +
                      $"&group_id={idGroup}" +
                      $"&v={AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion}";

                response = await client.PostAsync(url, null);

                result = await response.Content.ReadAsStringAsync();

                var callbackServers = new VkResponse(result).ToVkCollectionOf <VkNet.Model.CallbackServerItem>(x => x);

                long idServer           = -1;
                var  callbackServerUrl  = _configuration.GetValue <string>("CallbackServerUrl");
                var  callbackServerInfo = callbackServers.FirstOrDefault(x => x.Url == callbackServerUrl);
                if (callbackServerInfo == null)
                {
                    url = $"https://api.vk.com/method/groups.addCallbackServer?" +
                          $"access_token={tokenValue}" +
                          $"&group_id={idGroup}" +
                          $"&url={_configuration.GetValue<string>("SiteUrl")}{callbackServerUrl}" +
                          $"&title={_configuration.GetValue<string>("CallbackServerName")}" +
                          $"&v={AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion}";
                    response = await client.PostAsync(url, null);

                    result = await response.Content.ReadAsStringAsync();

                    var json = Newtonsoft.Json.Linq.JObject.Parse(result);
                    idServer = new VkResponse(json[propertyName: "response"])
                    {
                        RawJson = result
                    }[key: "server_id"];
                }
                else
                {
                    idServer = callbackServerInfo.Id;
                }

                var callbackProperties = new VkNet.Model.CallbackSettings();
                foreach (var property in callbackProperties.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                {
                    property.SetValue(callbackProperties, true);
                }
                var parameters = VkNet.Model.RequestParams.CallbackServerParams.ToVkParameters(new VkNet.Model.RequestParams.CallbackServerParams()
                {
                    GroupId          = (ulong)idGroup,
                    ServerId         = idServer,
                    CallbackSettings = callbackProperties
                });
                parameters.Add("access_token", tokenValue);
                parameters.Add("v", AspNet.Security.OAuth.Vkontakte.VkontakteAuthenticationDefaults.ApiVersion);
                url = "https://api.vk.com/method/groups.setCallbackSettings";

                HttpContent content = new FormUrlEncodedContent(parameters);
                response = await client.PostAsync(url, content);

                result = await response.Content.ReadAsStringAsync();
            }
            return(RedirectToAction(nameof(IndexConnected), "Groups"));
        }
 public async Task Ctor_EmptySource_Succeed()
 {
     var content = new FormUrlEncodedContent(new Dictionary<string, string>());
     Stream stream = await content.ReadAsStreamAsync();
     Assert.Equal(0, stream.Length);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="encodedpars"></param>
        /// <param name="headers"></param>
        /// <param name="cookiecontainer"></param>
        /// <param name="customLocalTempDir"></param>
        /// <exception cref="DataCollectionException">When an error happens before getting the response from the server. Details are into the inner exception</exception>
        /// <exception cref="BadHttpCodeException">When the server has answered a non-2XX response code</exception>
        /// <returns></returns>
        private static string DownloadJsonFile(Uri url, string method, Dictionary <string, string> encodedpars, Dictionary <string, string> headers, ref CookieContainer cookiecontainer, string customLocalTempDir, out string computed_url)
        {
            string localTmp = null;
            string filePath = null;

            if (url == null || string.IsNullOrEmpty(url.AbsolutePath))
            {
                throw new ArgumentException("Url parameter was null or empty.");
            }
            if (method == null)
            {
                throw new ArgumentException("Method cannot be null.");
            }

            method = method.ToUpper();
            if (method != "GET" && method != "POST" && method != "PUT" && method != "DELETE")
            {
                throw new ArgumentException("Invalid http method supplied: " + method);
            }

            if (!string.IsNullOrEmpty(customLocalTempDir))
            {
                if (!Directory.Exists(customLocalTempDir))
                {
                    throw new ArgumentException("Local tmp path doesn't exist: " + customLocalTempDir);
                }
                localTmp = customLocalTempDir;
            }
            else
            {
                localTmp = Path.GetTempPath();
            }

            filePath = Path.Combine(localTmp, Guid.NewGuid().ToString() + ".json");

            using (var handler = new HttpClientHandler()
            {
                CookieContainer = cookiecontainer
            })
                using (var client = new HttpClient(handler)
                {
                    BaseAddress = url
                })
                {
                    // Setto i parametri e gli headers
                    handler.AllowAutoRedirect = true;
                    handler.UseCookies        = true;

                    HttpRequestMessage req = new HttpRequestMessage();
                    req.RequestUri = url;
                    computed_url   = url.ToString();

                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            req.Headers.Add(h.Key, h.Value);
                        }
                    }

                    System.Threading.Tasks.Task <HttpResponseMessage> mtd = null;
                    switch (method)
                    {
                    case "GET":
                        req.Method = HttpMethod.Get;
                        break;

                    case "POST":
                        req.Method = HttpMethod.Post;
                        var data = new FormUrlEncodedContent(encodedpars);
                        req.Content = data;
                        break;

                    case "PUT":
                        req.Method  = HttpMethod.Put;
                        data        = new FormUrlEncodedContent(encodedpars);
                        req.Content = data;
                        break;

                    case "DELETE":
                        req.Method = HttpMethod.Delete;
                        break;
                    }

                    mtd = client.SendAsync(req);
                    HttpResponseMessage result = null;

                    try {
                        result = mtd.Result;
                    } catch (AggregateException e) {
                        // Any kind of exception could have happened in here.
                        // So, we simply wrap the exception into one of our specific class that will be catched later from the caller.
                        throw new DataCollectionException("Error during HTTP request to " + req.RequestUri, e.InnerException);
                    }

                    // In case there was no hard failure connected to the network, we have to check whether the result code was ok or not.
                    if (!result.IsSuccessStatusCode)
                    {
                        throw new BadHttpCodeException(result);
                    }

                    // Write to file.
                    using (var sw = new FileStream(filePath, FileMode.OpenOrCreate))
                        result.Content.CopyToAsync(sw).Wait();
                }
            return(filePath);
        }
Example #8
0
        /// <summary>
        /// Регистрация юридического лица.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static async Task <ServiceResponseObject <RegisterResponse> > RegisterLegal(RegisterLegalModel model)
        {
            try
            {
                //status & message
                var formContent = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "login", model.Login },
                    { "password", model.Password },
                    { "email", model.Email },
                    { "org_phone", model.OrgPhone },
                    { "client_type", model.ClientType },
                    { "client_last_name", model.ClientLastName },
                    { "client_name", model.ClientName },
                    { "client_patronymic", model.ClientPatronymic },
                    { "org_postal_address", model.OrgPostalAddress },
                    { "org_name", model.OrgName },
                    { "org_kpp", model.OrgKpp },
                    { "org_inn", model.OrgInn },
                    { "org_ogrn", model.OrgOgrn },
                    { "org_bank", model.OrgBank },
                    { "org_bank_payment", model.OrgBankpayment },
                    { "org_bank_correspondent", model.OrgBankCorrespondent },
                    { "org_bank_bik", model.OrgBankBik },
                    { "org_legal_address", model.OrgLegalAddress }
                });

                HttpResponseMessage response = await _httpClient.PostAsync($"client", formContent);

                string s_result;
                using (HttpContent responseContent = response.Content)
                {
                    s_result = await responseContent.ReadAsStringAsync();
                }

                ServiceResponseObject <RegisterResponse> o_data = new ServiceResponseObject <RegisterResponse>();

                switch (response.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                {
                    ErrorResponseObject error = new ErrorResponseObject();
                    error          = JsonConvert.DeserializeObject <ErrorResponseObject>(s_result);
                    o_data.Status  = response.StatusCode;
                    o_data.Message = error.Errors[0];
                    return(o_data);
                }

                case HttpStatusCode.InternalServerError:
                {
                    ErrorResponseObject error = new ErrorResponseObject();
                    o_data.Status  = response.StatusCode;
                    o_data.Message = "Внутренняя ошибка сервера 500";
                    return(o_data);
                }

                case HttpStatusCode.NotFound:
                {
                    ErrorResponseObject error = new ErrorResponseObject();
                    o_data.Status  = response.StatusCode;
                    o_data.Message = "Ресурс не найден 404";
                    return(o_data);
                }

                case HttpStatusCode.OK:
                {
                    var register = JsonConvert.DeserializeObject <RegisterResponse>(s_result);
                    o_data.Message      = register.message;
                    o_data.Status       = response.StatusCode;
                    o_data.ResponseData = new RegisterResponse
                    {
                        message = register.message,
                        user    = register.user
                    };
                    return(o_data);
                }

                default:
                {
                    throw new Exception(response.StatusCode.ToString() + " Server Error");
                }
                }
            }
            catch (Exception ex)
            {
                ServiceResponseObject <RegisterResponse> o_data = new ServiceResponseObject <RegisterResponse>();
                o_data.Message = ex.Message;
                return(o_data);
            }
        }
        public override void RedirectLogin()
        {
            while (!CheckWifi())
            {
                connectionStateCallBack.StateChange("等待WIFI...");
                Thread.Sleep(500);
            }
            connectionStateCallBack.StateChange("自动登录准备...");
            HttpClient httpClient = new HttpClient();
            Task <HttpResponseMessage> httpResponseMessage = httpClient.GetAsync("http://www.baidu.com");

            httpResponseMessage.Wait();
            HttpResponseMessage h = httpResponseMessage.Result;
            var b = h.Content.ReadAsStringAsync();

            b.Wait();
            String s        = b.Result;
            var    loginUrl = "";

            try
            {
                loginUrl = s.Substring(s.IndexOf("='") + 2, s.LastIndexOf("'<") - (s.IndexOf("='") + 2));
            }
            catch (Exception)
            {
                connectionStateCallBack.StateChange("已连接互联网...");
                return;
            }

            if (!loginUrl.StartsWith("http"))
            {
                connectionStateCallBack.StateChange("已连接互联网...");
                return;
            }
            connectionStateCallBack.StateChange("获取到的登录地址..." + loginUrl);
            string username = "";
            string password = "";

            try
            {
                string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    path = Directory.GetParent(path).ToString();
                }
                connectionStateCallBack.StateChange("用户目录: " + path);
                var user = File.ReadAllText(path + "\\userinfo").Split(new Char[] { ',' });
                if (user.Length != 2)
                {
                    connectionStateCallBack.StateChange("用户信息文件错误");
                    return;
                }
                connectionStateCallBack.StateChange("用户名:" + user[0]);
                connectionStateCallBack.StateChange("密码:" + user[1]);
                username = user[0];
                password = user[1];
            }
            catch (Exception e)
            {
                connectionStateCallBack.StateChange(e.Message);
                return;
            }

            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("userId", username),
                new KeyValuePair <string, string>("passwd", password),
                new KeyValuePair <string, string>("templatetype", "3"),
                new KeyValuePair <string, string>("pageid", "21")
            });

            var cc = httpClient.PostAsync(loginUrl, formContent);

            cc.Wait();
            var dd = cc.Result;

            connectionStateCallBack.StateChange("登录结果..." + dd.StatusCode);
        }
Example #10
0
        // Connect to the web API as the current user to post a new todo item
        private async void PostNewTodo()
        {
            // Get a token for the API. Note that this will almost always come from the cache
            // given that a POST will always follow a get of all the todos, whihc will have already acquired the token if necessary
            AuthenticationResult result = await App.AuthenticationContext.AcquireTokenAsync(App.ResourceID, App.ClientID);

            if (result.Status != AuthenticationStatus.Succeeded)
            {
                if (result.Error == "authentication_canceled")
                {
                    // The user cancelled the sign-in
                }
                else
                {
                    MessageDialog dialog = new MessageDialog(string.Format("If the error continues, please contact your administrator.\n\nError: {0}\n\nError Description:\n\n{1}", result.Error, result.ErrorDescription), "Sorry, an error occurred while signing you in.");
                    await dialog.ShowAsync();
                }
                // we failed to obtain a token, hence we cannot render this page. We need to go back to main.
                this.Frame.Navigate(typeof(MainPage));
                return;
            }
            // Populate the current user controol on the top right corner.
            // The code below works around a bug for whihc in some cases the service fails to return user information
            if (result.UserInfo.GivenName != null)
            {
                txtFirstName.Text = result.UserInfo.GivenName;
                txtLastName.Text  = result.UserInfo.FamilyName;
            }
            else
            {
                txtFirstName.Text = result.UserInfo.UserId;
                txtLastName.Text  = "(Temporary identifier)";
            }
            btnAccount.Visibility = Windows.UI.Xaml.Visibility.Visible;
            // Call the web API presenting the access token
            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Description", TodoText.Text) });

            var response = await httpClient.PostAsync(App.APIHostname + App.APITodoListPath, content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                GetTodoList();
            }
            else
            {
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    // If the To Do list service returns access denied, clear the token cache and have the user sign-in again.
                    MessageDialog dialog = new MessageDialog("Sorry, you don't have access to the To Do Service. You might need to sign up.");
                    await dialog.ShowAsync();

                    App.AuthenticationContext.TokenCacheStore.Clear();
                    this.Frame.Navigate(typeof(MainPage));
                }
                else
                {
                    MessageDialog dialog = new MessageDialog("Sorry, an error occurred accessing your To Do list.  Please try again.");
                    await dialog.ShowAsync();
                }
            }
        }
Example #11
0
        public async Task <IEnumerable <HeroesProfileReplay> > GetReplaysByFilters(GameType?gameType = null, GameRank?gameRank = null, string gameMap = null)
        {
            try
            {
                var dictionary = new Dictionary <string, string>();
                if (gameType != null)
                {
                    dictionary.Add("game_type", gameType.Value.GetQueryValue());
                }
                if (gameRank != null)
                {
                    dictionary.Add("rank", gameRank.Value.GetQueryValue());
                }
                if (gameMap != null)
                {
                    dictionary.Add("game_map", gameMap);
                }

                string filter;

                using (FormUrlEncodedContent content = new FormUrlEncodedContent(dictionary))
                {
                    filter = await content.ReadAsStringAsync();
                }

                return(await replaysByFilterCachePolicy.ExecuteAsync(async (context, token) =>
                {
                    int maxId = await GetMaxReplayIdAsync();
                    context["minId"] = maxId - settings.HeroesProfileApi.ApiMaxReturnedReplays;

                    // If nothing is found with the filter, try going back further

                    IEnumerable <HeroesProfileReplay> replays = await Policy
                                                                .Handle <Exception>()
                                                                .OrResult <IEnumerable <HeroesProfileReplay> >(replays => !replays.Any())
                                                                .WaitAndRetryAsync(retryCount: 20, sleepDurationProvider: (int retry, Context context) => TimeSpan.FromSeconds(1), onRetry: OnFilterRetry)
                                                                .ExecuteAsync(async(Context context, CancellationToken token) =>
                    {
                        HttpResponseMessage response = await Policy
                                                       .Handle <Exception>()
                                                       .OrResult <HttpResponseMessage>(msg => !msg.IsSuccessStatusCode)
                                                       .WaitAndRetryAsync(retryCount: 10, sleepDurationProvider: GetSleepDuration, OnRetry)
                                                       .ExecuteAsync((context, token) => httpClient.GetAsync(new Uri($"Replay/Min_id?min_id={context["minId"]}&{context.OperationKey}&api_token={settings.HeroesProfileApi.ApiKey}", UriKind.Relative), token), context, token);

                        if (response.IsSuccessStatusCode)
                        {
                            IEnumerable <HeroesProfileReplay> replays = await response.Content.ReadFromJsonAsync <IEnumerable <HeroesProfileReplay> >(cancellationToken: token);

                            var supported = replays
                                            .Where(x => x.Deleted == null)
                                            .Where(x => x.Url.Host.Contains(settings.HeroesProfileApi.S3Bucket))
                                            .Where(x => settings.Spectate.VersionsSupported.Contains(x.GameVersion));

                            return supported;
                        }
                        else
                        {
                            return Enumerable.Empty <HeroesProfileReplay>();
                        }
                    }, context, token)
                                                                .ConfigureAwait(false);

                    return replays;
                }, new Context(operationKey : filter), tokenProvider.Token));
            }
            catch (Exception e)
            {
                logger.LogError(e, "Could not get replays from HeroesProfile Replays.");
            }

            return(Enumerable.Empty <HeroesProfileReplay>());
        }
Example #12
0
        /// <summary>
        /// Hent oplysninger fra Motorregister
        /// </summary>
        /// <param name="regnr">nummerplade på køretøj</param>
        /// <param name="dato">historisk dato for oplysninger</param>
        /// <returns></returns>
        public static async Task <Bildata> HentOplysninger(string regnr, DateTime dato)
        {
            CookieContainer   CookieJar = new CookieContainer();
            HttpClientHandler handler   = new HttpClientHandler {
                CookieContainer = CookieJar
            };
            HttpClient client        = new HttpClient(handler);
            string     Token         = "";
            string     Radio         = "";
            string     PlateField    = "";
            string     HistoriskText = "";
            string     HistoriskKnap = "";
            Bildata    bildata       = new Bildata();

            var startPage = await client.GetAsync("https://motorregister.skat.dk/dmr-kerne/dk/skat/dmr/front/portlets/koeretoejdetaljer/visKoeretoej/VisKoeretoejController.jpf");

            if (startPage.IsSuccessStatusCode)
            {
                var content = await startPage.Content.ReadAsStringAsync();

                var tokenElement = Regex.Matches(content, "<input[^>]+?dmrFormToken[^>]+?>", RegexOptions.IgnoreCase)[0].Value;
                Token = XElement.Parse(tokenElement).Attribute("value").Value;

                //var radioElement = Regex.Matches(content, "<input[^>]+?REGISTRERINGSNUMMER[^>]+?>", RegexOptions.IgnoreCase)[0].Value;
                //Radio = XElement.Parse(radioElement).Attribute("name").Value;

                //var textElement = Regex.Matches(content, "<input[^>]+?soegeord[^>]+?>", RegexOptions.IgnoreCase)[0].Value;
                //PlateField = XElement.Parse(textElement).Attribute("name").Value;



                var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("dmrFormToken", Token),
                    new KeyValuePair <string, string>("wlw-radio_button_group_key:{actionForm.soegekriterie}", "REGISTRERINGSNUMMER"),
                    new KeyValuePair <string, string>("{actionForm.soegeord}", regnr),
                });

                HttpResponseMessage MotorInfo1 = await client.PostAsync("https://motorregister.skat.dk/dmr-kerne/dk/skat/dmr/front/portlets/koeretoej/nested/fremsoegKoeretoej/search.do", formContent);

                HttpResponseMessage MotorInfo2 = null,
                                    MotorInfo3 = null,
                                    MotorInfo5 = null;

                if (MotorInfo1.IsSuccessStatusCode)
                {
                    var MotorResult = await MotorInfo1.Content.ReadAsStringAsync();

                    // Fail Fast...
                    if (MotorResult.Contains("Ingen køretøjer fundet."))
                    {
                        throw new HttpException((int)HttpStatusCode.NotFound, "Ingen køretøjer fundet.");
                    }

                    // Hent historiske data i stedet
                    if (dato.Date < DateTime.Now.Date)
                    {
                        //var historiskInput = Regex.Matches(MotorResult, "<input[^>]+?lblHstrskVsnng[^>]+?>", RegexOptions.IgnoreCase)[0].Value;
                        //HistoriskText = XElement.Parse(historiskInput).Attribute("name").Value;

                        //var historiskButton = Regex.Matches(MotorResult, "<input[^>]+?lblHstrskVsnng[^>]+?>", RegexOptions.IgnoreCase)[0].Value;
                        //HistoriskKnap = XElement.Parse(historiskButton).Attribute("name").Value;

                        formContent = new FormUrlEncodedContent(new[]
                        {
                            new KeyValuePair <string, string>("dmrFormToken", Token),
                            new KeyValuePair <string, string>("{pageFlow.historiskDato}", dato.ToString("dd-MM-yyyy")),
                            new KeyValuePair <string, string>("HistoriskKnap", "Hent"),
                        });

                        MotorInfo1 = await client.PostAsync("https://motorregister.skat.dk/dmr-kerne/dk/skat/dmr/front/portlets/koeretoejdetaljer/nested/visKoeretoej/indstilHistoriskDato.do", formContent);

                        if (MotorInfo1.IsSuccessStatusCode)
                        {
                            MotorResult = await MotorInfo1.Content.ReadAsStringAsync();

                            MotorInfo2 = await client.GetAsync("https://motorregister.skat.dk/dmr-front/dmr.portal?_nfpb=true&_windowLabel=kerne_vis_koeretoej&kerne_vis_koeretoej_actionOverride=%2Fdk%2Fskat%2Fdmr%2Ffront%2Fportlets%2Fkoeretoej%2Fnested%2FvisKoeretoej%2FselectTab&kerne_vis_koeretoejdmr_tabset_tab=1&_pageLabel=vis_koeretoej_side");

                            MotorInfo3 = await client.GetAsync("https://motorregister.skat.dk/dmr-front/dmr.portal?_nfpb=true&_windowLabel=kerne_vis_koeretoej&kerne_vis_koeretoej_actionOverride=%2Fdk%2Fskat%2Fdmr%2Ffront%2Fportlets%2Fkoeretoej%2Fnested%2FvisKoeretoej%2FselectTab&kerne_vis_koeretoejdmr_tabset_tab=2&_pageLabel=vis_koeretoej_side");

                            MotorInfo5 = await client.GetAsync("https://motorregister.skat.dk/dmr-front/dmr.portal?_nfpb=true&_windowLabel=kerne_vis_koeretoej&kerne_vis_koeretoej_actionOverride=%2Fdk%2Fskat%2Fdmr%2Ffront%2Fportlets%2Fkoeretoej%2Fnested%2FvisKoeretoej%2FselectTab&kerne_vis_koeretoejdmr_tabset_tab=4&_pageLabel=vis_koeretoej_side");
                        }
                    }
                    else
                    {
                        MotorInfo2 = await client.GetAsync("https://motorregister.skat.dk/dmr-kerne/dk/skat/dmr/front/portlets/koeretoejdetaljer/nested/visKoeretoej/selectTab.do?dmr_tabset_tab=1");

                        MotorInfo3 = await client.GetAsync("https://motorregister.skat.dk/dmr-kerne/dk/skat/dmr/front/portlets/koeretoejdetaljer/nested/visKoeretoej/selectTab.do?dmr_tabset_tab=2");

                        MotorInfo5 = await client.GetAsync("https://motorregister.skat.dk/dmr-kerne/dk/skat/dmr/front/portlets/koeretoejdetaljer/nested/visKoeretoej/selectTab.do?dmr_tabset_tab=4");
                    }

                    ParseKøretøjData(bildata, MotorResult);

                    if (MotorInfo2.IsSuccessStatusCode)
                    {
                        var MotorResult2 = await MotorInfo2.Content.ReadAsStringAsync();

                        ParseTekniskeData(bildata, MotorResult2);
                    }

                    if (MotorInfo3.IsSuccessStatusCode)
                    {
                        var MotorResult3 = await MotorInfo3.Content.ReadAsStringAsync();

                        ParseSynsData(bildata, MotorResult3);
                    }

                    if (MotorInfo5.IsSuccessStatusCode)
                    {
                        var MotorResult5 = await MotorInfo5.Content.ReadAsStringAsync();

                        ParseAfgiftsData(bildata, MotorResult5);
                    }
                }
            }
            else
            {
                throw new HttpException((int)HttpStatusCode.ServiceUnavailable, "Motorregisteret er utilgængeligt");
            }

            return(bildata);
        }
Example #13
0
        public static async Task <ServerResponseStatus> TryLogin(string username, string password)
        {
            try
            {
                var url        = "https://maempedia.com/login.html";
                var requestURI = $"{url}?key={apiKey}";

                var client = new HttpClient()
                {
                    Timeout = TimeSpan.FromSeconds(TIMEOUT)
                };

                var values = new Dictionary <string, string>
                {
                    { "username", username },
                    { "password", password }
                };
                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(requestURI, content);

                if (!response.IsSuccessStatusCode)
                {
                    Debug.WriteLine("Maempedia HTTP request denied.");
                    return(ServerResponseStatus.ERROR);
                }

                var result = await response.Content.ReadAsStringAsync();

                if (result == null)
                {
                    Debug.WriteLine("Maempedia API has returned nothing.");
                    return(ServerResponseStatus.ERROR);
                }

                JObject json = null;
                try
                {
                    json = JObject.Parse(result);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException);
                    return(ServerResponseStatus.ERROR);
                }

                if (json["status"].ToString() == "SUCCESS")
                {
                    Owner owner = new Owner()
                    {
                        ID                  = json["user"]["id"].ToString(),
                        Username            = json["user"]["username"].ToString(),
                        Password            = json["user"]["password"].ToString(),
                        Email               = json["user"]["email"].ToString(),
                        Name                = json["user"]["name"].ToString(),
                        ProfilePicture      = "https://www." + json["user"]["photo_url"].ToString(),
                        ProfilePictureThumb = "https://www." + json["user"]["photo_thumb_url"].ToString(),
                        ContactNumber       = json["user"]["contact"].ToString(),
                        ContactWA           = json["user"]["wacontact"].ToString(),
                        IsMaemseller        = bool.Parse(json["user"]["is_maemseller"].ToString())
                    };

                    if (owner.IsMaemseller)
                    {
                        owner.Headline    = json["user"]["description"].ToString();
                        owner.OpeningHour = json["user"]["opening_hour"].ToString();
                        owner.ClosingHour = json["user"]["closing_hour"].ToString();
                        owner.Location    = new Location()
                        {
                            Address   = json["user"]["location"]["address"].ToString(),
                            Latitude  = double.Parse(json["user"]["location"]["lat"].ToString()),
                            Longitude = double.Parse(json["user"]["location"]["lng"].ToString())
                        };
                    }

                    App.User.SetUser(owner);
                    App.User.ProfileSynchronised = true;

                    return(ServerResponseStatus.VALID);
                }
                else
                {
                    return(ServerResponseStatus.INVALID);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(ServerResponseStatus.ERROR);
            }
        }
Example #14
0
        void PlacebetThread(object RollObject)
        {
            try
            {
                string      ClientSeed = R.Next(0, 100).ToString();
                PlaceBetObj tmp5       = RollObject as PlaceBetObj;
                decimal     amount     = tmp5.Amount;
                decimal     chance     = tmp5.Chance;
                bool        High       = tmp5.High;
                decimal     tmpchance  = High ? 99m - chance : chance;
                List <KeyValuePair <string, string> > pairs = new List <KeyValuePair <string, string> >();
                pairs.Add(new KeyValuePair <string, string>("rollAmount", (amount * 100000000m).ToString("0", System.Globalization.NumberFormatInfo.InvariantInfo)));
                pairs.Add(new KeyValuePair <string, string>("rollUnder", tmpchance.ToString("0", System.Globalization.NumberFormatInfo.InvariantInfo)));
                pairs.Add(new KeyValuePair <string, string>("mode", High ? "2" : "1"));
                pairs.Add(new KeyValuePair <string, string>("rollClient", ClientSeed));
                pairs.Add(new KeyValuePair <string, string>("token", accesstoken));


                FormUrlEncodedContent Content = new FormUrlEncodedContent(pairs);
                string sEmitResponse          = Client.PostAsync("play.php", Content).Result.Content.ReadAsStringAsync().Result;
                //Lastbet = DateTime.Now;
                try
                {
                    KDBet tmp = json.JsonDeserialize <KDBet>(sEmitResponse);
                    if (tmp.roll_id != null && tmp.roll_id != null)
                    {
                        Bet tmpBet = new Bet
                        {
                            Amount     = amount,
                            date       = DateTime.Now,
                            Id         = tmp.roll_id,
                            Profit     = tmp.roll_profit / 100000000m,
                            Roll       = tmp.roll_number,
                            high       = High,
                            Chance     = tmp.probability,
                            nonce      = (long)tmp.provablef_serverRoll,
                            serverhash = LastHash,
                            serverseed = tmp.provablef_Hash,
                            clientseed = ClientSeed
                        };
                        if (tmp.roll_result == "win")
                        {
                            wins++;
                        }
                        else
                        {
                            losses++;
                        }
                        wagered += amount;
                        profit  += tmp.roll_profit / 100000000m;
                        bets++;
                        LastHash = tmp.roll_next.hash;
                        balance  = tmp.balance / 100000000m;
                        FinishedBet(tmpBet);
                    }
                    else
                    {
                        Parent.updateStatus("An unknown error has occurred. Bet will retry in 30 seconds.");
                    }
                    //retrycount = 0;
                }
                catch
                {
                    Parent.updateStatus(sEmitResponse);
                }
            }
            catch (Exception e)
            { }
        }
Example #15
0
        public virtual string Login(string verifyCode)
        {
            if (IsNeedVerifyCode)
            {
                if (!CheckValCode(verifyCode))
                {
                    return("验证码输入错误");
                }
            }
            string res         = string.Empty;
            var    pemToXml    = RSAHelper.PemToXml(pubksy);
            var    password    = RSAHelper.RSAEncrypt(pemToXml, this.password);
            var    httpContent = new FormUrlEncodedContent(new Dictionary <string, string>()
            {
                { "staticpage", staticpage },
                { "charset", charset },
                { "token", token },
                { "tpl", TPL },
                { "subpro", "" },
                { "apiver", "v3" },
                { "tt", HttpUtil.GetTimeStamp() },
                { "codestring", verifyStr },
                { "safeflg", "0" },
                { "u", u },
                { "isPhone", "false" },
                { "detect", "1" },
                { "quick_user", "0" },
                { "gid", gid },
                { "logintype", "dialogLogin" },
                { "logLoginType", "pc_loginDialog" },
                { "idc", "" },
                { "loginmerge", "true" },
                { "splogin", "rate" },
                { "username", userName },
                { "password", password },
                { "verifycode", valcode },
                { "mem_pass", "on" },
                { "rsakey", rsakey },
                { "crypttype", "12" },
                { "ppui_logintime", HttpUtil.Generateplogintime() },
                { "countrycode", "" },
                { "fp_uid", string.IsNullOrEmpty(GetCookieValue("FP_UID"))?"a8e078358d61a058b43420dee15e9e77":GetCookieValue("FP_UID") },
                //{"fp_info", "960338120bd__cbs__"+HttpUtil.GenerateCallBack()+"8b87eb0671ea3df2d002~~~nxnn3QqCEgie0x2_Unn6yqz090gtoCdtRC_qqz090gtoCd0RC_unmCsVnmCsJnnsEnm3pOq0xwEgi~JIJH4zEp4gVkJAVkFnERaUirBniP4~LPJoEWJ9HdXAFiBzieJAt~4Au~6IskJI2eJnTWcutK4gtOBgugJGJW6ItK8UsianJW6ItKanTw7AE-czFW4mTpXobP4AEYF3JAXAEdJI2M4AwQJzbNJnBRJzHq6UswJAhQ4gJPXnhiJzBHJAwQ6A~W9zukXIJiYgTHJAVk8zieBnE-4zuWcAVw6grNanTLJgiec3tKazhNJEs3FiJHJIBiaRHH4UFiazVw4mLrJn6NBziiBgE-vUnsBqC0Rae0v__DUnvSUnvNUnsPq0KUEgi~JIJH4zEp4gVkJAVkFnERaUirBniP4~LPJoEWJDT9XnhRXdBwBzEn4nuxXmT9XnhRXdBwBzEn4nuxXmT86IFHBzEp4nii4UFu7nERBIFw6zTicusPaUFw6zTi9zukXIJiYgTHJAVkFIwi6dEk6AbWJDTY4dbk6AbWJGFP6dENJAVkFzh-4AukIA0Rnvr3asEYmvaimkP9ZPOov3MEUsAYhIlrZVvKsPFKg1C3kC8nAXMtlhgYdySekQyus4nkJjvvvDXur5lZwCCb~s~aCkfVFUnsKUnsAUnszUnsrnn2LqC7zCNYkl_CqzBAVO4zhd4C__nUnsmnwLYXeksnnvdUnvbnweUkGbjUnvRUnvYUnveUnvpquc93etp2TtpYl8p2x8paktx2ktY__"},
                //{"dv", "MDExAAoALQALAxIAHgAAAF00AAwCACKKzc3Nzdoidjd5PmwtYD9gMGMzbF1tMm0bfgxlA3o5VjJXDAIAIoqenp6eib3pqOah87L_oP-v_KzzwvKt8oThk_qc5abJrcgHAgAEkZGRkQwCACKKb29vb3nFkdCe2YvKh9iH14TUi7qK1Yr8meuC5J3esdWwBwIABJGRkZEHAgAEkZGRkQ0CACaRkZnW96PirOu5-LXqteW25rmIuOe4zqvZsNav7IPngsGpyKbBpAkCADWws87Pu7u7u7u8RkdELSxLS29vYDR1O3wubyJ9InIhcS4fL3AvWTxOJ0E4exRwFVY-XzFWMwYCACiRkZGRkZGRkZGRlNfX18NSUlJXAwMDAAAAAAVRUVFTi4uLjtra2tgAEwIAJpGzs7Pbr9ur2OLN4pb_mviZt9W03bnM4oHug6zFq8-q0vyU4I3hFwIACpOTsrK37ILZgO8WAgAisMSvn7GCuom4gbiOv4a2j7eCtoO1hLGBtoW9j7yKvIS1jQQCAAaTk5GQpZMVAgAIkZGQzjjFVycBAgAGkZOTg47uBQIABJGRkZ0QAgABkQcCAASRkZGRDQIABZGRku3tDQIAHpGRkhAJXRxSFUcGSxRLG0gYR3ZGGUY2VyRXIE89WQcCAASRkZGRDQIAHpGRmZuC1pfZnsyNwJ_AkMOTzP3Nks293K_cq8S20g0CACaRkZmcvemo5qHzsv-g_6_8rPPC8q3yhOGT-pzlpsmtyIvjguyL7gkCADWws87Pu7u7u7uwbWxvBgdgYERESx9eEFcFRAlWCVkKWgU0BFsEchdlDGoTUD9bPn0VdBp9GAcCAASRkZGRCQIAJ4qIU1I_Pz8_PzDW1oLDjcqY2ZTLlMSXx5ipmcaZ74r4kfeOzaLGowwCACKKnp6enozpvfyy9afmq_Sr-6j4p5am-abQtceuyLHynfmcDAIAIopvb29vfCp-P3E2ZCVoN2g4aztkVWU6ZRN2BG0LcjFeOl8HAgAEkZGRkQkCACOGhcDBDAwMDAwTubntrOKl97b7pPur-Kj3xvap9oXwkv-W4g"},
                { "callback", "parent.bd__pcbs__" + HttpUtil.GenerateCallBack() },
            });

            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            //httpClient.DefaultRequestHeaders.Clear();
            //httpClient.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.8");
            //httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");a
            HttpResponseMessage response = httpClient.PostAsync(new Uri(loginPostURL), httpContent).Result;

            response.EnsureSuccessStatusCode();
            String result = response.Content.ReadAsStringAsync().Result;

            if (response.StatusCode.Equals(HttpStatusCode.OK))
            {
                //var cookies = HttpHelper.GetAllCookies(cookieContainer);
                //return HttpHelper.GetAllCookies(cookieContainer).FirstOrDefault(c => c.Name.Equals("BDUSS")) != null;
                int    i1    = result.IndexOf("err_no=");
                int    i2    = result.IndexOf("&callback=");
                string errno = result.Substring(i1, i2 - i1).Replace("err_no=", "");
                switch (errno)
                {
                case "-1":
                    res = "系统错误,请您稍后再试";
                    break;

                case "2":
                    res = "您输入的帐号不存在";
                    break;

                case "4":
                    res = "您输入的帐号或密码有误 field : password";
                    break;

                case "6":
                    res = "您输入的验证码有误 field : verifyCode";
                    break;

                case "7":
                    res = "密码错误";
                    break;

                case "257":
                    res = "需要填入验证码";
                    break;

                default:
                    res = "errno:" + errno;
                    break;
                }
            }
            //httpClient.Dispose();
            return(res);
        }
Example #16
0
        public override bool Register(string username, string password)
        {
            ClientHandlr = new HttpClientHandler {
                UseCookies = true, AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, Proxy = this.Prox, UseProxy = Prox != null
            };
            Client = new HttpClient(ClientHandlr)
            {
                BaseAddress = new Uri("https://kingdice.com/api/")
            };
            Client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
            Client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("deflate"));
            try
            {
                List <KeyValuePair <string, string> > pairs = new List <KeyValuePair <string, string> >();
                pairs.Add(new KeyValuePair <string, string>("username", username));
                pairs.Add(new KeyValuePair <string, string>("aff", "221"));

                FormUrlEncodedContent Content = new FormUrlEncodedContent(pairs);
                string sEmitResponse          = Client.PostAsync("register.php", Content).Result.Content.ReadAsStringAsync().Result;

                KDLogin tmplogin = json.JsonDeserialize <KDLogin>(sEmitResponse);
                if (tmplogin.code == "SUCCESS")
                {
                    accesstoken = tmplogin.token;
                    pairs       = new List <KeyValuePair <string, string> >();
                    pairs.Add(new KeyValuePair <string, string>("token", accesstoken));
                    Content       = new FormUrlEncodedContent(pairs);
                    sEmitResponse = Client.PostAsync("logged.php", Content).Result.Content.ReadAsStringAsync().Result;
                    //sEmitResponse2 = Client.GetStringAsync("logged.php").Result;
                    KDLoggedIn tmpStats = json.JsonDeserialize <KDLoggedIn>(sEmitResponse);
                    if (tmpStats.code == "SUCCESS")
                    {
                        pairs = new List <KeyValuePair <string, string> >();
                        pairs.Add(new KeyValuePair <string, string>("pass", password));
                        pairs.Add(new KeyValuePair <string, string>("token", accesstoken));
                        Content       = new FormUrlEncodedContent(pairs);
                        sEmitResponse = Client.PostAsync("setpass.php", Content).Result.Content.ReadAsStringAsync().Result;
                        KDLoggedIn tmpStats2 = json.JsonDeserialize <KDLoggedIn>(sEmitResponse);
                        if (tmpStats2.code == "SUCCESS")
                        {
                            balance = tmpStats.balance / 100000000m;
                            if (tmpStats.address != null)
                            {
                                Parent.updateDeposit(tmpStats.address);
                            }
                            pairs = new List <KeyValuePair <string, string> >();
                            pairs.Add(new KeyValuePair <string, string>("token", accesstoken));
                            Content       = new FormUrlEncodedContent(pairs);
                            sEmitResponse = Client.PostAsync("nextroll.php", Content).Result.Content.ReadAsStringAsync().Result;
                            KDNextRoll tmphash = json.JsonDeserialize <KDNextRoll>(sEmitResponse);
                            if (tmphash.code == "SUCCESS")
                            {
                                LastHash = tmphash.round_hash;

                                iskd = true;
                                Thread t = new Thread(GetBalanceThread);
                                finishedlogin(true);
                                return(true);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Parent.DumpLog(e.ToString(), 1);
            }
            finishedlogin(false);
            return(false);
        }
Example #17
0
        public override void Login(string Username, string Password, string twofa)
        {
            ClientHandlr = new HttpClientHandler {
                UseCookies = true, AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, Proxy = this.Prox, UseProxy = Prox != null
            };
            Client = new HttpClient(ClientHandlr)
            {
                BaseAddress = new Uri("https://kingdice.com/api/")
            };
            Client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
            Client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("deflate"));
            Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
            Client.DefaultRequestHeaders.Add("Host", "kingdice.com");
            Client.DefaultRequestHeaders.Add("Origin", "https://kingdice.com");
            Client.DefaultRequestHeaders.Add("Referer", "https://kingdice.com");

            try
            {
                this.username = Username;
                List <KeyValuePair <string, string> > pairs = new List <KeyValuePair <string, string> >();
                pairs.Add(new KeyValuePair <string, string>("username", Username));
                pairs.Add(new KeyValuePair <string, string>("password", Password));
                pairs.Add(new KeyValuePair <string, string>("sdb", "8043d46408307f3ac9d14931ba27c9015349bf21b7b7"));
                pairs.Add(new KeyValuePair <string, string>("2facode", twofa /*==""?"undefined":twofa*/));
                FormUrlEncodedContent Content = new FormUrlEncodedContent(pairs);
                string sEmitResponse          = Client.PostAsync("login.php", Content).Result.Content.ReadAsStringAsync().Result;

                KDLogin tmplogin = json.JsonDeserialize <KDLogin>(sEmitResponse);
                if (tmplogin.code == "SUCCESS")
                {
                    accesstoken = tmplogin.token;
                    pairs       = new List <KeyValuePair <string, string> >();
                    pairs.Add(new KeyValuePair <string, string>("token", accesstoken));
                    Content       = new FormUrlEncodedContent(pairs);
                    sEmitResponse = Client.PostAsync("logged.php", Content).Result.Content.ReadAsStringAsync().Result;
                    //sEmitResponse2 = Client.GetStringAsync("logged.php").Result;
                    KDLoggedIn tmpStats = json.JsonDeserialize <KDLoggedIn>(sEmitResponse);
                    if (tmpStats.code == "SUCCESS")
                    {
                        balance = tmpStats.balance / 100000000m;
                        if (tmpStats.address != null)
                        {
                            Parent.updateDeposit(tmpStats.address);
                        }
                        pairs = new List <KeyValuePair <string, string> >();
                        pairs.Add(new KeyValuePair <string, string>("token", accesstoken));
                        Content       = new FormUrlEncodedContent(pairs);
                        sEmitResponse = Client.PostAsync("nextroll.php", Content).Result.Content.ReadAsStringAsync().Result;
                        KDNextRoll tmphash = json.JsonDeserialize <KDNextRoll>(sEmitResponse);
                        if (tmphash.code == "SUCCESS")
                        {
                            LastHash = tmphash.round_hash;
                            pairs    = new List <KeyValuePair <string, string> >();
                            pairs.Add(new KeyValuePair <string, string>("username", username));
                            pairs.Add(new KeyValuePair <string, string>("token", accesstoken));
                            Content       = new FormUrlEncodedContent(pairs);
                            sEmitResponse = Client.PostAsync("stats/profile.php", Content).Result.Content.ReadAsStringAsync().Result;
                            KDStat tmpstats = json.JsonDeserialize <KDStat>(sEmitResponse);
                            wagered = tmpstats.wagered / 100000000m;
                            profit  = tmpstats.profit / 100000000m;
                            bets    = (int)tmpstats.rolls;
                            Parent.updateBets(bets);
                            Parent.updateProfit(profit);
                            Parent.updateWagered(wagered);
                            iskd = true;
                            Thread t = new Thread(GetBalanceThread);
                            t.Start();
                            Parent.updateBalance(balance);
                            finishedlogin(true);
                            return;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Parent.DumpLog(e.ToString(), 1);
            }
            finishedlogin(false);
        }
Example #18
0
        public StatsService(DiscordSocketClient client, CommandHandler cmdHandler,
                            IBotCredentials creds, NadekoBot nadeko, IDataCache cache, IHttpClientFactory factory)
        {
            _log         = LogManager.GetCurrentClassLogger();
            _client      = client;
            _creds       = creds;
            _redis       = cache.Redis;
            _httpFactory = factory;

            _started = DateTime.UtcNow;
            _client.MessageReceived    += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter));
            cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan));

            _client.ChannelCreated += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Increment(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Increment(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.ChannelDestroyed += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Decrement(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Decrement(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.GuildAvailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.JoinedGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.GuildUnavailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            _client.LeftGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            if (_client.ShardId == 0)
            {
                _carbonitexTimer = new Timer(async(state) =>
                {
                    if (string.IsNullOrWhiteSpace(_creds.CarbonKey))
                    {
                        return;
                    }
                    try
                    {
                        using (var http = _httpFactory.CreateClient())
                        {
                            using (var content = new FormUrlEncodedContent(
                                       new Dictionary <string, string> {
                                { "servercount", nadeko.GuildCount.ToString() },
                                { "key", _creds.CarbonKey }
                            }))
                            {
                                content.Headers.Clear();
                                content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                                using (await http.PostAsync(new Uri("https://www.carbonitex.net/discord/data/botdata.php"), content).ConfigureAwait(false)) { }
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
            }
            _botlistTimer = new Timer(async(state) =>
            {
                if (string.IsNullOrWhiteSpace(_creds.BotListToken))
                {
                    return;
                }
                try
                {
                    using (var http = _httpFactory.CreateClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                                   new Dictionary <string, string> {
                            { "shard_count", _creds.TotalShards.ToString() },
                            { "shard_id", client.ShardId.ToString() },
                            { "server_count", client.Guilds.Count().ToString() }
                        }))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken);

                            using (await http.PostAsync(new Uri($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats"), content).ConfigureAwait(false)) { }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                    //ignored
                }
            }, null, TimeSpan.FromMinutes(5), TimeSpan.FromHours(1));

            var platform = "other";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                platform = "linux";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                platform = "osx";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                platform = "windows";
            }

            _dataTimer = new Timer(async(state) =>
            {
                try
                {
                    using (var http = _httpFactory.CreateClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                                   new Dictionary <string, string> {
                            { "id", string.Concat(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(_creds.ClientId.ToString())).Select(x => x.ToString("X2"))) },
                            { "guildCount", nadeko.GuildCount.ToString() },
                            { "version", BotVersion },
                            { "platform", platform }
                        }))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                            using (await http.PostAsync(new Uri("https://selfstats.nadekobot.me/"), content).ConfigureAwait(false)) { }
                        }
                    }
                }
                catch
                {
                    // ignored
                }
            }, null, TimeSpan.FromSeconds(1), TimeSpan.FromHours(1));
        }
        [Route("{conversationId}/activities")]  // Matches 'v3/conversations/{conversationId}/activities'
        async public Task <HttpResponseMessage> SendToConversation(string conversationId, [FromBody] Activity activity)
        {
            MockTurn            turn;
            HttpResponseMessage response;
            var requestBody = new Dictionary <string, string>();

            requestBody.Add("grant_type", "client_credentials");
            requestBody.Add("client_id", _appID);
            requestBody.Add("client_secret", _appPassword);
            requestBody.Add("scope", $"{_appID}/.default");

            // Get BearerToken if we haven't yet
            if (_tokenResponse == null)
            {
                using (var bearerContent = new FormUrlEncodedContent(requestBody))
                {
                    if (!_tokenClient.DefaultRequestHeaders.Contains("Host"))
                    {
                        _tokenClient.DefaultRequestHeaders.Add("Host", "login.microsoftonline.com");
                    }

                    // Send the request
                    response = await _tokenClient.PostAsync(new Uri("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"), bearerContent);

                    _tokenResponse = JsonConvert.DeserializeObject <TokenResponse>(await response.Content.ReadAsStringAsync());
                }
            }

            // Add incoming Activity to Turn database
            lock (_conversationLock)
            {
                if (_activityCount == 0)
                {
                    // Start timer for test so we can calculate message per second on summary
                    _startOfTest.Start();
                }

                // Get new activity ID
                activity.Id = (++_activityCount).ToString();

                turn = new MockTurn()
                {
                    Activity = activity
                };

                _turns.Add(long.Parse(activity.Id), turn);
            }

            // Send Activity to bot's endpoint
            using (StringContent activityContent = new StringContent(JsonConvert.SerializeObject(activity), Encoding.UTF8, "application/json"))
            {
                if (!_botClient.DefaultRequestHeaders.Contains("Authorization"))
                {
                    _botClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_tokenResponse.access_token}");
                }

                System.Diagnostics.Debug.WriteLine($"MockChannel SendActivity - activity.Conversation.Id - {activity.Conversation.Id}, activity.Id - {activity.Id}, activity.ServiceUrl - {activity.ServiceUrl} activity.GetActivityType - {activity.GetActivityType()}, activity.Text - {activity.Text}");

                // Start the Turn timer
                turn.TurnStart.Start();

                // Send the request
                response = await _botClient.PostAsync(new Uri(_botEndpoint), activityContent);
            }

            return(Request.CreateResponse(response.StatusCode, new ResourceResponse(id: activity.Id)));
        }
Example #20
0
        public static async Task <ServerResponseStatus> TryRegister(string username, string password, string email, string contact)
        {
            try
            {
                var url        = "https://maempedia.com/register.html";
                var requestURI = $"{url}?key={apiKey}";

                var client = new HttpClient()
                {
                    Timeout = TimeSpan.FromSeconds(TIMEOUT)
                };

                var values = new Dictionary <string, string>
                {
                    { "username", username },
                    { "password", password },
                    { "email", email },
                    { "wacontact", contact },
                    { "name", username }
                };
                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(requestURI, content);

                if (!response.IsSuccessStatusCode)
                {
                    Debug.WriteLine("Maempedia HTTP request denied.");
                    return(ServerResponseStatus.ERROR);
                }

                var result = await response.Content.ReadAsStringAsync();

                if (result == null)
                {
                    Debug.WriteLine("Maempedia API has returned nothing.");
                    return(ServerResponseStatus.ERROR);
                }

                JObject json = null;
                try
                {
                    json = JObject.Parse(result);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException);
                    return(ServerResponseStatus.ERROR);
                }

                if (json["status"].ToString() == "SUCCESS")
                {
                    Owner newOwner = new Owner()
                    {
                        ID                  = json["owner"]["id"].ToString(),
                        Username            = json["owner"]["username"].ToString(),
                        Password            = json["owner"]["password"].ToString(),
                        Email               = json["owner"]["email"].ToString(),
                        ContactWA           = json["owner"]["wacontact"].ToString(),
                        Name                = json["owner"]["username"].ToString(),
                        ProfilePicture      = json["owner"]["photo_url"].ToString(),
                        ProfilePictureThumb = json["owner"]["photo_thumb_url"].ToString()
                    };

                    App.User.SetUser(newOwner);
                    return(ServerResponseStatus.VALID);
                }
                else
                {
                    return(ServerResponseStatus.INVALID);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(ServerResponseStatus.ERROR);
            }
        }
Example #21
0
        public User AuthenticateOnline(string email, string password)
        {
            User       user     = null;
            HttpClient client   = AppState.CreateClient(ServiceType.OnPremiseWebApi.ToString());
            var        formData = new FormUrlEncodedContent(new[] {
                new KeyValuePair <string, string>("grant_type", "password"),
                new KeyValuePair <string, string>("username", email),
                new KeyValuePair <string, string>("password", password)
            });

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                       EncodeToBase64(string.Format("{0}:{1}",
                                                                                                                    applicationCode,
                                                                                                                    applicationSecretPass)));
            var response = client.PostAsync("/Authenticate", formData).Result;

            if (response.IsSuccessStatusCode)
            {
                var jsondata = response.Content.ReadAsStringAsync().Result;
                var token    = JsonConvert.DeserializeObject <AccessToken>(jsondata);
                AppState.Instance.OnPremiseToken = token;
                client.Dispose();
                client = AppState.CreateClient(ServiceType.OnPremiseWebApi.ToString());
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.access_token);
                response = client.GetAsync("api/user/UserById/" + token.Id).Result;
                if (response.IsSuccessStatusCode)
                {
                    jsondata = response.Content.ReadAsStringAsync().Result;
                    user     = JsonConvert.DeserializeObject <User>(jsondata);
                    AppState.Instance.IsSuperAdmin = false;
                    if (user.Roles.Contains("SuperAdmin"))
                    {
                        client.Dispose();
                        var formData1 = new FormUrlEncodedContent(new[] {
                            new KeyValuePair <string, string>("grant_type", "password"),
                            new KeyValuePair <string, string>("username", email),
                            new KeyValuePair <string, string>("password", password)
                        });
                        client = AppState.CreateClient(ServiceType.OnPremiseWebApi.ToString());
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                                   EncodeToBase64(string.Format("{0}:{1}",
                                                                                                                                applicationCode,
                                                                                                                                applicationSecretPass)));
                        response = client.PostAsync("/Authenticate", formData1).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            jsondata = response.Content.ReadAsStringAsync().Result;
                            token    = JsonConvert.DeserializeObject <AccessToken>(jsondata);
                            AppState.Instance.CentralizedToken = token;
                        }
                        AppState.Instance.IsSuperAdmin = true;
                    }

                    CreateCredentialFile(user, password);
                    if (AppState.Instance.IsSuperAdmin)
                    {
                        SynchPurchaseOrder(user.ServerUserId);
                    }
                }
            }
            else
            {
                ErrorMessage = "Invalid User Name or Password";
            }
            return(user);
        }
Example #22
0
        public static async Task <ServerResponseStatus> UpdateAccount(Models.Owner owner, byte[] image = null)
        {
            try
            {
                var url        = "https://maempedia.com/update_account.html";
                var requestURI = $"{url}?id={owner.ID}&key={apiKey}";

                var client = new HttpClient()
                {
                    Timeout = TimeSpan.FromSeconds(TIMEOUT)
                };

                var values = new Dictionary <string, string>
                {
                    { "username", owner.Username },
                    { "password", owner.Password },
                    { "email", owner.Email },
                    { "name", owner.Name },
                    { "opening_hour", owner.OpeningHour },
                    { "closing_hour", owner.ClosingHour },
                    { "description", owner.Headline },
                    { "location_address", owner.Location.Address },
                    { "location_lat", owner.Location.Latitude.ToString() },
                    { "location_lng", owner.Location.Longitude.ToString() },
                    { "wacontact", owner.ContactWA },
                    { "contact", owner.ContactNumber },
                    { "is_maemseller", owner.IsMaemseller.ToString() }
                };
                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(requestURI, content);

                if (!response.IsSuccessStatusCode)
                {
                    Debug.WriteLine("Maempedia HTTP request denied.");
                    return(ServerResponseStatus.ERROR);
                }

                var result = await response.Content.ReadAsStringAsync();

                if (result == null)
                {
                    Debug.WriteLine("Maempedia API has returned nothing.");
                    return(ServerResponseStatus.ERROR);
                }

                JObject json = null;
                try
                {
                    json = JObject.Parse(result);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException);
                    return(ServerResponseStatus.ERROR);
                }

                if (json["status"].ToString() != "SUCCESS")
                {
                    return(ServerResponseStatus.INVALID);
                }

                if (image == null)
                {
                    return(ServerResponseStatus.VALID);
                }

                return(await UploadImage(image, owner.ID));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(ServerResponseStatus.ERROR);
            }
        }
        private async void btn_ProceedClicked(object sender, EventArgs e)
        {
            btnProceed.IsVisible = false;
            ShowLoading(true);
            IsOnline = VerifyInternet();
            if (IsOnline)
            {
                if (txtPhoneNumber.Text != "" && txtPhoneNumber.Text != null)
                {
                    if (txtPhoneNumber.Text.Length != 10)
                    {
                        btnProceed.IsVisible = true;
                        ShowLoading(false);
                        DisplayAlert("", "Please enter valid Phone Number", "Ok");
                        return;
                    }

                    Customer objCustomer = new Customer();
                    objCustomer.PhoneNumber = txtPhoneNumber.Text;

                    // Remove Code

                    using (HttpClient client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(Convert.ToString(App.Current.Properties["BaseURL"]));
                        // We want the response to be JSON.
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        List <KeyValuePair <string, string> > postData = new List <KeyValuePair <string, string> >();
                        postData.Add(new KeyValuePair <string, string>("grant_type", "password"));
                        postData.Add(new KeyValuePair <string, string>("username", "Kiran"));
                        postData.Add(new KeyValuePair <string, string>("password", "1234"));
                        FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
                        // Post to the Server and parse the response.
                        var response = client.PostAsync("Token", content).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            var        jsonString   = response.Content.ReadAsStringAsync();
                            OAuthToken responseData = JsonConvert.DeserializeObject <OAuthToken>(jsonString.Result);
                            string     Access_Token = responseData.access_token;
                            App.Current.Properties["apitoken"] = Access_Token;
                        }
                    }

                    // Remove Code

                    if (App.Current.Properties.ContainsKey("apitoken"))
                    {
                        var json    = JsonConvert.SerializeObject(objCustomer);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        dal_Customer = new DALCustomer();
                        OCustomer resultObj = dal_Customer.ValidateCustomer(Convert.ToString(App.Current.Properties["apitoken"]), objCustomer);

                        if (resultObj.CustomerID != 0)
                        {
                            btnProceed.IsVisible = true;
                            ShowLoading(false);
                            await Navigation.PushAsync(new VerifyOTP(txtPhoneNumber.Text, resultObj.CustomerID, "EXISTING", resultObj.Name));
                        }
                        else
                        {
                            btnProceed.IsVisible = true;
                            ShowLoading(false);
                            await Navigation.PushAsync(new SignUp(resultObj.CustomerID, txtPhoneNumber.Text));
                        }
                    }
                    else
                    {
                        btnProceed.IsVisible = true;
                        ShowLoading(false);
                    }
                }
                else
                {
                    btnProceed.IsVisible = true;
                    ShowLoading(false);
                    DisplayAlert("", "Please enter your Phone Number", "Ok");
                }
            }
            else
            {
                await DisplayAlert("", "Please check your network connectivity", "Ok");

                return;
            }
        }
Example #24
0
        public static async Task <ServerResponseStatus> SendFeedback(string id, string comment, string suggestion)
        {
            try
            {
                var url        = "https://maempedia.com/feedbacks.html";
                var requestURI = $"{url}?id={id}&key={apiKey}";

                var client = new HttpClient()
                {
                    Timeout = TimeSpan.FromSeconds(TIMEOUT)
                };

                var values = new Dictionary <string, string>
                {
                    { "comment", comment },
                    { "suggestion", suggestion }
                };
                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(requestURI, content);

                if (!response.IsSuccessStatusCode)
                {
                    Debug.WriteLine("Maempedia HTTP request denied.");
                    return(ServerResponseStatus.ERROR);
                }

                var result = await response.Content.ReadAsStringAsync();

                if (result == null)
                {
                    Debug.WriteLine("Maempedia API has returned nothing.");
                    return(ServerResponseStatus.ERROR);
                }

                JObject json = null;
                try
                {
                    json = JObject.Parse(result);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException);
                    return(ServerResponseStatus.ERROR);
                }

                if (json["status"].ToString() == "SUCCESS")
                {
                    return(ServerResponseStatus.VALID);
                }
                else
                {
                    return(ServerResponseStatus.INVALID);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException);
                return(ServerResponseStatus.ERROR);
            }
        }
Example #25
0
        /// <summary>
        /// Регистрация физического лица.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static async Task <ServiceResponseObject <RegisterResponse> > RegisterIndividual(RegisterIndividualModel model)
        {
            try
            {
                //status & message
                var formContent = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "login", model.Login },
                    { "password", model.Password },
                    { "email", model.Email },
                    { "phone", model.Phone },
                    { "client_type", model.ClientType },
                    { "client_last_name", model.ClientLastName },
                    { "client_name", model.ClientName },
                    { "client_patronymic", model.ClientPatronymic },
                    { "client_birthday", model.ClientBirthday },
                    { "client_passport_serie", model.ClientPassportSerie },
                    { "client_passport_id", model.ClientPassportId },
                    { "client_passport_code", model.ClientPassportCode }
                });

                HttpResponseMessage response = await _httpClient.PostAsync($"client", formContent);

                string s_result;
                using (HttpContent responseContent = response.Content)
                {
                    s_result = await responseContent.ReadAsStringAsync();
                }

                ServiceResponseObject <RegisterResponse> o_data = new ServiceResponseObject <RegisterResponse>();

                switch (response.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                {
                    ErrorResponseObject error = new ErrorResponseObject();
                    error          = JsonConvert.DeserializeObject <ErrorResponseObject>(s_result);
                    o_data.Status  = response.StatusCode;
                    o_data.Message = error.Errors[0];
                    return(o_data);
                }

                case HttpStatusCode.InternalServerError:
                {
                    ErrorResponseObject error = new ErrorResponseObject();
                    o_data.Status  = response.StatusCode;
                    o_data.Message = "Внутренняя ошибка сервера 500";
                    return(o_data);
                }

                case HttpStatusCode.NotFound:
                {
                    ErrorResponseObject error = new ErrorResponseObject();
                    o_data.Status  = response.StatusCode;
                    o_data.Message = "Ресурс не найден 404";
                    return(o_data);
                }

                case HttpStatusCode.OK:
                {
                    var reg = JsonConvert.DeserializeObject <RegisterResponse>(s_result);
                    o_data.Message      = reg.message;
                    o_data.Status       = response.StatusCode;
                    o_data.ResponseData = new RegisterResponse
                    {
                        message = reg.message,
                        user    = reg.user
                    };
                    return(o_data);
                }

                default:
                {
                    throw new Exception(response.StatusCode.ToString() + " Server Error");
                }
                }
            }
            catch (Exception ex)
            {
                ServiceResponseObject <RegisterResponse> o_data = new ServiceResponseObject <RegisterResponse>();
                o_data.Message = ex.Message;
                return(o_data);
            }
        }
Example #26
0
        private async void AddTodoItem(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            //
            // Get an access token to call the To Do service.
            //
            AuthenticationResult result = null;

            try
            {
                result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId);
            }
            catch (AdalException ex)
            {
                // There is no access token in the cache, so prompt the user to sign-in.
                if (ex.ErrorCode == FAILED_SILENT)
                {
                    MessageBox.Show("Please sign in first");
                    SignInButton.Content = "Sign In";
                }
                else
                {
                    // An unexpected error occurred.
                    string message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        message += "Inner Exception : " + ex.InnerException.Message;
                    }

                    MessageBox.Show(message);
                }

                return;
            }

            //
            // Call the To Do service.
            //

            // Once the token has been returned by ADAL, add it to the http authorization header, before making the call to access the To Do service.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode Todo item, to POST to the todo list web api.
            HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("Title", TodoText.Text) });

            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "api/todolist", content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                await GetTodoList();
            }
            else
            {
                MessageBox.Show("An error occurred : " + response.ReasonPhrase);
            }
        }
Example #27
0
        public async Task <string[]> login()
        {
            string url = @"https://updateasc.netservicos.com.br/home/portal.do";

            Dictionary <string, string> form_data = new Dictionary <string, string>
            {
                { "token", "20160708*[email protected]" },
                { "login", "Enter Here" }
            };

            HttpClient client = new HttpClient(
                new HttpClientHandler
            {
                UseCookies             = false,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            });

            client.Timeout = TimeSpan.FromHours(2);

            string[] AcceptEncoding = new string[] { "gzip", "deflate" };

            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Accept", "*/*");
            client.DefaultRequestHeaders.Add("Accept-Language", "pt-BR");
            client.DefaultRequestHeaders.Add("Accept-Encoding", AcceptEncoding);
            client.DefaultRequestHeaders.Add("Referer", "wanet01.netservicos.com.br");
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)");
            client.DefaultRequestHeaders.Add("Host", "updateasc.netservicos.com.br");
            client.DefaultRequestHeaders.Add("Cookie", "asc-key-remote=" + Config.ASC_KEY_REMOTE + ";BIGipServerpool_netascs_https=2244091146.47873.0000; BIGipServerPOOL-ASC_HTTPS=370744586.20480.0000; BIGipServerpool_netasc_https=2193759498.47873.00");

            HttpContent         content  = new FormUrlEncodedContent(form_data);
            HttpResponseMessage response = await client.PostAsync(url, content);

            var contents = await response.Content.ReadAsStringAsync();

            HttpContentHeaders headers = content.Headers;

            if (response.IsSuccessStatusCode)
            {
                try
                {
                    string resposta       = response.Headers.ToString();
                    int    postion_incial = resposta.IndexOf("Set-Cookie:");
                    Config.ASC_JSESSIONID = resposta.Substring(postion_incial, 75).Replace("Set-Cookie: ", "");

                    return(new string[]
                    {
                        Config.ASC_KEY_REMOTE,
                        Config.ASC_JSESSIONID
                    });
                }
                catch (Exception)
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
        public async Task Ctor_AllAsciiChars_EncodingMatchesHttpUtilty()
        {
            var builder = new StringBuilder();
            for (int ch = 0; ch < 128; ch++)
            {
                builder.Append((char)ch);
            }
            string testString = builder.ToString();

            var data = new Dictionary<string, string>();
            data.Add("key", testString);
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            string result = new StreamReader(stream).ReadToEnd().ToLowerInvariant();

            // Result of UrlEncode invoked in .Net 4.6
            // string expectedResult = "key=" + HttpUtility.UrlEncode(testString).ToLowerInvariant();
            // HttpUtility is not part of ProjectK.

            string expectedResult = "key=%00%01%02%03%04%05%06%07%08%09%0a%0b%0c%0d%0e%0f%10%11%12%13%14%15%16%17%18" +
                "%19%1a%1b%1c%1d%1e%1f+!%22%23%24%25%26%27()*%2b%2c-.%2f0123456789%3a%3b%3c%3d%3e%3f%40abcdefghijklm" +
                "nopqrstuvwxyz%5b%5c%5d%5e_%60abcdefghijklmnopqrstuvwxyz%7b%7c%7d%7e%7f";

            string knownDiscrepancies = "~!*()";

            _output.WriteLine("Expecting result: '{0}'", expectedResult);
            _output.WriteLine("Actual result   : '{0}'", result);

            int discrepancies = 0;
            for (int i = 0; i < result.Length && i < expectedResult.Length; i++)
            {
                if (result[i] != expectedResult[i])
                {
                    Assert.True((result[i] == '%' || expectedResult[i] == '%'),
                        "Non-Escaping mis-match at position: " + i);

                    if (result[i] == '%')
                    {
                        Assert.True(knownDiscrepancies.Contains(expectedResult[i]),
                            "Escaped when it shouldn't be: " + expectedResult[i] + " at position " + i);
                        result = result.Substring(i + 3);
                        expectedResult = expectedResult.Substring(i + 1);
                    }
                    else
                    {
                        Assert.True(knownDiscrepancies.Contains(result[i]),
                            "Not escaped when it should be : " + result[i] + " at position " + i);
                        result = result.Substring(i + 1);
                        expectedResult = expectedResult.Substring(i + 3);
                    }
                    i = -1;
                    discrepancies++;
                }
            }
            Assert.Equal(5, discrepancies);
        }
        public SendNotificationPage()
        {
            InitializeComponent();

            Title = "Enviar notificação";

            ObservableCollection <Event> listEvents = MainPage.Instance.listEvents;

            if (listEvents.Count > 0)
            {
                Dictionary <string, Event> events = new Dictionary <string, Event>();

                foreach (Event _event in listEvents)
                {
                    events.Add(_event.Name, _event);
                }

                foreach (string name in events.Keys)
                {
                    Events.Items.Add(name);
                }

                Events.SelectedIndex = 0;

                ToAll.Toggled += (s, e) =>
                {
                    StackPicker.IsVisible = !ToAll.IsToggled;
                };
            }
            else
            {
                ToAllGrid.IsVisible   = false;
                StackPicker.IsVisible = false;
            }

            Send.Clicked += async(s, ev) =>
            {
                Send.IsEnabled = false;

                try
                {
                    var postData = new List <KeyValuePair <string, string> >();
                    postData.Add(new KeyValuePair <string, string>("app_key", Other.Other.AppKey));
                    postData.Add(new KeyValuePair <string, string>("title", TextTitle.Text));
                    postData.Add(new KeyValuePair <string, string>("link", Link.Text));
                    postData.Add(new KeyValuePair <string, string>("image", Image.Text));
                    postData.Add(new KeyValuePair <string, string>("message", Message.Text));
                    if (!ToAll.IsToggled)
                    {
                        postData.Add(new KeyValuePair <string, string>("eventid", listEvents[Events.SelectedIndex].Id.ToString()));
                    }
                    postData.Add(new KeyValuePair <string, string>("refresh_token", Other.Other.GetSetting("refresh_token")));

                    var content = new FormUrlEncodedContent(postData);

                    var client = new HttpClient();
                    client.MaxResponseContentBufferSize = 256000;
                    HttpResponseMessage response = await client.PostAsync(Other.Other.GetNotificationUrl(), content);

                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();

                        switch (result)
                        {
                        case "notification_send":
                            Other.Other.ShowMessage("Notificação enviada com sucesso", this);
                            await Navigation.PopAsync();

                            break;

                        case "invalid_user":
                            Other.Other.ShowMessage("Usuário inválido", this);
                            (s as Button).IsEnabled = true;
                            break;

                        case "try_again":
                            Other.Other.ShowMessage("Houve um erro, tente novamente", this);
                            (s as Button).IsEnabled = true;
                            break;
                        }
                    }
                    else
                    {
                        (s as Button).IsEnabled = true;
                        Other.Other.ShowMessage("Houve um erro ao enviar os dados, tente novamente", this);
                    }
                }
                catch
                {
                    (s as Button).IsEnabled = true;
                    Other.Other.ShowMessage("Houve um erro ao enviar os dados, tente novamente", this);
                }
            };
        }
Example #30
0
        /// <summary>
        /// Authentication against Jive API
        /// Requires admin credentials in order to do impersonation
        /// </summary>
        public bool Authentify()
        {
            try
            {
                string     resultfinal   = "no result";
                string     resultrequest = "";
                HttpClient client        = new HttpClient();
                _logger.Log(new LogEntry(LoggingEventType.Debug, "Starting authentication"));

                var authHeader = new AuthenticationHeaderValue("basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(OauthId + ":" + OauthSecret)));
                client.DefaultRequestHeaders.Authorization = authHeader;

                // Create the HttpContent for the form to be posted.
                var requestContent = new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", Username),
                    new KeyValuePair <string, string>("password", Password)
                });

                // FOR TESTING PURPOSE ONLY : overriding certificate validation
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                // Get the response.
                var task = System.Threading.Tasks.Task.Run(async() => await client.PostAsync(AuthenticationURI, requestContent));
                task.Wait();
                HttpResponseMessage response = task.Result;

                // Get the response content.
                HttpContent responseContent = response.Content;

                // Get the stream of the content.
                var taskResult = System.Threading.Tasks.Task.Run(async() => await responseContent.ReadAsStreamAsync());
                taskResult.Wait();
                using (var reader = new StreamReader(taskResult.Result))
                {
                    // Write the output.
                    var taskResult2 = System.Threading.Tasks.Task.Run(async() => await reader.ReadToEndAsync());
                    taskResult2.Wait();
                    resultrequest = taskResult2.Result;
                    _logger.Log(new LogEntry(LoggingEventType.Debug, "Authentication result : " + taskResult2.ToString()));
                }

                dynamic stuff = JsonConvert.DeserializeObject(resultrequest);
                resultfinal = null;
                if (stuff.error != null)
                {
                    _logger.Log(new LogEntry(LoggingEventType.Error, "Authentication error : " + stuff.error_description));
                    throw new UnauthorizedAccessException("Error during authentication against API : " + stuff.error_description);
                }
                else if (stuff.access_token == null)
                {
                    _logger.Log(new LogEntry(LoggingEventType.Error, "Authentication error : " + stuff.error_description));
                    throw new UnauthorizedAccessException("Error during authentication against API. Acces token is null. " + stuff.error_description);
                }
                else
                {
                    resultfinal         = stuff.access_token;
                    this.IsAuthentified = true;
                    _accessToken        = resultfinal;
                    _logger.Log(new LogEntry(LoggingEventType.Debug, "Authentication result : " + resultfinal));
                    return(true);
                }
            }
            catch (Exception e)
            {
                _logger.Log(new LogEntry(LoggingEventType.Error, "Error during authentication. ", e));
                throw e;
            }
        }
Example #31
0
    private async Task Request()
    {
        Debug.Log("requesting...");
        string input_name     = extractFromInput(newName);
        string input_password = extractFromInput(password);
        string input_id       = extractFromInput(id);
        string phrase         = "not initialized";

        try
        {
            var content = new FormUrlEncodedContent(new KeyValuePair <string, string>[] {
                new KeyValuePair <string, string>("Name", input_name),
                new KeyValuePair <string, string>("Password", input_password),
                new KeyValuePair <string, string>("Id", input_id)
            });
            var msg = await client.PostAsync(url, content);

            phrase = await msg.Content.ReadAsStringAsync();

            msg.EnsureSuccessStatusCode();
        }
        catch (HttpRequestException)
        {
            Debug.Log("phrase: " + phrase);
            QueueOnMainThread(() => {
                panel.DisplayInfo(phrase);
            });
            return;
        }

        catch (InvalidOperationException)
        {
            QueueOnMainThread(() => {
                panel.DisplayInfo(phrase);
            });
            return;
        }

        catch (TaskCanceledException)
        {
            QueueOnMainThread(() => {
                panel.DisplayInfo(phrase);
            });
            return;
        }

        QueueOnMainThread(() => {
            Debug.Log("room id received: ..." + Int32.Parse(phrase));
            PlayerPrefs.SetInt("roomId", Int32.Parse(phrase));
            PlayerPrefs.SetString("newName", input_name);
            PlayerPrefs.SetString("password", input_password);
            PlayerPrefs.SetString("id", input_id);
            panel.DisplayInfo("loading scene...");
            try
            {
                SceneManager.LoadScene("GameScene_1");
            }
            catch (Exception) {
                panel.DisplayInfo("error occurs!");
            }
        });
    }
Example #32
0
        public static MediaFoundationStreamingSources CreateFromニコ動(string user_id, string password, string video_id, WaveFormat soundDeviceFormat)
        {
            var sources = new MediaFoundationStreamingSources();

            #region " ニコ動から SourceReaderEx を生成する。"
            //----------------
            if (null == _HttpClient)
            {
                _HttpClient = new HttpClient();
            }

            // ログインする。
            var content = new FormUrlEncodedContent(new Dictionary <string, string> {
                { "mail", user_id },
                { "password", password },
                { "next_url", string.Empty },
            });
            using (var responseLogin = _HttpClient.PostAsync("https://secure.nicovideo.jp/secure/login?site=niconico", content).Result)
            {
            }

            // 動画ページにアクセスする。(getflvより前に)
            var responseWatch = _HttpClient.GetStringAsync($"http://www.nicovideo.jp/watch/{video_id}").Result;

            // 動画情報を取得する。
            var responseGetFlv = _HttpClient.GetStringAsync($"http://flapi.nicovideo.jp/api/getflv/{video_id}").Result;
            var flvmap         = HttpUtility.ParseQueryString(responseGetFlv);
            var flvurl         = flvmap["url"];

            // 動画の長さを取得する。
            ulong  長さbyte      = 0;
            string contentType = "";
            using (var requestMovie = new HttpRequestMessage(HttpMethod.Get, flvurl))
                using (var responseMovie = _HttpClient.SendAsync(requestMovie, HttpCompletionOption.ResponseHeadersRead).Result)
                {
                    長さbyte      = (ulong)(responseMovie.Content.Headers.ContentLength);
                    contentType = responseMovie.Content.Headers.ContentType.MediaType;
                }

            // IMFByteStream を生成する。
            sources._ByteStream                = new ByteStream(IntPtr.Zero);
            sources._HttpRandomAccessStream    = new HttpRandomAccessStream(_HttpClient, 長さbyte, flvurl);
            sources._unkHttpRandomAccessStream = new ComObject(Marshal.GetIUnknownForObject(sources._HttpRandomAccessStream));
            MediaFactory.CreateMFByteStreamOnStreamEx(sources._unkHttpRandomAccessStream, sources._ByteStream);
            using (var 属性 = sources._ByteStream.QueryInterfaceOrNull <MediaAttributes>())
            {
                // content-type を設定する。
                属性.Set(ByteStreamAttributeKeys.ContentType, contentType);
            }

            // SourceResolver で IMFByteStream から MediaSouce を取得する。
            using (var sourceResolver = new SourceResolver())
                using (var unkMediaSource = sourceResolver.CreateObjectFromStream(sources._ByteStream, null, SourceResolverFlags.MediaSource))
                {
                    sources._MediaSource = unkMediaSource.QueryInterface <MediaSource>();

                    // MediaSource から SourceReaderEx を生成する。
                    using (var 属性 = new MediaAttributes())
                    {
                        // DXVAに対応しているGPUの場合には、それをデコードに利用するよう指定する。
                        属性.Set(SourceReaderAttributeKeys.D3DManager, DXResources.Instance.MFDXGIDeviceManager);

                        // 追加のビデオプロセッシングを有効にする。
                        属性.Set(SourceReaderAttributeKeys.EnableAdvancedVideoProcessing, true); // 真偽値が bool だったり

                        // 追加のビデオプロセッシングを有効にしたら、こちらは無効に。
                        属性.Set(SinkWriterAttributeKeys.ReadwriteDisableConverters, 0);         // int だったり

                        // 属性を使って、SourceReaderEx を生成。
                        using (var sourceReader = new SourceReader(sources._MediaSource, 属性))
                        {
                            sources._SourceReaderEx = sourceReader.QueryInterfaceOrNull <SourceReaderEx>();
                        }
                    }
                }
            //----------------
            #endregion

            #region " WaveFormat を生成。"
            //----------------
            sources._Audioのフォーマット = new WaveFormat(
                soundDeviceFormat.SampleRate,
                32,
                soundDeviceFormat.Channels,
                AudioEncoding.IeeeFloat);
            //----------------
            #endregion

            sources._SourceReaderEx生成後の初期化();

            return(sources);
        }
Example #33
0
        //Método responsável por buscar os dados do veículo direto do site do governo
        private async Task <List <VeiculoModel> > ObterVeiculosTabelaFipe(CatalogoContext catalogoContext, string Referencia, int Ano)
        {
            //Configuração de proxy
            //Remover ou configurar de acordo com a necessidade
            HttpClient httpClient = new HttpClient(new HttpClientHandler()
            {
                UseProxy = true,
                Proxy    = null, // use system proxy
                DefaultProxyCredentials = new System.Net.NetworkCredential("fabio.souza", "fs123456")
            });

            //Retorna as tabelas de referência
            var resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarTabelaDeReferencia", null);

            //Cria uma lista de veículos
            List <VeiculoModel> lista = new List <VeiculoModel>();

            //Se o retorno é bem sucedido, prossegue
            if (resposta.IsSuccessStatusCode)
            {
                //Lê o conteúdo da resposta
                List <JObject> conteudo = await resposta.Content.ReadAsAsync <List <JObject> >();

                //Retorna o código da tabela de acordo com o ano informado
                var codigo_tabela = conteudo.Where(e => e.GetValue("Mes").ToString().Replace(" ", "") == Referencia).Select(e => e.GetValue("Codigo").ToString()).FirstOrDefault();

                //Se o código não é nulo, prossegue
                if (codigo_tabela != null)
                {
                    //Cria os parâmetros para a próxima requisição
                    var pairs = new List <KeyValuePair <string, string> >();
                    pairs.Add(new KeyValuePair <string, string>("codigoTabelaReferencia", codigo_tabela));
                    pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1"));

                    //cria o corpo da requisição
                    var body = new FormUrlEncodedContent(pairs);

                    //Retorna as marcas de acordo com a tabela de referência
                    resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarMarcas", body);

                    var marcas = await resposta.Content.ReadAsAsync <List <JObject> >();

                    //Percorre as marcas
                    for (var i = 0; i < marcas.Count; i++)
                    {
                        //Cria os parâmetros para a próxima requisição
                        pairs = new List <KeyValuePair <string, string> >();
                        pairs.Add(new KeyValuePair <string, string>("codigoTabelaReferencia", codigo_tabela));
                        pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1"));
                        pairs.Add(new KeyValuePair <string, string>("codigoMarca", marcas[i].GetValue("Value").ToString()));

                        //cria o corpo da requisição
                        body = new FormUrlEncodedContent(pairs);

                        //Retorna os modelos de acordo com a tabela de referência e marca
                        resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarModelos", body);

                        JObject Ano_Modelos = await resposta.Content.ReadAsAsync <JObject>();

                        List <JObject> Modelos = Ano_Modelos.GetValue("Modelos").ToObject <List <JObject> >();


                        //Percorre os modelos
                        for (var m = 0; m < Modelos.Count; m++)
                        {
                            //Cria os parâmetros para a próxima requisição
                            pairs = new List <KeyValuePair <string, string> >();
                            pairs.Add(new KeyValuePair <string, string>("codigoTabelaReferencia", codigo_tabela));
                            pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1"));
                            pairs.Add(new KeyValuePair <string, string>("codigoMarca", marcas[i].GetValue("Value").ToString()));
                            pairs.Add(new KeyValuePair <string, string>("codigoModelo", Modelos[m].GetValue("Value").ToString()));
                            pairs.Add(new KeyValuePair <string, string>("anoModelo", Ano.ToString()));
                            pairs.Add(new KeyValuePair <string, string>("codigoTipoVeiculo", "1"));
                            pairs.Add(new KeyValuePair <string, string>("codigoTipoCombustivel", "1"));
                            pairs.Add(new KeyValuePair <string, string>("tipoConsulta", "tradicional"));
                            pairs.Add(new KeyValuePair <string, string>("tipoVeiculo", "carro"));

                            //cria o corpo da requisição
                            body = new FormUrlEncodedContent(pairs);

                            //Retorna os dados do veículo de acordo com a tabela de referência, marca, modelo e ano do modelo
                            resposta = await httpClient.PostAsync("https://veiculos.fipe.org.br/api/veiculos//ConsultarValorComTodosParametros", body);

                            JObject Veiculo = await resposta.Content.ReadAsAsync <JObject>();

                            //Se o veículo é encontrado e possui valor, prossegue
                            if (Veiculo != null)
                            {
                                if (Veiculo.Property("Valor") != null)
                                {
                                    var style    = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
                                    var provider = new CultureInfo("pt-BR");

                                    string valor = Veiculo.GetValue("Valor").ToString();
                                    valor = valor.Replace("R$ ", "").Replace(".", "");

                                    VeiculoModel veiculoModel = new VeiculoModel()
                                    {
                                        AnoModelo  = short.Parse(Veiculo.GetValue("AnoModelo").ToString()),
                                        CodigoFipe = Veiculo.GetValue("CodigoFipe").ToString(),
                                        Marca      = Veiculo.GetValue("Marca").ToString(),
                                        Modelo     = Veiculo.GetValue("Modelo").ToString(),
                                        PrecoMedio = Decimal.Parse(valor, style, provider),
                                        Referencia = Referencia
                                    };

                                    //Adiciona o veículo no banco de dados
                                    var result = await Adicionar(catalogoContext, veiculoModel);

                                    //Se é adicionado com sucesso, adiciona na lista
                                    if (result.GetType() == typeof(VeiculoModel))
                                    {
                                        veiculoModel = (VeiculoModel) await Adicionar(catalogoContext, veiculoModel);

                                        lista.Add(veiculoModel);
                                    }


                                    //Limitado a 10 pois o processo leva muito tempo
                                    if (lista.Count >= 10)
                                    {
                                        return(lista);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //Retorna a lista
            return(lista);
        }
 /// <summary>
 /// サーバーへリクエストを送り、結果をHttpResponseMessageとして取得する。
 /// 直には呼ばないかも。
 /// </summary>
 /// <param name="serverUri"></param>
 /// <param name="postParm"></param>
 /// <returns></returns>
 async Task<HttpResponseMessage> GetResponse(Uri serverUri, Dictionary<string, string> postParams)
 {
     HttpContent encodedContent = new FormUrlEncodedContent(postParams);
     var responce = await Post(serverUri, encodedContent);
     return responce;
 }
Example #35
0
        //确认发布新启事
        private async void newItemSureAsync(object sender, RoutedEventArgs e)
        {
            //item / putItemInfo ? type = 1 & title = 寻找丢失黑色钱包一个 & label = 钱包 & content = blalalallalal & place = 和平大道 & longitude = 116.45555 & latitude = 39.87333
            int    type      = this.itemType;
            string title     = itemTitle.Text;
            string label     = itemCategory.Text;
            string content   = itemContent.Text;
            string place     = itemPlace.Text;
            string lostTime  = itemLostTime.Text;
            double longitude = (Application.Current as App).longitude;
            double latitude  = (Application.Current as App).latitude;

            if (title == "" || content == "")
            {
                ShowMessageDialog("标题和内容不允许为空!");
            }
            //要访问的接口路径
            var uri = new Uri("https://lostandfoundapp.chinacloudsites.cn/item/putItemInfo");

            // Always catch network exceptions for async methods
            try
            {
                HttpClient client = (Application.Current as App).client;
                //HttpClient client = new HttpClient();
                Dictionary <string, string> dict = new Dictionary <string, string>();;
                dict.Add("type", type.ToString());
                dict.Add("title", title);
                dict.Add("label", label);
                dict.Add("content", content);
                dict.Add("place", place);
                dict.Add("lostTime", lostTime);
                dict.Add("longitude", longitude.ToString());
                dict.Add("latitude", latitude.ToString());
                Debug.WriteLine("参数列表-发布启事");
                Debug.WriteLine(dict.ToString());
                FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(dict);
                HttpResponseMessage   response = await client.PostAsync(uri, formUrlEncodedContent);

                JObject resultObj = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                //如果status不为1,说明登录失败,将报错信息以弹框方式显示。
                if (int.Parse(resultObj["status"].ToString()) != 1)
                {
                    ShowMessageDialog(resultObj["msg"].ToString());
                }
                else
                {
                    //发布成功,跳转启事详情页面
                    ShowMessageDialog("发布成功!");
                    this.Frame.Navigate(typeof(itemInfo), int.Parse(resultObj["itemId"].ToString()));
                }
            }
            catch
            {
                // Details in ex.Message and ex.HResult.
            }

            async void ShowMessageDialog(string msg)
            {
                var msgDialog = new Windows.UI.Popups.MessageDialog(msg)
                {
                    Title = "提示"
                };

                msgDialog.Commands.Add(new Windows.UI.Popups.UICommand("确定"));
                await msgDialog.ShowAsync();
            }
        }
Example #36
0
        static async Task ChatHubServer2()
        {
            try
            {
                string        url        = "https://localhost:44327/chathub";
                HubConnection connection = new HubConnectionBuilder()
                                           .WithUrl(url, options =>
                {
                    Cookie authCookie             = new Cookie();
                    string username               = "******";
                    string password               = "******";
                    string authEndpoint           = "https://localhost:44327/account/login";
                    FormUrlEncodedContent content = new FormUrlEncodedContent(
                        new KeyValuePair <string, string>[]
                    {
                        new KeyValuePair <string, string>("Email", username),
                        new KeyValuePair <string, string>("Password", password)
                    }
                        );
                    HttpWebRequest request  = WebRequest.Create(authEndpoint) as HttpWebRequest;
                    request.Method          = "POST";
                    request.ContentType     = "application/x-www-form-urlencoded";
                    request.CookieContainer = new CookieContainer();
                    using (Stream stream = request.GetRequestStream())
                    {
                        string payload      = string.Concat("Email=", username, "&Password="******".AspNetCore.Identity.Application"];
                    }
                    if (authCookie != null)
                    {
                        options.Cookies.Add(authCookie);
                    }
                })
                                           .Build();
                //because the server keep alive interval is 1 minute
                //so the client server timeout must be set to 2 minutes
                connection.ServerTimeout = TimeSpan.FromMinutes(2);

                Console.WriteLine("Press CTRL+C to quit");
                Console.Write(">> ");
                string name = "Mirza";
                BlockingCollection <string> messages = new BlockingCollection <string>();
                connection.Closed += async(error) =>
                {
                    Console.WriteLine("Reconnecting...");
                    await Task.Delay(1000);

                    await connection.StartAsync();

                    Console.WriteLine($"Connected to {url}");
                };
                connection.On <string, string>("ReceiveMessage", (user, message) =>
                {
                    Console.Clear();
                    messages.Add($"<<{user}>> `{message}`");
                    foreach (string data in messages)
                    {
                        Console.WriteLine(data);
                    }
                    Console.Write("\n>> ");
                });
                await connection.StartAsync();

                while (true)
                {
                    string message = Console.ReadLine();
                    await connection.SendAsync("SendMessage", name, message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }