private void RequestToken()
 {
     var client = new RestClient("https://api.soundcloud.com");
     const string clientSecret = "";
     var request = new RestRequest("oauth2/token");
     string encodedBody = string.Format("code={0}&grant_type=authorization_code&client_id={1}&client_secret={2}&redirect_uri={3}",
         ReturnedCode, MyClientId, clientSecret, RedirectUrl);
     request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
     request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
     var response = client.Post<AuthorizationResponse>(request);
     Token = response.Data.AccessToken;
 }
        public Stream Build(IEnumerable<IContent> contents)
        {
            using (var htmlStream = _htmlGenerator.GenerateHtml(contents, Descriptor.SupportedFileExtension))
            using (var tmpStream = new MemoryStream())
            {
                htmlStream.CopyTo(tmpStream);

                var apiKey = _siteService.GetSiteSettings().As<DownloadAsPdfSettingsPart>().CloudConvertApiKey;

                var client = new RestClient("https://api.cloudconvert.org/");
                var request = new RestRequest("process");
                request.AddParameter("apikey", apiKey);
                request.AddParameter("inputformat", "html");
                request.AddParameter("outputformat", "pdf");
                request.AddParameter("converter", "unoconv");
                var response = client.Post<InitResponse>(request);
                var processUrl = response.Data.Url;
                if (response.StatusCode != HttpStatusCode.OK) throw new OrchardException(T("PDF generation failed as the CloudConvert API returned an error when trying to open the converion process. Status code: {0}. CloudConvert error message: {1}.", response.StatusCode, response.Data.Error));

                var processClient = new RestClient("https:" + processUrl);

                var uploadRequest = new RestRequest();
                uploadRequest.AddFile("file", tmpStream.ToArray(), "output.html");
                uploadRequest.AddParameter("input", "upload");
                uploadRequest.AddParameter("format", "pdf");
                var uploadResponse = processClient.Post(uploadRequest);
                if (uploadResponse.StatusCode != HttpStatusCode.OK) throw new OrchardException(T("PDF generation failed as the CloudConvert API returned an error when trying to upload the HTML file. Status code: {0}.", uploadResponse.StatusCode));

                var processResponse = processClient.Get<ProcessResponse>(new RestRequest());
                var tryCount = 0;
                while (processResponse.Data.Step != "finished" && tryCount < 20)
                {
                    Thread.Sleep(2000); // Yes, doing this like this is bad. No better idea yet.
                    processResponse = processClient.Get<ProcessResponse>(new RestRequest());
                    tryCount++;
                }
                if (tryCount == 20) throw new OrchardException(T("PDF generation failed as CloudConvert didn't finish the conversion after 40s."));

                using (var wc = new WebClient())
                {
                    var fileBytes = wc.DownloadData("https:" + processResponse.Data.Output.Url);
                    return new MemoryStream(fileBytes);
                }
            }
        }
Esempio n. 3
0
        public IRestResponse <T> SendPostRequest <T>(string resource, object data)
        {
            var req = new RestRequest(resource, Method.POST)
            {
                RequestFormat = DataFormat.Json
            }
            .AddJsonBody(data)
            .AddHeader("Content-Type", "application/json");

            var response = _client.Post <T>(req);

            return(response);
        }
Esempio n. 4
0
        public CreateZakazResponse CreateZkz(Dictionary <string, Pay> pays, string sts, string vu, string Surname, string Name)
        {
            var client = new RestSharp.RestClient(serviceUri);


            var zkzReq = new RestSharp.RestRequest();

            zkzReq.AddParameter("top", "2");
            zkzReq.AddParameter("id", id);
            zkzReq.AddParameter("hash", hash2);
            zkzReq.AddParameter("type", "10");
            zkzReq.AddParameter("sts", sts);
            zkzReq.AddParameter("vu", vu);

            //начисления
            var paysJson = JsonConvert.SerializeObject(pays);

            zkzReq.AddParameter("l", paysJson);

            zkzReq.AddParameter("name1", Surname);
            zkzReq.AddParameter("name2", Name);
            zkzReq.AddParameter("email", "*****@*****.**");

            zkzReq.AddParameter("flmon", "1");
            zkzReq.AddParameter("flnonotice", "1");


            var zkzResp = client.Post(zkzReq);
            var zkzCont = zkzResp.Content;
            var zkz     = JsonConvert.DeserializeObject <CreateZakazResponse>(zkzCont);

            return(zkz);
        }
Esempio n. 5
0
        public IActionResult RestsharpTest()
        {
            RestSharp.RestClient restClient = new RestSharp.RestClient();
            restClient.Post(new Func <RestRequest>(() =>
            {
                var req           = new RestRequest();
                req.Resource      = "https://localhost:5001/lab/UploadTest";
                req.Method        = Method.POST;
                req.RequestFormat = DataFormat.Json;

                /*
                 * req.AddHeader("content-type", "application/x-www-form-urlencoded");
                 * req.AddParameter("application/x-www-form-urlencoded", $"input[0][col1]=row1&input[0][col2]=1", ParameterType.RequestBody);
                 */

                /*
                 * req.AddJsonBody(new object[]
                 * {
                 *  new { col1 = "row3", col2 = 3 },
                 *  new { col1 = "row4", col2 = 4 },
                 * });
                 */

                req.AlwaysMultipartFormData = true;
                req.AddFile("file1", "d:/18.jpg");
                return(req);
            }).Invoke());

            //restClient.DownloadData(new RestRequest("", Method.POST, DataFormat.Json));

            return(Json(new { msg = "OK", fileName = "test" }));
        }
Esempio n. 6
0
        public void Flush(Workspace workspace)
        {
            ConsoleEx.Info($"Running sink: {this.GetType().Name}");

            var request = new RestRequest(@"api/workspaces", Method.POST);
            request.AddJsonBody(workspace);
            request.RequestFormat = DataFormat.Json;

            var restClient = new RestClient(serviceUri);
            var response = restClient.Post(request);
            if(response.StatusCode == HttpStatusCode.OK)
            {
                ConsoleEx.Ok("Workspace analysis report published.");
                var locationHeader = response.Headers.FirstOrDefault(h=> h.Name == "Location");
                if (locationHeader != null)
                {
                    string workspaceLocation = locationHeader.Value.ToString().ToLower();
                    ConsoleEx.Ok($"Visit {workspaceLocation}");
                }
            }
            else
            {
                ConsoleEx.Error($"Workspace not published to target sink.");
                ConsoleEx.Error($"Status: {response.StatusCode}, Response: {response.Content}");
            }
        }
        public void Send(OutgoingMessage outgoingMessage)
        {
            var client = new RestClient(TwilioBaseUrl);
            client.Authenticator = new HttpBasicAuthenticator(AccountSid, AuthToken);
            const string sendResource = "/SMS/Messages.json";
            var request = new RestRequest(sendResource, Method.POST);
            request.AddParameter("From", From);
            request.AddParameter("To", outgoingMessage.To);
            request.AddParameter("Body", outgoingMessage.Body);
            var response = client.Post<TwilioResponse>(request);
            if (response.ErrorException != null)
            {
                throw response.ErrorException;
            }            
            if(response.Data.Status!="queued")
            {
                throw new Exception(response.Data.Message);
            }

            _repository.Create(new LoggedOutgoingMessage
                                   {
                                       Body = outgoingMessage.Body,
                                       Sent = SystemDateTime.Now(),
                                       ToNumber = outgoingMessage.To
                                   });
        }
Esempio n. 8
0
        public RedirectResult SignIn(string login, string password, string appId, 
            string redirectUri, string state)
        {
            var client = new RestClient("http://localhost:9999/api/");
            var signInRequest = new RestRequest("Auth/SignIn");

            signInRequest.AddQueryParameter("login",login);
            signInRequest.AddQueryParameter("password",password);
            signInRequest.AddQueryParameter("appId",appId);
            signInRequest.AddQueryParameter("redirectUri", redirectUri);
            signInRequest.AddQueryParameter("state","666");

            var response = client.Post(signInRequest);
            var url = response.ResponseUri.ToString();

            var urlArr = url.Split('?', '=', '&');
            var user = Auth(login, password);
            if (user == null)
                throw new ArgumentException("Неверная пара логин/пароль");

            var app = _appDataReposytory.AppDatas.FirstOrDefault(e => e.Id.ToString() == appId);
            if (app == null)
                throw new Exception("Нет приложения с таким appId");


            _codes.Add(urlArr[2], user.Id);

            //_sessionHelper.CreateNewSession(user, app);

            return new RedirectResult(url);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            var appName = string.Empty;
            var hostName = string.Empty;
            var help = false;

            var p = new OptionSet
                {
                    {"app=", v => appName = v},
                    {"host=", v => hostName = v},
                    {"h|?|help", v => help = v != null},
                };
            p.Parse(args);

            if (help || string.IsNullOrWhiteSpace(appName) || string.IsNullOrWhiteSpace(hostName))
            {
                p.WriteOptionDescriptions(Console.Out);
                return;
            }

            var restClient = new RestClient("http://" + hostName + ":9000");
            var request = new RestRequest("/api/v1/install-queue/" + appName, Method.POST) {RequestFormat = DataFormat.Json};
            request.AddBody(new { @null = string.Empty });
            var response = restClient.Post(request);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                Console.WriteLine("'{0}' deployment started remotely on '{1}'.", appName, hostName);
            }
        }
Esempio n. 10
0
        public string Subscribe(string topic)
        {
            RestRequest request = new RestRequest("/topics/{topic_name}/subscriptions", Method.POST);

            request.AddUrlSegment("topic_name", topic);

            IRestResponse <Subscription> response = _client.Post <Subscription>(request);

            if (IsPostSuccessful(response))
            {
                return(response.Data.subscription_id);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 11
0
 public IRestResponse Run(Step step, ScenarioContext context)
 {
     var apiPostStep = (ApiPostStep) step;
     var client = new RestClient(apiPostStep.Host);
     var restRequest = BuildRequest(apiPostStep);
     restRequest.AddBody(apiPostStep.Payload);
     return client.Post(restRequest);
 }
Esempio n. 12
0
 public string Shorten(string urlToShorten)
 {
     IRestClient client = new RestClient(SHORTENER_API);
     IRestRequest request = new RestRequest(SHORTEN_ENDPOINT);
     request.RequestFormat = DataFormat.Json;
     request.AddBody(new { longUrl = urlToShorten });
     IRestResponse response = client.Post(request);
     dynamic json = response.Content;
     return json.id ?? urlToShorten;
 }
Esempio n. 13
0
        public IRestResponse Post(IRestRequest request)
        {
            RestSharp.RestClient client   = new RestSharp.RestClient();
            IRestResponse        response = client.Post(request);

            if (!response.IsSuccessful)
            {
                throw new RequestException(response.ErrorMessage + " Uri: " + response.ResponseUri, response);
            }

            return(response);
        }
Esempio n. 14
0
 public static String post(String title, String content)
 {
     RestClient rc = new RestClient("http://app.askform.cn");
     RestRequest request = new RestRequest("{guide}.aspx?Type={type}");
     request.AddUrlSegment("guide", instance.FromGuide);
     request.AddUrlSegment("type", instance.FormType.ToString());
     request.AddParameter("Survey.F77960001-2", title);
     request.AddParameter("Survey.F77960001-3", content);
     request.AddParameter("Survey_duration", "0");
     IRestResponse respone= rc.Post(request);
     return respone.StatusCode.ToString();
 }
Esempio n. 15
0
        public CheckPayResponse CheckPay(string sts, string vu)
        {
            var client = new RestSharp.RestClient(serviceUri);


            var req = new RestSharp.RestRequest();

            req.AddParameter("top", "1");
            req.AddParameter("id", id);
            req.AddParameter("hash", hash1);
            req.AddParameter("type", "10");
            req.AddParameter("sts", sts);
            if (!string.IsNullOrEmpty(vu))
            {
                req.AddParameter("vu", vu);
            }

            // req.Parameters.Add(new Parameter(){Name = });

            var resp = client.Post(req);
            var cont = resp.Content;
            //  JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore };
            dynamic obj = JsonConvert.DeserializeObject(cont);

            //воркераунд потому что payload дегенератский
            //массива с платежами нет, сериализуем во враппер
            if (obj.l is JArray)
            {
                var paysWrapper = JsonConvert.DeserializeObject <GenericCheckPayResponse>(cont);
                return(new CheckPayResponse()
                {
                    Err = paysWrapper.Err, Hash = paysWrapper.Hash, L = null, Msg = paysWrapper.Msg, Top = paysWrapper.Top
                });
            }

            /*   if (!string.IsNullOrEmpty(obj.msg.Value))
             * {
             *     throw new Exception(obj.msg.Value);
             * }
             *
             * /* var paysWrapper = JsonConvert.DeserializeObject<GenericCheckPayResponse>(cont);
             * if (paysWrapper == null)
             * {#1#*/
            else
            {
                var pays = JsonConvert.DeserializeObject <CheckPayResponse>(cont);
                return(pays);
            }

            /*}
             * return null;*/
        }
Esempio n. 16
0
        /// <summary>
        /// Requests a Github API token, given you received a code first, i.e. user allowed that.
        /// 
        /// See OAuth documentation for how to do that.
        /// Your App needs to be registered first.
        /// </summary>
        /// <param name="client_id">your app's client_id</param>
        /// <param name="client_secret">your app's secret</param>
        /// <param name="code">code you got from github</param>
        /// <returns>oauth token if successful, null otherwise</returns>
        public static string requestToken(string client_id, string client_secret, string code)
        {
            // Not on api.github.com
            var client = new RestClient("https://github.com");
            client.UserAgent = "mabako/Git.hub";

            var request = new RestRequest("/login/oauth/access_token");
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("client_id", client_id);
            request.AddParameter("client_secret", client_secret);
            request.AddParameter("code", code);

            var response = client.Post<OAuth2Data>(request);
            if (response.Data != null)
                return response.Data.AccessToken;
            return null;
        }
        private void PhoneHome()
        {
            while (true)
            {
                var restClient = new RestClient("http://localhost:9001") {Timeout = 1000};
                var request = new RestRequest("/api/v1/clients/register", Method.POST) {RequestFormat = DataFormat.Json};
                request.AddBody(new { @null = string.Empty });
                restClient.Post(request);

                if (_cancellation.IsCancellationRequested)
                {
                    break;
                }

                Thread.Sleep(new TimeSpan(0,0,0, 30));
            }
        }
            public void send(string recipient, string text)
            {
                if (string.IsNullOrEmpty(text) || text.Length > 603)
                {
                    _log.Error("Unable to send sms because text is null or longer than 603 characters.");
                    return;
                }

                if (string.IsNullOrEmpty(recipient) || !_numberValidator.IsMatch(recipient))
                {
                    _log.Error("Unable to send sms because recipient isn't a valid phone number.");
                    return;
                }

                if (string.IsNullOrEmpty(_username) || string.IsNullOrEmpty(_password))
                {
                    _log.Error("Unable to send sms because 'sms.username' or 'sms.password' is not specified.");
                    return;
                }

                var client = new RestClient("https://json.aspsms.com");
                var request = new RestRequest("SendSimpleTextSMS");
                request.AddJsonBody(new
                {
                    UserName = _username,
                    Password = _password,
                    Originator = "Xpressive.H",
                    Recipients = new [] { recipient },
                    MessageText = text
                });

                var response = client.Post(request);

                if (response.StatusCode != HttpStatusCode.OK && response.ErrorMessage != null)
                {
                    if (response.ErrorException != null)
                    {
                        _log.Error("Error when sending SMS: " + response.ErrorMessage, response.ErrorException);
                    }
                    else
                    {
                        _log.Error("Error when sending SMS: " + response.ErrorMessage);
                    }
                }
            }
Esempio n. 19
0
        public RedirectToRouteResult AddMan(Manufacturer man)
        {
            var token = _sessionHelper.GetToken();

            if (token == "SessionIsNull")
                return RedirectToAction("GoToErrorForm", "Cpu");

            var clientMan = new RestClient(SiteConn.ManWebApiServer);
            var addMan = new RestRequest($"Man/AddMan", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            addMan.AddHeader("Authorization", token);
            addMan.AddHeader("Content-Type", "application/json");

            addMan.AddObject(man);

            var responseMan = clientMan.Post(addMan);

            return RedirectToAction("List", "Man");
        }
Esempio n. 20
0
        //private readonly string serviceUri = "http://*****:*****@"api/accounts", Method.POST);
            request.AddJsonBody(new
            {
                email = emailAddress
            });
            request.RequestFormat = DataFormat.Json;

            var response = serviceClient.Post<Registration>(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return response.Data;
            }
            else
            {
                ConsoleEx.Error($"Registration failed.");
                ConsoleEx.Error($"Status: {response.StatusCode}, Response: {response.Content}");
                return null;
            }
        }
 public static string HttpPost(this Uri uri, IDictionary<string, string> parameters)
 {
     RestClient client = new RestClient(uri.GetBaseUrl());
     RestRequest request = new RestRequest();
     if (parameters != null)
     {
         foreach (KeyValuePair<string, string> pair in parameters)
         {
             request.AddParameter(pair.Key, pair.Value);
         }
     }
     IRestResponse response = client.Post(request);
     response.CheckResponse();
     return response.Content;
 }
Esempio n. 22
0
        private string RequestToken()
        {
            var client = new RestClient("https://api.flowdock.com/");
            var tokenRequest = new RestRequest("oauth/token");

            tokenRequest.AddQueryParameter("client_id", OauthCodes.ApplicationId);
            tokenRequest.AddQueryParameter("client_secret", OauthCodes.SecretId);
            tokenRequest.AddQueryParameter("code", ReturnedCode);
            tokenRequest.AddQueryParameter("redirect_uri", "http://ya.ru");
            tokenRequest.AddQueryParameter("grant_type", "authorization_code");

            var response = client.Post<AuthResponse>(tokenRequest);
            return response.Data.AccessToken;
        }
        protected override void Execute(NativeActivityContext context)
        {
            RestSharp.RestClient client     = new RestSharp.RestClient();
            MCser.SoapClient     soapClient = null;

            String ExistAuthToken  = "" + ExistingAuth.Get(context);
            String ExistServiceURL = "" + ExistingServ.Get(context);

            if (ExistAuthToken.Trim().Length > 1)
            {
                RespAuthToken  = ExistAuthToken.Trim();
                RespServiceURL = ExistServiceURL.Trim();
            }
            else
            {
                String  sfdcConsumerkey    = "";
                String  sfdcConsumerSecret = "";
                String  sfdcServiceURL     = "";
                String  sfdcUserName       = "";
                String  sfdcPassword       = "";
                Boolean EnvType            = (EnvironmentType == Type_of_Environment.Design_and_Test) ? true : false;
                if (EnvType)
                {
                    sfdcConsumerkey    = ConsumerKey.Get(context);
                    sfdcConsumerSecret = ConsumerSecret.Get(context);
                    sfdcServiceURL     = ServiceURL.Get(context);
                    sfdcUserName       = UserName.Get(context);
                    sfdcPassword       = Password.Get(context);
                }
                else
                {
                    sfdcConsumerkey    = ConsumerKeyProd.Get(context);
                    sfdcConsumerSecret = SecureStringToString(ConsumerSecretProd.Get(context));
                    sfdcServiceURL     = "" + SecureStringToString(ServiceURLProd.Get(context));
                    sfdcUserName       = UserNameProd.Get(context);
                    sfdcPassword       = SecureStringToString(PasswordProd.Get(context));
                }

                try
                {
                    client.BaseUrl = new Uri("https://auth.exacttargetapis.com/v1/requestToken");

                    var request2 = new RestRequest(Method.POST);
                    request2.RequestFormat = DataFormat.Json;
                    request2.AddParameter("clientId", sfdcConsumerkey);
                    request2.AddParameter("clientSecret", sfdcConsumerSecret);

                    JObject jsonObj = JObject.Parse(client.Post(request2).Content);
                    RespAuthToken = (String)jsonObj["accessToken"];
                    String ErrorType = "";
                    ErrorType = (String)jsonObj["error"];
                    String ErrorMsg = "";
                    ErrorMsg = (String)jsonObj["error_description"];


                    if ((RespAuthToken != null && RespAuthToken != "") && ErrorMsg == null)
                    {
                        BasicHttpsBinding binding = new BasicHttpsBinding();
                        binding.Name                   = "MyServicesSoap";
                        binding.CloseTimeout           = TimeSpan.FromMinutes(1);
                        binding.OpenTimeout            = TimeSpan.FromMinutes(1);
                        binding.ReceiveTimeout         = TimeSpan.FromMinutes(60);
                        binding.SendTimeout            = TimeSpan.FromMinutes(1);
                        binding.AllowCookies           = false;
                        binding.BypassProxyOnLocal     = false;
                        binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                        binding.MaxBufferSize          = 20000000;
                        binding.MaxBufferPoolSize      = 20000000;
                        binding.MaxReceivedMessageSize = 20000000;
                        binding.MessageEncoding        = WSMessageEncoding.Text;
                        binding.TextEncoding           = System.Text.Encoding.UTF8;
                        binding.TransferMode           = TransferMode.Buffered;
                        binding.UseDefaultWebProxy     = true;

                        binding.ReaderQuotas.MaxDepth = 32;
                        binding.ReaderQuotas.MaxStringContentLength = 8192;
                        binding.ReaderQuotas.MaxArrayLength         = 16384;
                        binding.ReaderQuotas.MaxBytesPerRead        = 4096;
                        binding.ReaderQuotas.MaxNameTableCharCount  = 16384;

                        binding.Security.Mode = BasicHttpsSecurityMode.Transport;
                        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                        binding.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;
                        binding.Security.Transport.Realm = "";
                        binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                        binding.Security.Message.AlgorithmSuite       = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;


                        String          endpointStr = "https://webservice.s10.exacttarget.com/Service.asmx";
                        EndpointAddress endpoint    = new EndpointAddress(endpointStr);
                        soapClient = new MCser.SoapClient(binding, endpoint);
                        soapClient.ClientCredentials.UserName.UserName = sfdcUserName;
                        soapClient.ClientCredentials.UserName.Password = sfdcPassword;
                        soapClient.Endpoint.EndpointBehaviors.Add(new FuelOAuthHeaderBehavior(RespAuthToken));
                        RespServiceURL = sfdcServiceURL;
                    }
                    else if (RespAuthToken == null && (ErrorMsg != "" && ErrorMsg != null))
                    {
                        RespAuthToken  = "Error Type: " + ErrorType;
                        RespServiceURL = "Error: " + ErrorMsg;
                    }
                }
                catch (Exception ex)
                {
                    RespAuthToken  = "Error Type: " + ex.ToString();
                    RespServiceURL = "Error: " + ex.ToString();
                }
            }

            var salesForceProperty = new SalesForceProperty(soapClient, true, RespAuthToken, RespServiceURL);

            if (Body != null)
            {
                context.ScheduleAction <SalesForceProperty>(Body, salesForceProperty, OnCompleted, OnFaulted);
            }
        }
        /// <summary>
        /// 取得PChome股市個股成交明細頁面。
        /// </summary>
        /// <param name="stockID"></param>
        /// <returns></returns>
        private IRestResponse GetRestResponse(int stockID)
        {
            //"http://stock.pchome.com.tw/stock/sto0/ock3/sid3481.html"
            var url = string.Format("http://stock.pchome.com.tw/stock/sto0/ock3/sid{0}.html", stockID);

            var clinet = new RestClient(url)
            {
                CookieContainer = new CookieContainer()
            };

            var req = new RestRequest().AddParameter("is_check", "1");

            clinet.Get(req);
            return clinet.Post(req);
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            int    age      = 120;
            string ageBlock = "";

            switch (age)
            {
            case 50:
                ageBlock = "the big five-oh";
                break;

            case var testAge when(new List <int>()
                                  { 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }).Contains(testAge):
                ageBlock = "octogenarian";

                break;

            case var testAge when((testAge >= 90)& (testAge <= 99)):
                ageBlock = "nonagenarian";

                break;

            case var testAge when(testAge >= 100):
                ageBlock = "centenarian";

                break;

            case var testAge when(testAge >= 110):
                ageBlock = "centenarian +";

                break;

            default:
                ageBlock = "just old";
                break;
            }


            return;

            var dbContext  = new  AutoBotContext();
            var dbContext2 = new AutoBotContext();


            var srv = new ShtrafiUserService(dbContext);
            var res = srv.RegisterDocumentSetToCheck(dbContext2.Users.FirstOrDefault(), "1621390815", "test doc set name",
                                                     "1630048283");

            return;


            var userTelegrammId = "TestUser";

            var clientId = "R413393879901";
            var key      = "dfS3s4Gfadgf9";
            var operType = 1;
            var hash     = "7f710ee37c3ff2e3587e1e1acff60ed5";



            Console.WriteLine("starting to connect...");
            var client = new RestSharp.RestClient(" https://www.elpas.ru/api.php");

            Console.WriteLine("Приветствуем вас в сервисе оплаты штрафов. У нас можно платить штрафы гибдд с низкой комиссией (10%, мин 30р). Оплата производится на надёжном сайте-партнере (moneta.ru), вы не вводите данные карт в чат.");
            Console.WriteLine("Пожалуйста введите номер свидетельства о регистрации ТС");
            var sts = Console.ReadLine();

            sts = "1621390860";

            //todo: add validation
            Console.WriteLine("Вы можете также ввести номер водительского удостоверения, это повысит вероятность поиска штрафов. Либо просто отправьте 0");
            var vu = Console.ReadLine();

            if (vu == "0")
            {
                vu = null;
            }

            var req = new RestSharp.RestRequest();

            req.AddParameter("top", "1");
            req.AddParameter("id", "R413393879901");
            req.AddParameter("hash", "7f710ee37c3ff2e3587e1e1acff60ed5");
            req.AddParameter("type", "10");
            req.AddParameter("sts", sts);
            if (vu != null)
            {
                req.AddParameter("vu", vu);
            }

            // req.Parameters.Add(new Parameter(){Name = });

            var resp = client.Post(req);
            var cont = resp.Content;

            var pays = JsonConvert.DeserializeObject <CheckPayResponse>(cont);

            //todo: add check on -1 error and 500 and repeat call if needed

            if (pays?.Err == -4)
            {
                Console.WriteLine("Штрафы не найдены. Обратите внимание что это не гарантирует на 100% их отсутсвие. Рекомендуем повторить проверку через какое-то время");
                Console.ReadLine();
            }

            var payCount = pays?.L.Count;

            if (payCount != 0)
            {
                if (payCount == 1)
                {
                    Console.WriteLine("У вас найден штраф:");
                }
                else
                {
                    Console.WriteLine($"У вас найдено {payCount} штрафов:");
                }
                int i = 1;
                foreach (var pay in pays.L)
                {
                    Console.WriteLine(i + ": " + pay.Value);
                    i++;
                }
            }

            Console.WriteLine("Перечислите номера штрафов или введите \"все\" чтобы оплатить все штрафы.");
            if (Console.ReadLine().Contains("все"))
            {
                var zkzReq = new RestSharp.RestRequest();
                zkzReq.AddParameter("top", "2");
                zkzReq.AddParameter("id", "R413393879901");
                zkzReq.AddParameter("hash", "7116af7911c223750ce58d22948f7fd8");
                zkzReq.AddParameter("type", "10");
                zkzReq.AddParameter("sts", sts);
                zkzReq.AddParameter("vu", vu);

                //начисления
                var paysJson = JsonConvert.SerializeObject(pays.L);
                zkzReq.AddParameter("l", paysJson);

                zkzReq.AddParameter("name1", "Степанов");
                zkzReq.AddParameter("name2", "Андрей");
                zkzReq.AddParameter("email", "*****@*****.**");

                zkzReq.AddParameter("flmon", "1");
                zkzReq.AddParameter("flnonotice", "1");


                var zkzResp = client.Post(zkzReq);
                var zkzCont = zkzResp.Content;
                var zkz     = JsonConvert.DeserializeObject <CreateZakazResponse>(zkzCont);

                if (zkzResp != null)
                {
                    Console.WriteLine($"Для оплаты перейдите по ссылке: {zkz.Urlpay}");
                }

                //register and check
                var  bll            = new ShtrafiBLL.ShtrafiUserService(new AutoBotContext());
                var  usr            = bll.GetUserByMessengerId(userTelegrammId);
                User registeredUser = new User();
                if (usr == null)
                {
                    registeredUser = bll.RegisterUserAfterFirstPay(userTelegrammId, "имя", "фамилия", sts, "");
                }
                Console.WriteLine($"User registered, id is {registeredUser.Id}");

                Console.WriteLine("нажмите любую кнопку чтоб отменить подписку");

                bll.ToggleDocumentSetForSubscription(registeredUser.DocumentSetsTocheck.FirstOrDefault(), false);

                Console.ReadLine();

                /* var cont = resp.Content;
                 *
                 * var pays = JsonConvert.DeserializeObject<CheckPayResponse>(cont);*/
            }

            Console.ReadLine();
        }
Esempio n. 26
0
        public void SignOut(string token, string appId, string appSecretKey, string grantType)
        {
            if (string.IsNullOrEmpty(token))
                throw new ArgumentNullException("token");

            if (string.IsNullOrEmpty(appId))
                throw new ArgumentNullException("appId");

            if (string.IsNullOrEmpty(appSecretKey))
                throw new ArgumentNullException("appSecretKey");

            if (string.IsNullOrEmpty(grantType))
                throw new ArgumentNullException("grantType");

            if (grantType != "token")
                throw new ArgumentException("Неправильное значение grantType");

            var client = new RestClient("http://localhost:9999/api/");
            var signOutRequest = new RestRequest("Auth/SignOut");

            signOutRequest.AddQueryParameter("token", token);
            signOutRequest.AddQueryParameter("appId", appId);
            signOutRequest.AddQueryParameter("appSecretKey", appSecretKey);
            signOutRequest.AddQueryParameter("grantType", grantType);

            var response = client.Post(signOutRequest);

        }
        public Token RefreshToken(string refreshToken, string appId, string appSecretKey,
            string responseType, string grantType)
        {
            //var user = _userReposytory.UserInfoes.FirstOrDefault(e => e.Id == authCode.Value);

            var client = new RestClient(SiteConn.AuthWebApiServer);
            var signInRequest = new RestRequest("Auth/RefreshToken");

            signInRequest.AddQueryParameter("refreshToken", refreshToken);
            signInRequest.AddQueryParameter("appId", appId);
            signInRequest.AddQueryParameter("appSecretKey", appSecretKey);
            signInRequest.AddQueryParameter("responseType", responseType);
            signInRequest.AddQueryParameter("grantType", grantType);

            var response = client.Post<Token>(signInRequest);

            //_sessionHelper.SaveToken(response.Data, user, app);
            //_codes.Remove(authCode.Key);

            return response.Data;
        }
Esempio n. 28
0
        public JsonResult GetToken(string code, string appId, string appSecretKey,
            string responseType, string grantType)
        {   

            if (string.IsNullOrEmpty(code))
                throw new ArgumentNullException("code");

            if (string.IsNullOrEmpty(appId))
                throw new ArgumentNullException("appId");

            if (string.IsNullOrEmpty(appSecretKey))
                throw new ArgumentNullException("appSecretKey");

            if (string.IsNullOrEmpty(responseType))
                throw new ArgumentNullException("responseType");

            if (responseType != "token")
                throw new ArgumentException("Неправильное значение responseType");

            if (string.IsNullOrEmpty(grantType))
                throw new ArgumentNullException("grantType");

            if (grantType != "code")
                throw new ArgumentException("Неправильное значение grantType");

            var app = _appDataReposytory.AppDatas.FirstOrDefault(e => e.Id.ToString() == appId);
            if (app == null)
                 throw new Exception("Нет приложения с таким appId");

            if (app.AppSecretId != appSecretKey)
                 throw new ArgumentException("Неверное значение appSecretKey");

            var authCode = _codes.FirstOrDefault(e => e.Key == code);
            if (authCode.Key == null)
                throw new ArgumentException("Неверное значение code");

            var user = _userReposytory.UserInfoes.FirstOrDefault(e => e.Id == authCode.Value);

            var client = new RestClient("http://localhost:9999/api/");
            var signInRequest = new RestRequest("Auth/GetToken");

            signInRequest.AddQueryParameter("code", code);
            signInRequest.AddQueryParameter("appId", appId);
            signInRequest.AddQueryParameter("appSecretKey", appSecretKey);
            signInRequest.AddQueryParameter("responseType", responseType);
            signInRequest.AddQueryParameter("grantType", grantType);

            var response = client.Post<Token>(signInRequest);
            
            //_sessionHelper.SaveToken(response.Data, user, app);
            _codes.Remove(authCode.Key);

            return Json(new
            {
                token = response.Data.AccessToken,
                tokenType = "bearer",
                RefreshToken = response.Data.RefreshToken,
                ExpiresIn = response.Data.ExpiresIn.ToString(CultureInfo.CurrentCulture)
            });
        }
        public void SignOut(string appId, string appSecretKey, string grantType)
        {
            var token = _sessionHelper.GetToken();
            

            var client = new RestClient(SiteConn.AuthWebApiServer);
            var signOutRequest = new RestRequest("Auth/SignOut");

            signOutRequest.AddQueryParameter("token", token);
            signOutRequest.AddQueryParameter("appId", appId);
            signOutRequest.AddQueryParameter("appSecretKey", appSecretKey);
            signOutRequest.AddQueryParameter("grantType", grantType);

            var response = client.Post(signOutRequest);

            _sessionHelper.DeleteSession();

        }
        public void Send(string jiraRestApiUrl, string jiraUsername, string jiraPassword)
        {
            jiraRestApiUrl = jiraRestApiUrl.TrimEnd("/".ToCharArray()) + "/rest/api/2/";
            var restClient = new RestClient(jiraRestApiUrl)
                                 {
                                     Authenticator =
                                         new HttpBasicAuthenticator(jiraUsername,
                                                                    jiraPassword)
                                 };

            var request = new RestRequest("issue", Method.POST);
            //request.AddBody(this);
            //request.RequestFormat = DataFormat.Json;

            //request.AddHeader("Content-Type", "application/json");

            string json = request.JsonSerializer.Serialize(this);

            request.Method = Method.POST;
            request.AddHeader("Accept", "application/json");
            request.Parameters.Clear();
            request.AddParameter("application/json", json, ParameterType.RequestBody);

            restClient.Post(request);
        }
Esempio n. 31
-1
        private static AdmAccessToken GetAccessToken(string clientId, string clientSecret)
        {
            const string accessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            var restClient = new RestClient(accessUri);
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "x-www-form-urlencoded");
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", clientId);
            request.AddParameter("client_secret", clientSecret);
            request.AddParameter("scope", "http://api.microsofttranslator.com");

            var token = restClient.Post<AdmAccessToken>(request);

            return token.Data;
        }
        public RedirectResult SignIn(string login, string password, string appId, 
            string redirectUri, string state)
        {
            var client = new RestClient(SiteConn.AuthWebApiServer);
           

            var signInRequest = new RestRequest("Auth/SignIn");

            signInRequest.AddQueryParameter("login",login);
            signInRequest.AddQueryParameter("password",password);
            signInRequest.AddQueryParameter("appId",appId);
            signInRequest.AddQueryParameter("redirectUri", redirectUri);
            signInRequest.AddQueryParameter("state","666");

            var response = client.Post(signInRequest);
            if (response == null) return new RedirectResult(redirectUri);

            //получаю куки с токеном
            if (response.Cookies != null)
            {
                return new RedirectResult(redirectUri);
            }
            
            return null;
        }