Example #1
4
        public async Task<bool> IsValidKey(string key)
        {
            try
            {
                var client = new RestClient("http://" + _serverAdress);
                var request = new RestRequest("getProductKeyValid.php", Method.GET);
                request.AddParameter("productkeys_Key", key);

                request.Timeout = 5000;
                IRestResponse response = await client.ExecuteGetTaskAsync(request);
                //only throws the exception. Let target choose what to do
                if (response.ErrorException != null)
                {
                    throw response.ErrorException;
                }
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(response.Content);
                //if string equals "1" the key is not activated yet
                if (model.Equals("1"))
                    return true;
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }
 private static string FetchFeed(string domain, string resource)
 {
     var client = new RestClient(domain);
     var request = new RestRequest(resource);
     IRestResponse response = client.Execute(request);
     return response.Content;
 }
 private static void InitRestClient()
 {
     if (client==null)
     {
         client = new RestClient(SERVER_REST_URL);
     }
 }
        static private async Task<Images> download(string domain, string path, string pattern)
        {
            var result = new Images();
            var client = new RestClient(domain);
            var restTasks = new List<Task<IRestResponse>>();
            var response = client.Get(new RestRequest(path, Method.GET));

            foreach (Match match in Regex.Matches(response.Content, pattern))
            {
                string fileName = match.Captures[0].Value.Replace(">", "");
                result.Add(fileName, 0);
                if (!File.Exists(baseDir(path) + "\\" + fileName))
                {
                    var img = new RestRequest(path + fileName, Method.GET);
                    img.AddParameter("fileName", fileName);
                    restTasks.Add(client.ExecuteTaskAsync(img));
                }
            }

            foreach (var restTask in restTasks)
            {
                response = await restTask;
                string fileName = response.Request.Parameters[0].Value.ToString();
                result[fileName] = (int)response.StatusCode;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var fs = File.Create(baseDir(path) + "\\" + fileName);
                    await fs.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
                    fs.Close();
                }
            }
            return result;
        }
        public string ActivateFeature(string baseSiteUrl, string user, string password, string domain)
        {
            if (baseSiteUrl.EndsWith("/"))
                baseSiteUrl += "_api/";
            else
                baseSiteUrl += "/_api/";

            RestClient rc = new RestClient(baseSiteUrl);
            NetworkCredential nCredential = new NetworkCredential(user, password, domain);
            rc.Authenticator = new NtlmAuthenticator(nCredential);

            RestRequest request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
            request.AddHeader("Accept", "application/json;odata=verbose");
            request.AddHeader("Body", "");

            string returnedStr = rc.Execute(request).Content;
            int startPos = returnedStr.IndexOf("FormDigestValue", StringComparison.Ordinal) + 18;
            int length = returnedStr.IndexOf(@""",", startPos, StringComparison.Ordinal) - startPos;
            string formDigestValue = returnedStr.Substring(startPos, length);

            request = new RestRequest("web/features/add('de646322-53f3-474d-96bf-0ea3670a0722',false)", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Accept", "application/json;odata=verbose");
            //request.AddHeader("Body", "");
            request.AddHeader("Content-Type", "application/json;odata=verbose");
            request.AddHeader("X-RequestDigest", formDigestValue);
            IRestResponse response = rc.Execute(request);
            string content = response.Content;

            return content;
        }
Example #6
1
        public void CreateInstance(string code)
        {
            var client = new RestClient("https://console.cloud-elements.com/elements/api-v2");
            var dropbox = "/elements/dropbox/instances";

            var json = @"{
             ""element"": {
               ""key"": ""dropbox""
             },
             ""providerData"": {
               ""code"": """ + code +  @"""
             },
             ""configuration"": {
               ""oauth.callback.url"": ""http://*****:*****@"""
            }";
            var createInstance = new RestRequest(dropbox, Method.POST) { RequestFormat = DataFormat.Json };
            createInstance.AddHeader("Authorization", "User kiJp+N8I12IAynsqCqq4I7M/XuwS6aUSJR4hLPLYCI8=, Organization 1eaea1a56a443c25f529ca678c4cd66b");

            //createInstance.AddParameter("elementInstance",json,  "application/json",  ParameterType.RequestBody);
            createInstance.AddParameter("application/json", json, ParameterType.RequestBody);
            //            createInstance.AddBody(json);

            var restResponse = client.Execute(createInstance);
            var restfulResponse = new RestfulResponse(restResponse, dropbox);
        }
Example #7
0
 private NextClient(ApiInfo apiInfo)
 {
     _apiInfo = apiInfo;
     _client = new RestClient(_apiInfo.BaseUrl);
     PrivateFeed = new PrivateFeed(this, c => c.Session.PrivateFeed);
     PublicFeed = new PublicFeed(this, c => c.Session.PublicFeed);
 }
        public void BreakItemRoleInheritance(string listTitle, string baseSiteUrl, string user, string password, string domain)
        {
            try
            {
                RestClient RC = new RestClient(baseSiteUrl);
                NetworkCredential NCredential = new NetworkCredential(user, password, domain);
                RC.Authenticator = new NtlmAuthenticator(NCredential);

                RestRequest Request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
                Request.AddHeader("Accept", "application/json;odata=verbose");
                Request.AddHeader("Body", "");

                string ReturnedStr = RC.Execute(Request).Content;
                int StartPos = ReturnedStr.IndexOf("FormDigestValue") + 18;
                int length = ReturnedStr.IndexOf(@""",", StartPos) - StartPos;
                string FormDigestValue = ReturnedStr.Substring(StartPos, length);

                Request = new RestRequest("web/lists/GetByTitle('" + listTitle + "')/getItemById(12)/breakroleinheritance", Method.POST);
              //  Request = new RestRequest("web/lists/GetByTitle('" + listTitle + "')/breakroleinheritance(true)", Method.POST);
                Request.RequestFormat = DataFormat.Json;
                Request.AddHeader("Accept", "application/json;odata=verbose");
                Request.AddHeader("X-RequestDigest", FormDigestValue);
                string content = RC.Execute(Request).Content;

                //return "Permission breaked successfully";
            }
            catch (Exception)
            {

                throw;
            }
        }
Example #9
0
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            RestClient client = new RestClient("http://pokeapi.co/api/v1");

            string pokemonName = PokemonNameBox.Text;

            RestRequest request = new RestRequest("pokemon/{name}", Method.GET);
            request.AddUrlSegment("name", pokemonName);
            var response = client.Execute(request);

            if (response.Content == "")
            {
                ResultBox.AppendText(String.Format("Pokemon {0} not found{1}",pokemonName,Environment.NewLine));
            }

            dynamic pokemon = JsonConvert.DeserializeObject(response.Content);

            bool hasEvolution = (pokemon.evolutions.Count > 0) ? true : false;

            if (hasEvolution)
            {
                ResultBox.AppendText(String.Format("{0} has an evolution!{1}", pokemonName,Environment.NewLine));
                ResultBox.AppendText(String.Format("Method of evolution: {0}{1}", pokemon.evolutions[0].method, Environment.NewLine));
            }
            else
            {
                ResultBox.AppendText(String.Format("{0} has no evolution.{1}", pokemonName,Environment.NewLine));
            }

            ResultBox.AppendText(Environment.NewLine);
        }
        //TODO
        public AccessToken Login(string userName, string password, string state)
        {
            var client = new RestClient(@"https://api.twitch.tv/kraken/oauth2/token");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-type", "application/json");
            request.AddBody(
                new
                {
                    client_id = ClientID,
                    client_secret = ClientSecret,
                    grant_type = "authorization_code",
                    redirect = @"https://localhost",
                    code = /*code received from redirect*/,
                    state = state
                });

            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject<AccessToken>(response.Content);
                return result;
            }
            return null;
        }
        public TeamCityClient(string username, string password, string serverUrl)
        {
            _username = username;
            _password = password;

            _restClient = new RestClient(serverUrl) { Authenticator = new HttpBasicAuthenticator(_username, _password) };
        }
Example #12
0
        /// <summary>
        /// Use this method first to retrieve the url to redirect the user to to allow the url.
        /// Once they are done there, Fitbit will redirect them back to the predetermined completion URL
        /// </summary>
        /// <returns></returns>
        public string GetAuthUrlToken()
        {
			var baseUrl = "https://api.fitbit.com";
			var client = new RestClient(baseUrl);
			client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);
            
            var request = new RestRequest("oauth/request_token", Method.POST);
			var response = client.Execute(request);


			//Assert.NotNull(response);
			//Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            if(response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception("Request Token Step Failed");

			var qs = HttpUtility.ParseQueryString(response.Content);
			var oauth_token = qs["oauth_token"];
			var oauth_token_secret = qs["oauth_token_secret"];

			//Assert.NotNull(oauth_token);
			//Assert.NotNull(oauth_token_secret);

			request = new RestRequest("oauth/authorize");
			request.AddParameter("oauth_token", oauth_token);
			var url = client.BuildUri(request).ToString();
			//Process.Start(url);

            return url;
        }
 public IRestResponse Run(Step step, ScenarioContext context)
 {
     var apiStep = (ApiOptionsStep)step;
     var client = new RestClient(apiStep.Host);
     var restRequest = BuildRequest(apiStep);
     return client.Options(restRequest);
 }
Example #14
0
        private Task<dynamic> GetCore(dynamic parameters, CancellationToken ct)
        {
            return Task<dynamic>.Factory.StartNew(() => {

                this.RequiresAuthentication();

                var user = Context.CurrentUser as Identity;
                if (user == null)
                    return Negotiate.WithStatusCode(Nancy.HttpStatusCode.Unauthorized);

                List<string> responses = new List<string>();

                var client = new RestClient(Request.Url.SiteBase);
                foreach (var device in _connection.Select<Device>())
                {
                    var request = new RestRequest(DevicesProxyModule.PATH + "/.well-known/core", Method.GET);
                    request.AddUrlSegment("id", device.Id.ToString(CultureInfo.InvariantCulture));
                    request.AddParameter("SessionKey", user.Session.SessionKey);

                    var resp = client.Execute(request);

                    if (resp.StatusCode == HttpStatusCode.OK)
                        responses.Add(resp.Content);
                }

                var r = (Response)string.Join(",", responses);
                r.ContentType = "application/link-format";
                return r;
            }, ct);
        }
        //dummy change 1222252fff
        public ActionResult Index()
        {
            var vv = Directory.GetDirectories(@"\\EVBYMINSD246C\Upload_Cache");
            var client = new RestClient(jiraUrl)
            {
                Authenticator = new HttpBasicAuthenticator("*****@*****.**", "ttMLC4eg")
            };

            //var request = new RestRequest("group/user?groupname=jira-developers", Method.POST);
            //request.RequestFormat = DataFormat.Json;
            //request.AddBody(new
            //{
            //    name = "Pete Conlan"
            //});

            //var request = new RestRequest("/user", Method.GET);
            //request.AddParameter("username", "Pete Conlan");

            //IRestResponse resp = client.Execute(request);

            //Regex regex = new Regex(@".*errors.*");
            //Match match = regex.Match(resp.Content);
            //if (match.Success)
            //{
            //    dynamic errorDetail = JObject.Parse(resp.Content);
            //    var error = errorDetail.errorMessages;
            //    return ThrowJsonError(new Exception(error.ToString()));
            //}

            return View();
        }
        /// <summary>
        /// Authorizes app via twitch.tv. If successful redirect is generated and code is parsed
        /// </summary>
        /// <returns></returns>
        public Code authorization()
        {
            {
                var client = new RestClient(@"https://api.twitch.tv/kraken/oauth2/authorize");
                var request = new RestRequest(Method.GET);

                request.AddParameter("response_type", "code");
                request.AddParameter("client_id", ClientID);
                request.AddParameter("redirect_url", @"https://localhost");
                request.AddParameter("scope", "chat_login");
                request.AddParameter("state", state);

                var response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //somehow grab redirect and parse code...

                }
                else
                {
                    return null;
                }
            }
        }
Example #17
0
        public StartupList getStartups(StartupFilter filter)
        {
            var client = new RestClient(StaticValues.RootUri);

            var request = new RestRequest("startups", Method.GET);
            request.AddParameter("filter", StringEnum.GetStringValue(filter));

            var response = client.Execute(request);
            var content = response.Content;

            // Check Errros
            ErrorChecker.CheckForErrors(response, 1);

            if (filter != StartupFilter.Raising)
            {
                var startupsObj = JsonConvert.DeserializeObject<List<Startup>>(content.Replace(",\"fundraising\":false", "").Replace(",\"fundraising\":true", ""));

                return new StartupList()
                {
                    Startups = startupsObj,
                    LastPage = 1,
                    Total = startupsObj.Count,
                    PerPage = 50,
                    Page = 1
                };

            } else {

                var startupsObj = JsonConvert.DeserializeObject<StartupList>(content);
                return startupsObj;
            }
        }
Example #18
0
        /// <summary>
        /// Confirm a newly-created subscription, pre-authorzation or one-off
        /// payment. This method also checks that the resource response data includes
        /// a valid signature and will throw a {SignatureException} if the signature is
        /// invalid.
        /// </summary>
        /// <param name="requestContent">the response parameters returned by the API server</param>
        /// <returns>the confirmed resource object</returns>
        public ConfirmResource ConfirmResource(NameValueCollection requestContent)
        {
            var resource = DeserializeAndValidateRequestSignature(requestContent);

            var request = new RestRequest("confirm", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddBody(
                new
                    {
                        resource_id = resource.ResourceId,
                        resource_type = resource.ResourceType
                    });

            var client = new RestClient
                             {
                                 BaseUrl = new System.Uri(ApiClient.ApiUrl),
                                 UserAgent = GoCardless.UserAgent
                             };
            var serializer = new JsonSerializer
            {
                ContractResolver = new UnderscoreToCamelCasePropertyResolver(),
            };
            client.AddHandler("application/json", new NewtonsoftJsonDeserializer(serializer));
            client.Authenticator = new HttpBasicAuthenticator(GoCardless.AccountDetails.AppId, GoCardless.AccountDetails.AppSecret);
            var response = client.Execute(request);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new ApiException("Unexpected response : " + (int)response.StatusCode + " " + response.StatusCode);
            }

            return resource;
        }
 public void GetPersons(Action<List<Person>> callback)
 {
     var client = new RestClient("https://raw.github.com/bekkopen/dotnetkurs/master/PersonPhoneApp/");
     client.AddHandler("text/plain", new JsonDeserializer());
     var request = new RestRequest("Persons.json", Method.GET) {RequestFormat = DataFormat.Json};
     client.ExecuteAsync<List<Person>>(request, response => callback(response.Data));
 }
        /// <summary>
        /// This example uses the raw JSON string to create a POST
        /// request for sending one or more SMTP messages through Email-On-Demand.
        /// 
        /// The JSON request generated by this sample code looks like this:
        /// 
        ///{
        ///    "ServerId": "YOUR SERVER ID HERE",
        ///    "ApiKey": "YOUR API KEY HERE",
        ///    "Messages": [{
        ///        "Subject": "Email subject line for raw JSON example.",
        ///        "TextBody": "The text portion of the message.",
        ///        "HtmlBody": "<h1>The html portion of the message</h1><br/>Test",
        ///        "To": [{
        ///            "EmailAddress": "*****@*****.**",
        ///            "FriendlyName": "Customer Name"
        ///        }],
        ///        "From": {
        ///            "EmailAddress": "*****@*****.**",
        ///            "FriendlyName": "From Address"
        ///        },
        ///    }]
        ///}
        /// </summary>
        public static void SimpleInjectionViaStringAsJson(
            int serverId, string yourApiKey, string apiUrl)
        {
            // The client object processes requests to the SocketLabs Injection API.
            var client = new RestClient(apiUrl);

            // Construct the string used to generate JSON for the POST request.
            string stringBody =
                "{" +
                    "\"ServerId\":\"" + serverId + "\"," +
                    "\"ApiKey\":\"" + yourApiKey + "\"," +
                    "\"Messages\":[{" +
                        "\"Subject\":\"Email subject line for raw JSON example.\"," +
                        "\"TextBody\":\"The text portion of the message.\"," +
                        "\"HtmlBody\":\"<h1>The html portion of the message</h1><br/>Test\"," +
                        "\"To\":[{" +
                            "\"EmailAddress\":\"[email protected]\"," +
                            "\"FriendlyName\":\"Customer Name\"" +
                        "}]," +
                        "\"From\":{" +
                            "\"EmailAddress\":\"[email protected]\"," +
                            "\"FriendlyName\":\"From Address\"" +
                        "}," +
                    "}]" +
                "}";

            try
            {
                // Generate a new POST request.
                var request = new RestRequest(Method.POST) { RequestFormat = DataFormat.Json };

                // Store the request data in the request object.
                request.AddParameter("application/json; charset=utf-8", stringBody, ParameterType.RequestBody);

                // Make the POST request.
                var result = client.ExecuteAsPost(request, "POST");

                // Store the response result in our custom class.
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result.Content)))
                {
                    var serializer = new DataContractJsonSerializer(typeof (PostResponse));
                    var resp = (PostResponse) serializer.ReadObject(stream);

                    // Display the results.
                    if (resp.ErrorCode.Equals("Success"))
                    {
                        Console.WriteLine("Successful injection!");
                    }
                    else
                    {
                        Console.WriteLine("Failed injection! Returned JSON is: ");
                        Console.WriteLine(result.Content);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error, something bad happened: " + ex.Message);
            }
        }
        private void cargarKPIsAsignados()
        {
            RestClient client = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
            RestRequest request = new RestRequest("kpis/indicadoresAsignados/{idRol}", Method.GET);

            request.AddUrlSegment("idRol", (string)Session["idRolSeleccionado"]);

            var response = client.Execute(request);

            string json = response.Content;

            List<KPI> listaKpis = JsonConvert.DeserializeObject<List<KPI>>(json);

            if (listaKpis != null)
            {
                DataTable tablaIndicadoresKPIAsignados = new DataTable("kpis");
                tablaIndicadoresKPIAsignados.Columns.AddRange(new DataColumn[5] {new DataColumn("ID",typeof(int)),
                new DataColumn("Descripcion",typeof(string)),
                new DataColumn("Formato",typeof(string)),
                new DataColumn("Objetivo",typeof(string)),
                new DataColumn("Periodicidad",typeof(string))
                });
                if (listaKpis.Count > 0)
                    foreach (var kpi in listaKpis)
                        tablaIndicadoresKPIAsignados.Rows.Add(kpi.KPIID, kpi.DescKpi, kpi.Formato, kpi.Objetivo, kpi.Periodicidad);

                Session["indicadoresKPIAsignados"] = tablaIndicadoresKPIAsignados;
                bindData(false);
            }
        }
        public ZapireNotificationProvider()
        {
            // link to the trello board: https://trello.com/b/oQAFDog0

            // create a rest client and use the url provided by Zapier
            _client = new RestClient("https://zapier.com/hooks/catch/3t0dam/");
        }
        public ActionResult FacebookAuth()
        {
            if (Request.Params.AllKeys.Contains("code"))
            {
                var code = Request.Params["code"];
                var client = new RestClient("https://graph.facebook.com/oauth/access_token");
                var request = new RestRequest(Method.GET);

                //request.AddParameter("action", "access_token");
                request.AddParameter("client_id", this.ClientID);
                request.AddParameter("redirect_uri", this.FacebookCallbackUrl);
                request.AddParameter("client_secret", this.ClientSecret);
                request.AddParameter("code", code);

                var response = client.Execute(request);

                var pairResponse = response.Content.Split('&');
                var accessToken = pairResponse[0].Split('=')[1];

                client = new RestClient("https://graph.facebook.com/me");
                request = new RestRequest(Method.GET);

                request.AddParameter("access_token", accessToken);

                response = client.Execute(request);

                JObject jObject = JObject.Parse(response.Content);
            }

            return RedirectToAction("Index", "Home");
        }
Example #24
0
        protected void btnCrear_Click(object sender, EventArgs e)
        {
            if (validarCampos())
            {
                RestClient client = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
                RestRequest request = new RestRequest("kpis/", Method.POST);

                List<DetalleFormula> formulaCompleta = new List<DetalleFormula>();

                for (int i = 0; i < formula.Count; i++)
                {
                    formulaCompleta.Add(new DetalleFormula(i, variables[i], formula[i]));
                }

                KPI kpiNuevo = new KPI(0, txtDescripcion.Text, ddlFormato.Text, Convert.ToDouble(txtObjetivo.Text), ddlPeriodicidad.Text, new ParametroKPI(Convert.ToInt32(ddlLimiteInf.Text), Convert.ToInt32(ddlLimiteSup.Text)), formulaCompleta);

                request.AddJsonBody(kpiNuevo);

                var response = client.Execute(request);

                formula = new List<string>();
                variables = new List<string>();
                operador = false;

                Response.Redirect("indicadoresKPI.aspx");
            }
            else
            {
                //"error"
            }
        }
 public IEnumerable<Event> Get()
 {
     var client = new RestClient(@"https://github.com");
     var request = new RestRequest(string.Format("{0}.json", _username));
     var response = client.Execute(request);
     return JsonConvert.DeserializeObject<IList<Event>>(response.Content);
 }
 public CustomDataHelper(string site, string user, string password, string baseUrl)
 {
     _client = new RestClient(baseUrl)
                   {
                       Authenticator = new HttpBasicAuthenticator(site + "\\" + user, password)
                   };
 }
Example #27
0
        static void callPhone(string phonenumber, string message)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                delegate
                {
                    return true;
                });

            var client = new RestClient("https://api.shoutpoint.com");
            var request = new RestRequest("v0/Dials/Connect", Method.POST);
            request.AddHeader("x-api-key", "SncRoqW8Lf4B4xA0nv5MH9tzKHnPfraA");
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", "{\"call\":{\"no\":" + phonenumber + ",\"caller_id_no\":\"17607183780\"}}", ParameterType.RequestBody);//16024784411
            var responce = client.Execute(request);//19492465047
            Console.WriteLine(responce);
            callobj test = JsonConvert.DeserializeObject<callobj>(responce.Content);
            var request2 = new RestRequest("v0/LiveCalls/" + test.call.id + "/Actions/HangUp", Method.POST);
            request2.AddHeader("x-api-key", "SncRoqW8Lf4B4xA0nv5MH9tzKHnPfraA");
            request2.AddHeader("Content-Type", "application/json");
            request2.AddParameter("application/json", "{\"message\":[\"" + message + "\"]}", ParameterType.RequestBody);
            var responce2 = client.Execute(request2);
            //var endcall= new RestRequest("v0/Dials/Connect", Method.POST);
            //endcall.AddHeader("x-api-key", "SncRoqW8Lf4B4xA0nv5MH9tzKHnPfraA");
            //endcall.AddHeader("Content-Type", "application/json");
        }
Example #28
0
 protected OKServiceRequest(string path, RequestParams parameters, OKRestVerb verb)
 {
     _path = path;
     _params = parameters;
     _verb = verb;
     _httpClient = GetServiceClient();
 }
        /// <summary>Creates new card registration data.</summary>
        /// <param name="cardRegistration">Card registration data object to create.</param>
        /// <returns>Card registration object returned from API.</returns>
        public CardRegistrationDataDTO RegisterCardData(CardRegistrationDataPostDTO cardRegistrationData)
        {
            var client = new RestClient(cardRegistrationData.CardRegistrationURL);

            var request = new RestRequest(Method.POST);
            request.AddParameter(Constants.DATA, cardRegistrationData.PreregistrationData);
            request.AddParameter(Constants.ACCESS_KEY_REF, cardRegistrationData.AccessKey);
            request.AddParameter(Constants.CARD_NUMBER, cardRegistrationData.CardNumber);
            request.AddParameter(Constants.CARD_EXPIRATION_DATE, cardRegistrationData.CardExpirationDate);
            request.AddParameter(Constants.CARD_CVX, cardRegistrationData.CardCvx);

            var response = client.Execute(request);

            var responseString = response.Content;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var cardRegistrationDataDTO = new CardRegistrationDataDTO
                {
                    RegistrationData = responseString
                };
                return cardRegistrationDataDTO;
            }
            else
                throw new Exception(responseString);
        }
Example #30
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();
        }
        public List <T> GetDataSync <T>(string filterType, string filterText)
        {
            // Set up our return data object -- a list of typed objects.
            List <T> returnData = new List <T>();

            // dch rkl 12/07/2016 capture errors with try/catch
            try
            {
                App_Settings appSettings = App.Database.GetApplicationSettings();

                // set up the proper URL
                string url = GetRestServiceUrl();
                if (!url.EndsWith(@"/"))
                {
                    url += @"/";
                }
                if ((filterType != null) &&
                    (filterType.Length > 0) &&
                    (filterText != null) &&
                    (filterText.Length > 0))
                {
                    url += @"q/" + typeof(T).Name + @"/" + filterType + @"?v=" + Uri.EscapeDataString(filterText);
                }
                else
                {
                    url += @"all/" + typeof(T).Name;
                }

                // Create a HTTP client to call the REST service
                RestSharp.RestClient client = new RestSharp.RestClient(url);

                var request = new RestSharp.RestRequest(Method.GET);
                if (appSettings.DeviceID != null)
                {
                    SimpleAES encryptText = new SimpleAES("V&WWJ3d39brdR5yUh5(JQGHbi:FB@$^@", "W4aRWS!D$kgD8Xz@");
                    string    authid      = encryptText.EncryptToString(appSettings.DeviceID);
                    string    datetimever = encryptText.EncryptToString(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz"));
                    request.AddHeader("x-tdws-authid", authid);
                    request.AddHeader("x-tdws-auth", datetimever);
                }

                var response = client.Execute(request);

                // dch rkl 12/09/2016 include not found
                //if (response.StatusCode != System.Net.HttpStatusCode.OK)
                if (response.StatusCode != System.Net.HttpStatusCode.OK && response.StatusCode != System.Net.HttpStatusCode.NotFound)
                {
                    //throw new Exception("Bad request");
                    ErrorReporting errorReporting = new ErrorReporting();
                    // dch rkl 12/07/2016 add the call/sub/proc to log
                    //errorReporting.sendException(new Exception(response.Content));
                    errorReporting.sendException(new Exception(response.Content), "RestClient.cs.GetDataSync");
                }

                string JsonResult = response.Content;
                returnData = JsonConvert.DeserializeObject <List <T> >(JsonResult);
            }
            catch (Exception ex)
            {
                // dch rkl 12/07/2016 Log Error
                ErrorReporting errorReporting = new ErrorReporting();
                errorReporting.sendException(ex, string.Format("TechDashboard.RestClient.GetDataSync: FilterType={0}; FilterText={1}",
                                                               filterType, filterText));
            }

            return(returnData);
        }
Example #32
0
        public JsonResult ConsultarDatosTrabajador(string numeroDocumento)
        {
            string data    = "";
            string mensaje = "";

            //Modificado por Javier García (Kerocorp) 7/03/2017
            try
            {
                List <EDTipoDocumento> ListaDocumentos = lnausencia.ObtenerTipoDocumento();



                var usuarioActual = ObtenerUsuarioEnSesion(System.Web.HttpContext.Current);
                //if (usuarioActual == null)
                //{
                //    ViewBag.Mensaje = "Debe estar autenticado para registrar una Ausencia.";
                //    return View();
                //}
                EmpresaAfiliadoModel datos = null;

                if (!string.IsNullOrEmpty(numeroDocumento))
                {
                    foreach (var tdoc in ListaDocumentos)
                    {
                        var cliente = new RestSharp.RestClient(ConfigurationManager.AppSettings["Url"]);
                        var request = new RestRequest(consultaAfiliadoEmpresaActivo, RestSharp.Method.GET);
                        request.RequestFormat = DataFormat.Xml;
                        request.Parameters.Clear();
                        request.AddParameter("tpEm", usuarioActual.SiglaTipoDocumentoEmpresa);
                        request.AddParameter("docEm", usuarioActual.NitEmpresa);
                        request.AddParameter("tpAfiliado", tdoc.Sigla.ToLower());
                        request.AddParameter("docAfiliado", numeroDocumento);
                        request.AddHeader("Content-Type", "application/json");
                        request.AddHeader("Accept", "application/json");

                        ServicePointManager.ServerCertificateValidationCallback = delegate
                        { return(true); };
                        IRestResponse <List <EmpresaAfiliadoModel> > response = cliente.Execute <List <EmpresaAfiliadoModel> >(request);
                        var result = response.Content;

                        if (!string.IsNullOrWhiteSpace(result))
                        {
                            var respuesta = Newtonsoft.Json.JsonConvert.DeserializeObject <List <EmpresaAfiliadoModel> >(result);
                            if (respuesta.Count == 0)
                            {
                                data = "No existe relación laboral entre el documento ingresado y la empresa";
                            }
                            mensaje = "NOTFOUND";
                            var EmpresaSystem = respuesta.Where(a => a.estadoEmpresa.ToUpper().Equals("ACTIVA")).FirstOrDefault();
                            if (EmpresaSystem == null)
                            {
                                data = "No existe relación laboral entre el documento ingresado y la empresa";
                            }
                            mensaje = "NOTFOUND";
                            var AfilSystem = respuesta.Where(a => a.estadoPersona.ToUpper().Equals("ACTIVO")).FirstOrDefault();
                            if (AfilSystem == null)
                            {
                                data = "No existe relación laboral entre el documento ingresado y la empresa"; mensaje = "NOTFOUND";
                            }
                            else
                            {
                                GuardarSesionAfiliado(AfilSystem);
                                datos = AfilSystem;
                                return(Json(new { Data = datos, Mensaje = "OK" }));
                            }
                        }
                        else
                        {
                            return(Json(new { Data = "No se obtuvo respuesta del servicio.", Mensaje = "NOTFOUND" }));
                        }
                    }
                    return(Json(new { Data = data, Mensaje = mensaje }));
                }
                else
                {
                    return(Json(new { Data = "Debe Ingresar Un número de documento.", Mensaje = "NOTFOUND" }));
                }
                //Fin Modificación

                //    var cliente = new RestSharp.RestClient(ConfigurationManager.AppSettings["Url"]);
                //    var request = new RestRequest(ConfigurationManager.AppSettings["consultaAfiliado"], RestSharp.Method.GET);
                //    request.RequestFormat = DataFormat.Xml;
                //    request.Parameters.Clear();
                //    request.AddParameter("tpDoc", "cc");
                //    request.AddParameter("doc", numeroDocumento);
                //    request.AddHeader("Content-Type", "application/json");
                //    request.AddHeader("Accept", "application/json");

                //    //se omite la validación de certificado de SSL
                //    ServicePointManager.ServerCertificateValidationCallback = delegate
                //    { return true; };
                //    IRestResponse<List<AfiliadoModel>> response = cliente.Execute<List<AfiliadoModel>>(request);
                //    var result = response.Content;
                //    if (!string.IsNullOrWhiteSpace(result))
                //    {
                //        var respuesta = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AfiliadoModel>>(result);
                //        if (respuesta.Count == 0)
                //            return Json(new { Data = "No se encontró ningun Trabajador asociado al documento ingresado.", Mensaje = "NOTFOUND" });
                //        var afiliado = respuesta.Where(a => a.Estado == "Activo").FirstOrDefault();
                //        if (afiliado == null)
                //            return Json(new { Data = "El afiliado asociado al documento ingresado se encuentra inactivo.", Mensaje = "INACTIVO" });
                //        else
                //        {
                //            GuardarSesionAfiliado(afiliado);
                //            datos = afiliado;
                //        }
                //    }
                //}
                //if (datos != null)
                //{
                //    return Json(new { Data = datos, Mensaje = "OK" });
                //}
                //else
                //    return Json(new { Data = "No se encontró ningun trabajador asociado al documento ingresado", Mensaje = "NOTFOUND" });
            }
            catch (Exception ex)
            {
                registroLog.RegistrarError(typeof(AusenciasController), string.Format("Error en la Acción ConsultarDatosTrabajador: {0}: {1}", DateTime.Now, ex.StackTrace), ex);
                return(Json(new { Data = "No se logró consultar la información del Trabajador. Intente más tarde.", Mensaje = "ERROR" }));
            }
        }
Example #33
0
        public string getDevIdByName(string devName, string authToken, ILogger log, string cmd, string optional_dev_Id)
        {
            string fmcIP   = System.Environment.GetEnvironmentVariable("FMC_IP", EnvironmentVariableTarget.Process);
            string fmcUUID = System.Environment.GetEnvironmentVariable("FMC_DOMAIN_UUID", EnvironmentVariableTarget.Process);

            string devId  = "";
            var    regUrl = "https://" + fmcIP + "/api/fmc_config/v1/domain/" + fmcUUID + "/devices/devicerecords";

            if ("FTD" == cmd)
            {
                log.LogInformation("util:::: Getting FTD ({0}) Device ID", devName);
            }
            else if ("NIC" == cmd)
            {
                log.LogInformation("util:::: Getting NIC ({0}) Device ID", devName);
                regUrl = regUrl + "/" + optional_dev_Id + "/physicalinterfaces";
                log.LogWarning("util:::: URL : {0}", regUrl);
            }
            else if ("ZONE" == cmd)
            {
                log.LogInformation("util:::: Getting Zone ({0}) Device ID", devName);
                regUrl = "https://" + fmcIP + "/api/fmc_config/v1/domain/" + fmcUUID + "/object/securityzones";
            }
            else if ("NAT" == cmd)
            {
                log.LogInformation("util:::: Getting NAT policy ({0}) ID", devName);
                regUrl = "https://" + fmcIP + "/api/fmc_config/v1/domain/" + fmcUUID + "/policy/ftdnatpolicies";
            }
            else
            {
                log.LogError("util:::: Unknown command");
                return("ERROR");
            }

            regUrl = regUrl + "?offset=0&limit=1000";

            var devClient  = new RestClient(regUrl);
            var devRequest = new RestRequest(Method.GET);

            //Disable SSL certificate check
            devClient.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

            devRequest.AddHeader("X-auth-access-token", authToken);

            var response = devClient.Execute(devRequest);

            if (response.StatusCode.ToString() != "OK")
            {
                log.LogError("util:::: Failed get Device ID (Status Code : {0}", response.StatusCode);
                return("ERROR");
            }

            log.LogInformation("util:::: Successfully got Response for Device id request ");
            log.LogDebug("util:::: response : {0}", response.Content);

            try
            {
                //convert string to json object
                JObject o = JObject.Parse(response.Content);

                foreach (var item in o["items"])
                {
                    if (devName == item["name"].ToString())
                    {
                        devId = item["id"].ToString();
                        break;
                    }
                }

                if (0 == devId.Length)
                {
                    log.LogError("util:::: Unable to get Device ID for Device Name({0})", devName);
                    log.LogError("util:::: Contents received from FMC : {0}", response.Content);
                    return("ERROR");
                }
            }
            catch
            {
                log.LogError("util:::: Exception Occoured");
                return("ERROR");
            }
            log.LogInformation("util:::: Found  Device({0}) ID : {1} ", devName, devId);
            return(devId);
        }
Example #34
0
        //*********************Get Object ID by name from FMC*****************************************************************
        public string getObjIdByName(string objName, string authToken, ILogger log, string cmd)
        {
            string fmcIP   = System.Environment.GetEnvironmentVariable("FMC_IP", EnvironmentVariableTarget.Process);
            string fmcUUID = System.Environment.GetEnvironmentVariable("FMC_DOMAIN_UUID", EnvironmentVariableTarget.Process);

            string objId  = "";
            string type   = "";
            var    regUrl = "https://" + fmcIP + "/api/fmc_config/v1/domain/" + fmcUUID + "/object/";

            if ("HOST" == cmd)
            {
                log.LogInformation("util:::: Getting Host obj ({0})  ID", objName);
                regUrl = regUrl + "hosts";
                type   = "Host";
            }
            else if ("PORT" == cmd)
            {
                log.LogInformation("util:::: Getting Port obj ({0})  ID", objName);
                regUrl = regUrl + "protocolportobjects";
                type   = "ProtocolPortObject";
            }
            else if ("NETWORK" == cmd)
            {
                log.LogInformation("util:::: Getting Network obj ({0})  ID", objName);
                regUrl = regUrl + "networkaddresses";
                type   = "Network";
            }
            else if ("NETWORKGROUP" == cmd)
            {
                log.LogInformation("util:::: Getting Network Group obj ({0})  ID", objName);
                regUrl = regUrl + "networkgroups";
                type   = "NetworkGroup";
            }
            else
            {
                log.LogError("util:::: Unknown command");
                return("ERROR");
            }

            regUrl = regUrl + "?offset=0&limit=1000";

            var devClient  = new RestClient(regUrl);
            var devRequest = new RestRequest(Method.GET);

            //Disable SSL certificate check
            devClient.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

            devRequest.AddHeader("X-auth-access-token", authToken);

            var response = devClient.Execute(devRequest);

            if (response.StatusCode.ToString() != "OK")
            {
                log.LogError("util:::: Failed get Device ID (Status Code : {0}", response.StatusCode);
                return("ERROR");
            }

            log.LogInformation("util:::: Successfully got Response for Device id request ");
            log.LogDebug("util:::: response : {0}", response.Content);

            //convert string to json object
            try
            {
                JObject o = JObject.Parse(response.Content);

                foreach (var item in o["items"])
                {
                    if ((objName == item["name"].ToString()) && (type == item["type"].ToString()))
                    {
                        objId = item["id"].ToString();
                        break;
                    }
                }

                if (0 == objId.Length)
                {
                    log.LogError("util:::: Unable to get Device ID for Device Name({0})", objName);
                    log.LogError("util:::: Contents received from FMC : {0}", response.Content);
                    return("ERROR");
                }
            }
            catch
            {
                log.LogError("util:::: Exception occoured");
                return("ERROR");
            }

            log.LogInformation("util:::: Found FTD Device({0}) ID : {1} ", objName, objId);
            return(objId);
        }
 public BaseService()
 {
     RestClient = new RestSharp.RestClient(ApiUrl);
 }
Example #36
0
        public async Task <ResponseData> LayChiTietPhieuNhapKho(int phieuNhapId)
        {
            try
            {
                string url     = string.Format("{0}/api/import/get-detail/{1}", Config.HOST, phieuNhapId);
                var    client  = new RestSharp.RestClient(url);
                var    request = new RestSharp.RestRequest(Method.GET);
                request.AddHeader("content-type", "application/json; charset=utf-8");
                request.AddHeader("x-access-token", UserResponse.AccessToken);

                var response = await client.ExecuteTaskAsync(request);

                var responseParse = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(response.Content);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var     data    = responseParse["data"];
                    NhapKho nhapKho = Newtonsoft.Json.JsonConvert.DeserializeObject <NhapKho>(data.ToString());
                    Kho     kho     = new Kho()
                    {
                        Id  = data["IdKho"],
                        Ten = data["TenKho"]
                    };
                    NhanVien nhanVien = new NhanVien()
                    {
                        Id  = data["IdNhanVien"],
                        Ten = data["TenNhanVien"]
                    };
                    NhaCungCap nhaCungCap = new NhaCungCap()
                    {
                        Id  = data["IdNhaCungCap"],
                        Ten = data["TenNhaCungCap"]
                    };
                    nhapKho.NhanVien   = nhanVien;
                    nhapKho.Kho        = kho;
                    nhapKho.NhaCungCap = nhaCungCap;

                    var danhSachVatTuJson = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(data["DanhSachVatTu"].ToString());

                    List <ChiTietNhapKho> listChiTietNhapKho = new List <ChiTietNhapKho>();
                    foreach (var item in danhSachVatTuJson)
                    {
                        ChiTietNhapKho chiTiet = Newtonsoft.Json.JsonConvert.DeserializeObject <ChiTietNhapKho>(item.ToString());
                        VatTu          vatTu   = new VatTu()
                        {
                            Id  = item["IdVatTu"],
                            Ten = item["TenVatTu"]
                        };
                        chiTiet.VatTu   = vatTu;
                        chiTiet.NhapKho = nhapKho;
                        listChiTietNhapKho.Add(chiTiet);
                    }
                    return(new ResponseData()
                    {
                        Status = Config.CODE_OK,
                        Data = listChiTietNhapKho,
                        Message = ""
                    });
                }
                else
                {
                    return(Util.GenerateErrorResponse(response, responseParse));
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        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);
            }
        }
Example #38
0
        public Task <BaseRestSharp.RestResponse> InvokeCall(HttpServiceRequest httpRequest, bool throwException = true,
                                                            bool isElasticLog = false, bool invokeAsync = false)
        {
            ServicePointManager.DefaultConnectionLimit = 200;
            // Base URL
            BaseRestSharp.RestClient    client   = new BaseRestSharp.RestClient(httpRequest.Url);
            BaseRestSharp.IRestResponse response = null;
            Stopwatch watch = new Stopwatch();


            // Method to be triggered
            BaseRestSharp.RestRequest request = new BaseRestSharp.RestRequest(httpRequest.Action, (BaseRestSharp.Method)httpRequest.MethodType)
            {
                Timeout = httpRequest.Timeout
            };

            if (httpRequest.CookieJar != null)
            {
                foreach (Cookie cookie in httpRequest.CookieJar)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }
            }

            if (httpRequest.Body != null)
            {
                request.RequestFormat = BaseRestSharp.DataFormat.Json;
                request.AddJsonBody(httpRequest.Body);
            }

            if (httpRequest.Headers != null)
            {
                foreach (KeyValuePair <string, string> header in httpRequest.Headers.ToList())
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }


            if (httpRequest.QueryStringParameters != null)
            {
                foreach (KeyValuePair <string, string> param in httpRequest.QueryStringParameters.ToList())
                {
                    request.AddQueryParameter(param.Key, param.Value);
                }
            }

            watch.Start();

            BaseRestSharp.RestResponse customRestResponse = null;
            TaskCompletionSource <BaseRestSharp.RestResponse> taskCompletionSource = new TaskCompletionSource <BaseRestSharp.RestResponse>();


            response = client.Execute(request);
            watch.Stop();

            taskCompletionSource.SetResult(customRestResponse);

            ResponseVerifications(response, throwException, httpRequest.Url, httpRequest.MethodType);


            return(taskCompletionSource.Task);
        }
        private async Task <bool> GetItems()
        {
            if (Connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                ErrorDocs.Clear();
                RestSharp.RestClient client = new RestSharp.RestClient();
                string path = "DocumentSQLConnection";
                client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath + path);
                {
                    await GetAllHeaders();

                    if (CompleteNums.Count == 0)
                    {
                        await DisplayAlert("Done", "There are no futher outstanding orders to complete!", "OK");

                        await Navigation.PopAsync();

                        return(false);
                    }
                    foreach (string strNum in CompleteNums)
                    {
                        string str     = $"GET?qry=SELECT * FROM tblTempDocLines WHERE DocNum='" + strNum + "'";
                        var    Request = new RestSharp.RestRequest();
                        Request.Resource = str;
                        Request.Method   = RestSharp.Method.GET;
                        var cancellationTokenSource = new CancellationTokenSource();
                        var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                        if (res.Content.ToString().Contains("DocNum"))
                        {
                            DataSet myds = new DataSet();
                            myds = Newtonsoft.Json.JsonConvert.DeserializeObject <DataSet>(res.Content);
                            foreach (DataRow row in myds.Tables[0].Rows)
                            {
                                try
                                {
                                    var Doc = new DocLine();
                                    Doc.DocNum       = row["DocNum"].ToString();
                                    Doc.SupplierCode = row["SupplierCode"].ToString();
                                    Doc.SupplierName = row["SupplierName"].ToString();
                                    Doc.ItemBarcode  = row["ItemBarcode"].ToString();
                                    Doc.ItemCode     = row["ItemCode"].ToString();
                                    Doc.ItemDesc     = row["ItemDesc"].ToString();
                                    Doc.Bin          = row["Bin"].ToString();
                                    try
                                    {
                                        Doc.ScanAccQty = Convert.ToInt32(row["ScanAccQty"].ToString().Trim());
                                    }
                                    catch
                                    {
                                        Doc.ScanAccQty = 0;
                                    }
                                    Doc.ScanRejQty = 0;
                                    try
                                    {
                                        Doc.PalletNum = Convert.ToInt32(row["PalletNumber"].ToString().Trim());
                                    }
                                    catch
                                    {
                                        Doc.PalletNum = 0;
                                    }
                                    try
                                    {
                                        Doc.Balacnce = Convert.ToInt32(row["Balacnce"].ToString().Trim());
                                    }
                                    catch
                                    {
                                        Doc.Balacnce = 0;
                                    }
                                    if (Convert.ToInt32(Doc.Balacnce) == -1)
                                    {
                                        Doc.Balacnce = 0;
                                    }
                                    Doc.ItemQty = Convert.ToInt32(row["ItemQty"].ToString().Trim());
                                    await GoodsRecieveingApp.App.Database.Insert(Doc);
                                }
                                catch (Exception ex)
                                {
                                    LodingIndiactor.IsVisible = false;
                                    Vibration.Vibrate();
                                    message.DisplayMessage("Error In Server!!" + ex, true);
                                    return(false);
                                }
                            }
                        }
                    }
                }
                PopData();
            }
            return(false);
        }
        private async void TxfBarcode_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txfBarcode.Text != "")
            {
                Loader.IsVisible = true;
                try
                {
                    BOMItem bi = await GoodsRecieveingApp.App.Database.GetBOMItem(txfBarcode.Text);

                    Loader.IsVisible = false;
                    Vibration.Vibrate();
                    message.DisplayMessage("You can only add single items", true);
                }
                catch
                {
                    try
                    {
                        if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                        {
                            RestSharp.RestClient client = new RestSharp.RestClient();
                            string path = "FindDescAndCode";
                            client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath + path);
                            {
                                string str     = $"GET?qrystr=ACCPRD|4|" + txfBarcode.Text;
                                var    Request = new RestSharp.RestRequest();
                                Request.Resource = str;
                                Request.Method   = RestSharp.Method.GET;
                                var cancellationTokenSource = new CancellationTokenSource();
                                var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                                if (res.IsSuccessful && res.Content.Split('|')[0].Contains("0"))
                                {
                                    if (res.Content.Split('|')[2] == MainPage.docLines.Find(x => x.ItemDesc == "1ItemFromMain").ItemCode)
                                    {
                                        lblItemDesc.Text = res.Content.Split('|')[3];
                                        ItemBarcode      = res.Content.Split('|')[4];
                                        ItemCode         = res.Content.Split('|')[2];
                                        Loader.IsVisible = false;
                                    }
                                    else
                                    {
                                        Loader.IsVisible = false;
                                        Vibration.Vibrate();
                                        message.DisplayMessage("This is not the same product", true);
                                        txfBarcode.Text = "";
                                        txfBarcode.Focus();
                                        return;
                                    }
                                }
                            }
                        }
                        else
                        {
                            Vibration.Vibrate();
                            message.DisplayMessage("No Internet Connection", true);
                        }
                    }
                    catch
                    {
                        lblItemDesc.Text = "No Item With This Code";
                        Loader.IsVisible = false;
                        Vibration.Vibrate();
                        message.DisplayMessage("We could not find this item code", true);
                        txfBarcode.Text = "";
                        txfBarcode.Focus();
                        return;
                    }
                }
                txfQTY.Focus();
            }
        }
 public RestClient(string url = null)
 {
     _client = string.IsNullOrWhiteSpace(url) ? new RestSharp.RestClient() : new RestSharp.RestClient(url);
 }
Example #42
0
 private void AuthenticateIfNeeded(RestClient client, IRestRequest request) =>
 Authenticator?.Authenticate(client, request);
Example #43
0
        public SillycoreRestClient(string baseUrl, string clientId, string clientSecret, string tokenUrl, string scope)
        {
            InitializeDefaults(baseUrl);

            DecoratedClient = new OAuth2Decorator(DecoratedClient, clientId, clientSecret, tokenUrl, scope);
        }
        private void btnCallVerify_Click(object sender, EventArgs e)
        {
            if (txtKey.Text == String.Empty)
            {
                MessageBox.Show("E' necessario specificare una chiave valida per il servizio FILL");
                txtKey.Focus();
                return;
            }

            Cursor = Cursors.WaitCursor;
            Application.DoEvents();


            // inizializzazione client del servizio FILL
            var clientFill = new RestSharp.RestClient();

            clientFill.BaseUrl = new Uri("https://streetmaster.streetmaster.it");

            var request = new RestRequest("smrest/webresources/fill", Method.GET);

            request.RequestFormat = DataFormat.Json;

            // valorizzazione input
            // per l'esempio viene valorizzato un insieme minimo dei parametri
            request.AddParameter("Key", txtKey.Text);
            request.AddParameter("Localita", txtInComune.Text);
            request.AddParameter("Cap", txtInCap.Text);
            request.AddParameter("Provincia", txtInProvincia.Text);
            request.AddParameter("Indirizzo", txtInIndirizzo.Text);
            request.AddParameter("Localita2", String.Empty);
            request.AddParameter("Dug", String.Empty);
            request.AddParameter("Civico", String.Empty);

            var response = clientFill.Execute <FillResponse>(request);

            outFill = response.Data;


            //  output generale
            txtOutEsito.Text   = outFill.Norm.ToString();
            txtOutCodErr.Text  = outFill.CodErr.ToString();
            txtOutNumCand.Text = outFill.NumCand.ToString();

            currCand = 0;

            // dettaglio del primo candidato se esiste
            // nella form di output e' riportato solo un sottoinsieme di tutti i valori restituiti
            if (outFill.Output.Count > 0)
            {
                txtOutCap.Text         = outFill.Output[currCand].Cap;
                txtOutComune.Text      = outFill.Output[currCand].Comune;
                txtOutFrazione.Text    = outFill.Output[currCand].Frazione;
                txtOutIndirizzo.Text   = outFill.Output[currCand].Indirizzo;
                txtOutProvincia.Text   = outFill.Output[currCand].Prov;
                txtOutScoreComune.Text = outFill.Output[currCand].ScoreComune.ToString();
                txtOutScoreStrada.Text = outFill.Output[currCand].ScoreStrada.ToString();
                txtOutX.Text           = outFill.Output[currCand].Geocod.X.ToString("0.#####");
                txtOutY.Text           = outFill.Output[currCand].Geocod.Y.ToString("0.#####");
                txtOutRegione.Text     = outFill.Output[currCand].Detail.Regione;
                txtOutIstatProv.Text   = outFill.Output[currCand].Detail.IstatProv;
                txtOutIstatComune.Text = outFill.Output[currCand].Detail.IstatComune;
            }
            Cursor = Cursors.Default;
        }
Example #45
0
 private void InitializeDefaults(string baseUrl)
 {
     DecoratedClient = new RestSharp.RestClient(baseUrl);
     DecoratedClient.AddHandler("application/json", new CustomJsonSerializer());
     DecoratedClient.UserAgent = "Trendyol.App.RestClient";
 }
Example #46
0
        public JsonResult GetAiQiYiURL(string voteid, bool repeatget = true)
        {
            VideoInfo videoInfo = null;

            _iqiyiclient = new RestSharp.RestClient("http://openapi.iqiyi.com");
            _iqiyiclient.AddHandler("application/json", new RestSharp.Deserializers.JsonDeserializer());
            if (DateTime.Now > overDate || tokeninfo == null)
            {
                var req = new RestSharp.RestRequest("/api/iqiyi/authorize", RestSharp.Method.GET);
                //接口参数
                req.AddParameter("client_id", clientid);
                req.AddParameter("client_secret", clientsecret);

                try
                {
                    var response = _iqiyiclient.Execute(req);
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var json = response.Content.Replace("\\", "");
                        json = json.Substring(1, json.Length - 2);

                        var data = Newtonsoft.Json.JsonConvert.DeserializeObject <BaseInfo <TokenInfo> >(json);
                        if (data != null && data.code == "A00000")
                        {
                            overDate  = DateTime.Now.AddSeconds(data.data.expires_in);
                            tokeninfo = data.data;
                        }
                    }
                    else
                    {
                        return(Json(videoInfo, JsonRequestBehavior.AllowGet));
                    }
                }
                catch (Exception ex)
                {
                    return(Json(videoInfo, JsonRequestBehavior.AllowGet));
                }
            }
            if (tokeninfo != null)
            {
                var req = new RestSharp.RestRequest("/api/file/fullStatus", RestSharp.Method.GET);
                //接口参数
                req.AddParameter("access_token", tokeninfo.access_token);
                req.AddParameter("file_id", voteid);
                try
                {
                    var response = _iqiyiclient.Execute(req);
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var json = response.Content.Replace("\\", "");
                        json = json.Substring(1, json.Length - 2);
                        var data = Newtonsoft.Json.JsonConvert.DeserializeObject <BaseInfo <VideoInfo> >(json);
                        if (data != null && data.code == "A00000")
                        {
                            data.data.m3u896 = data.data.urllist.m3u8[96].ToString();

                            var mp4Client = new RestSharp.RestClient();
                            mp4Client.AddHandler("application/json", new RestSharp.Deserializers.JsonDeserializer());
                            var reqmp4         = new RestSharp.RestRequest(data.data.urllist.mp4[2], RestSharp.Method.GET);
                            var repsonsemp4url = mp4Client.Execute(reqmp4);
                            try
                            {
                                if (repsonsemp4url.StatusCode == HttpStatusCode.OK)
                                {
                                    json = repsonsemp4url.Content;
                                    var i = json.IndexOf('{');
                                    var f = json.LastIndexOf(";");
                                    json = json.Substring(i, f - i);
                                    var mp4urldata = Newtonsoft.Json.JsonConvert.DeserializeObject <BaseInfo <MP4Info> >(json);
                                    if (mp4urldata.code == "A00000")
                                    {
                                        data.data.mp42 = mp4urldata.data.l;
                                    }
                                    else
                                    {
                                        data.data.mp42 = "";
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //_logger.Error("获取MP4地址错误1:" + ex.ToString());
                                throw ex;
                            }

                            videoInfo = data.data;
                        }
                        else if (data != null && data.code == "A00007")
                        {
                            if (repeatget)
                            {
                                var repdata = Newtonsoft.Json.JsonConvert.DeserializeObject <BaseInfo <RepeatVideo> >(json);
                                if (repdata != null && repdata.data != null && repdata.data.fileIdBefore.Length == 32)
                                {
                                    return(GetAiQiYiURL(repdata.data.fileIdBefore, false));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return(Json(videoInfo, JsonRequestBehavior.AllowGet));
        }
Example #47
0
 public void Dispose()
 {
     _client = null;
 }
Example #48
0
 public static RestClientException CreateFailedException(RSharp.RestClient restClient, RSharp.IRestResponse restResponse)
 => RestClientException.Create(restResponse.StatusCode,
                               restResponse.StatusDescription,
                               restResponse.Request.ToRestClientRequest(restClient.BaseUrl),
                               restResponse.ToRestClientRequest());
Example #49
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            string tip = "";

            if (tbSure.Text.Length == 0)
            {
                MessageBox.Show("Enter Countdown");
            }

            int _time = Convert.ToInt32(tbSure.Text);
            int time  = 0;

            if ((BtnSn.IsChecked == true))
            {
                time = _time;
                tip  = "Second";
            }
            else if (BtnDk.IsChecked == true)
            {
                time = _time * 60;
                tip  = "Minute";
            }
            else if (BtnSaat.IsChecked == true)
            {
                time = _time * 3600;
                tip  = "Hour";
            }
            else
            {
                MessageBox.Show("You didnt choose time !");
            }



            string token  = DeviceInfoProp.Login();
            string t      = MillisecondsTimestamp(DateTime.Now);
            string hash   = Hash(DeviceInfoProp.client_id + token + t, DeviceInfoProp.secret);
            var    client = new RestSharp.RestClient("https://openapi.tuyaeu.com/v1.0/devices/" + DeviceInfoProp.device_id + "/commands");

            client.Timeout = -1;
            var request = new RestRequest(Method.POST);

            request.AddHeader("client_id", DeviceInfoProp.client_id);
            request.AddHeader("access_token", token);
            request.AddHeader("sign", hash);
            request.AddHeader("t", t);
            request.AddHeader("sign_method", "HMAC-SHA256");
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", "{\n\t\"commands\":[\n\t\t{\n\t\t\t\"code\": \"countdown_1\",\n\t\t\t\"value\":" + time + "\n\t\t}\n\t]\n}", ParameterType.RequestBody);

            client.Execute(request);

            bool lastState = CheckLastState(DeviceInfoProp.device_id);

            if (lastState)
            {
                m_notifyIcon.BalloonTipText = "Light will turn off after " + _time + " " + tip;
            }
            else
            {
                m_notifyIcon.BalloonTipText = "Light will turn on after " + _time + " " + tip;
            }

            m_notifyIcon.BalloonTipTitle = "The Light App";
            m_notifyIcon.ShowBalloonTip(1000);

            Window.GetWindow(this).Close();
        }
Example #50
0
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile(args[0])
                         .Build();

            var rs = new RestSharp.RestClient(config["ConfluenceUrl"]);

            rs.Authenticator = new HttpBasicAuthenticator(config["User"], config["Token"]);
            rs.ClearHandlers();

            var serializer = new JsonSerializer();

            rs.AddHandler("application/json", new NewtonsoftDeserializer(serializer));

            var container = BuildContainer(rs, config, args[0]);

            var pageUrl = $"/rest/api/content?expand=body,body.atlas_doc_format,container,metadata.properties,ancestors&spaceKey={config["SpaceKey"]}&limit=100";

            var reporter = new ErrorReporter();

            int totalPages   = 0;
            int ignoredPages = 0;

            var rules = CreateRuleSet(container);

            var ignoredPaths = config.GetSection("Ignore")
                               .GetChildren()
                               .Select(x => x.Value)
                               .ToList();

            var debugPages = config.GetSection("DebugPages").GetChildren().Select(x => x.Get <string>()).ToList();

            while (!string.IsNullOrWhiteSpace(pageUrl))
            {
                var response = await rs.ExecuteGetTaskAsync <Paged <Page> >(new RestRequest(pageUrl));

                foreach (var page in response.Data.Results)
                {
                    if (page.Ancestors.ElementAtOrDefault(1)?.Title != config["CheckRoot"])
                    {
                        continue;
                    }

                    var path = page.GetPath();

                    if (ignoredPaths.Any(x => path.StartsWith(x, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        Console.WriteLine($"Ignoring {path}");
                        ignoredPages++;
                        continue;
                    }

                    if (debugPages.Contains(page.Id))
                    {
                        System.Diagnostics.Debugger.Break();
                    }

                    foreach (var rule in rules)
                    {
                        try
                        {
                            rule.Check(page, reporter);
                        }
                        catch (Exception e)
                        {
                            reporter.Report(page, $"Rule {rule.GetType().Name} failed with {e.Message}");
                        }
                    }
                }

                Console.WriteLine(response.Data._links?.Next);
                pageUrl     = response.Data._links?.Next;
                totalPages += response.Data.Results.Count;
            }

            reporter.SendErrorsTo(container.Resolve <ConsoleErrorTarget>());

            Console.WriteLine($"{totalPages} pages in total");
            Console.WriteLine($"{totalPages - ignoredPages} pages checked");
            Console.WriteLine($"{ignoredPages} pages ignored");
            Console.WriteLine($"{reporter.ErrorsCount} errors reported");
        }
        private async Task <bool> GetItems(string code)
        {
            if (await RemoveAllOld(code))
            {
                if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                {
                    RestSharp.RestClient client = new RestSharp.RestClient();
                    string path = "GetDocument";
                    client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath + path);
                    {
                        string str     = $"GET?qrystr=ACCHISTL|6|{code}|102|" + GoodsRecieveingApp.MainPage.UserCode;
                        var    Request = new RestSharp.RestRequest();
                        Request.Resource = str;
                        Request.Method   = RestSharp.Method.GET;
                        var cancellationTokenSource = new CancellationTokenSource();
                        var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                        if (res.Content.ToString().Contains("DocNum"))
                        {
                            if (!firstSO)
                            {
                                if (!await PalletAddSO())
                                {
                                    return(false);
                                }
                            }
                            await GoodsRecieveingApp.App.Database.DeleteSpecificDocs(code);

                            DataSet myds = new DataSet();
                            myds = Newtonsoft.Json.JsonConvert.DeserializeObject <DataSet>(res.Content);
                            foreach (DataRow row in myds.Tables[0].Rows)
                            {
                                try
                                {
                                    var Doc = new DocLine();
                                    Doc.DocNum       = row["DocNum"].ToString();
                                    Doc.SupplierCode = row["SupplierCode"].ToString();
                                    Doc.SupplierName = row["SupplierName"].ToString();
                                    Doc.ItemBarcode  = row["ItemBarcode"].ToString();
                                    Doc.ItemCode     = row["ItemCode"].ToString();
                                    Doc.ItemDesc     = row["ItemDesc"].ToString();
                                    Doc.Bin          = row["Bin"].ToString();
                                    try
                                    {
                                        Doc.ScanAccQty = Convert.ToInt32(row["ScanAccQty"].ToString().Trim());
                                    }
                                    catch
                                    {
                                        Doc.ScanAccQty = 0;
                                    }
                                    Doc.ScanRejQty = 0;
                                    try
                                    {
                                        Doc.PalletNum = Convert.ToInt32(row["PalletNumber"].ToString().Trim());
                                    }
                                    catch
                                    {
                                        Doc.PalletNum = 0;
                                    }
                                    currentPallet   = Doc.PalletNum;
                                    Doc.ItemQty     = Convert.ToInt32(row["ItemQty"].ToString().Trim());
                                    lblCode.Text    = Doc.DocNum;
                                    lblCusName.Text = Doc.SupplierName;
                                    await GoodsRecieveingApp.App.Database.Insert(Doc);
                                }
                                catch (Exception)
                                {
                                    LodingIndiactor.IsVisible = false;
                                    Vibration.Vibrate();
                                    message.DisplayMessage("Error In Server!!", true);
                                    return(false);
                                }
                            }
                            return(true);
                        }
                        else
                        {
                            LodingIndiactor.IsVisible = false;
                            Vibration.Vibrate();
                            message.DisplayMessage("Error Invalid SO Code!!", true);
                        }
                    }
                }
                else
                {
                    LodingIndiactor.IsVisible = false;
                    Vibration.Vibrate();
                    message.DisplayMessage("Internet Connection Problem!", true);
                }
            }
            return(false);
        }
Example #52
0
 public static RestClientException CreateErrorException(RSharp.RestClient restClient, RSharp.IRestResponse restResponse, Exception ex)
 => new RestClientException(HttpStatusCode.InternalServerError,
                            ex.Message,
                            restResponse.Request.ToRestClientRequest(restClient.BaseUrl),
                            restResponse.ToRestClientRequest());
Example #53
0
 public DataRestClient()
 {
     _client = new RestSharp.RestClient(_dataManagementServiceUrl);
 }
Example #54
0
        public string CreateProduct(string access_token, string product_name, string product_discription, double product_price, double product_shipping, string product_sku)
        {
            // access_token string Required. Provided in Oauth flow.
            // product_name string Required. Product name should be unique.
            // product_price numeric / float Required. A numeric / float value that represents the price of the product.
            // product_shipping numeric / float A numeric / float value that represents how much the cost if the product would be shipped to the buyer.
            // product_sku string Merchant's sku for the product.

            this.access_token        = access_token;
            this.product_name        = product_name;
            this.product_price       = product_price;
            this.product_shipping    = product_shipping;
            this.product_sku         = product_sku;
            this.product_description = product_discription;
            try
            {
                string url    = "https://api.aligncommerce.com/products";
                var    client = new RestSharp.RestClient();
                client.BaseUrl       = url;
                client.Authenticator = new HttpBasicAuthenticator(user, pass);
                var request = new RestSharp.RestRequest();
                request.Method = Method.POST;
                //  request.Resource = json;
                request.AddParameter("access_token", this.access_token);
                request.AddParameter("product_name", this.product_name);
                request.AddParameter("product_price", this.product_price);
                request.AddParameter("product_shipping", this.product_shipping);
                request.AddParameter("product_sku", this.product_sku);
                request.AddParameter("product_description", this.product_description);
                IRestResponse response = client.Execute(request);
                //  return response.Content.ToString();

                if (response.StatusCode.ToString() == "200")
                {
                    var js  = new JavaScriptSerializer();
                    var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                    this.Message = dic["message"];
                    return(Message);
                }

                else if (response.StatusCode.ToString() == "400" ||
                         response.StatusCode.ToString() == "401" ||
                         response.StatusCode.ToString() == "402" ||
                         response.StatusCode.ToString() == "403" ||
                         response.StatusCode.ToString() == "404" ||
                         response.StatusCode.ToString() == "500" ||
                         response.StatusCode.ToString() == "502")
                {
                    var js  = new JavaScriptSerializer();
                    var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                    this.Message = dic["error_message"];
                    return(Message);
                }

                else
                {
                    return(response.Content);
                }
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
Example #55
0
        public IActionResult PerformSelfTest()
        {
            // var TargetURL = Request.Scheme + "://" + Request.Host.ToString() + Program.SwaggerJSONFile();
            var basePath   = _conf.GetValue <string>("DefaultPublicFacingHttpUrl", Request.Scheme + "://" + Request.Host.ToString());
            var TargetURL  = basePath + Program.SwaggerJsonFile();
            var Address    = "CYJV9DRIE9NCQJYLOYOJOGKQGOOELTWXVWUYGQSWCNODHJAHACADUAAHQ9ODUICCESOIVZABA9LTMM9RW";
            var BundleHash = "TXGCKHFQPOYLN9BZNLXEKAGVGSRGHHUJUQTRYKJLAHTHUBEBQSBUXGOASFOI9KTUIURHODX9HZFSIHANX";
            var TXHash     = "JYSCFGQDBICFTJKQTRSPOJNCJ9IBAONHTSAQVVYIZVHLVEKGCLLWA9NPQWEEUOBGSHOXKDQSCIVTZ9999";

            _logger.LogInformation("Trying to get API definition from {TargetURL}", TargetURL);

            var client = new RestSharp.RestClient(TargetURL)
            {
                Timeout = 2000
            };
            var resp = client.Execute(new RestSharp.RestRequest(TargetURL, RestSharp.Method.GET));

            if (resp.IsSuccessful && resp.StatusCode == HttpStatusCode.OK)
            {
                // Getting list of all get procedures
                var Source     = JsonConvert.DeserializeObject <JObject>(resp.Content);
                var TestClient = new RestSharp.RestClient(basePath)
                {
                    Timeout = 10000
                };

                var TestResults = new List <SelfTestResult>();
                var ApiCalls    = (from item in Source["paths"]
                                   from v in item.Values()
                                   where (v as JProperty).Name == "get"
                                   select(item as JProperty).Name).ToList();

                foreach (var item in ApiCalls) // let's cycle thru all API paths
                {
                    var ApiCall = item;
                    if (ApiCall.Contains("bundle", StringComparison.InvariantCultureIgnoreCase))
                    {
                        ApiCall = ApiCall.Replace("{hash}", BundleHash, StringComparison.InvariantCultureIgnoreCase);
                    }
                    if (ApiCall.Contains("transaction", StringComparison.InvariantCultureIgnoreCase))
                    {
                        ApiCall = ApiCall.Replace("{hash}", TXHash, StringComparison.InvariantCultureIgnoreCase);
                    }
                    ApiCall = ApiCall.Replace("{address}", Address, StringComparison.InvariantCultureIgnoreCase);
                    ApiCall = basePath + ApiCall;

                    if (!ApiCall.Contains(nameof(PerformSelfTest), StringComparison.InvariantCultureIgnoreCase))
                    {
                        var result = TestClient.Execute(new RestSharp.RestRequest(ApiCall, RestSharp.Method.GET));
                        TestResults.Add(new SelfTestResult()
                        {
                            ApiCall = ApiCall, StatusCode = (int)result.StatusCode
                        });
                        if ((int)result.StatusCode >= 500)
                        {
                            break;
                        }
                    }
                }
                return(Json(TestResults)); // Format the output
            }
            return(StatusCode(500));
        }
Example #56
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tipoDocumentoEmp"></param>
        /// <param name="numDocumentoEmp"></param>
        /// <param name="tipoDocumento"></param>
        /// <param name="numDucumento"></param>
        /// <param name="resultadoEmp"></param>
        /// <param name="resultadoAfi"></param>
        /// <returns></returns>
        private EmpresaAfiliadoModel ConsultarAfiliadoEmpresaActivos(string tipoDocumentoEmp, string numDocumentoEmp, string tipoDocumento, string numDucumento, out int resultadoEmp, out int resultadoAfi)
        {
            try
            {
                EmpresaAfiliadoModel objEmpresaAfi = null;
                //variable para manejar el resultado: 0: No existe la empresa,
                //1: Existe pero se encuentra inactiva, 2: Existe y se encuentra activa
                //3: No existe el afiliado, 4: Existe el afiliado pero se encuentra inactivo
                //5: Existe el afiliado y se encuentra activo.
                resultadoEmp = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.NoExisteEmp;
                resultadoAfi = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.NoExisteAfi;
                var cliente = new RestSharp.RestClient(ConfigurationManager.AppSettings["Url"]);
                var request = new RestRequest(consultaAfiliadoEmpresaActivo, RestSharp.Method.GET);
                request.RequestFormat = DataFormat.Xml;
                request.Parameters.Clear();
                request.AddParameter("tpEm", tipoDocumentoEmp);
                request.AddParameter("docEm", numDocumentoEmp);
                request.AddParameter("tpAfiliado", tipoDocumento);
                request.AddParameter("docAfiliado", numDucumento);
                request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Accept", "application/json");

                //se omite la validación de certificado de SSL
                ServicePointManager.ServerCertificateValidationCallback = delegate
                { return(true); };
                IRestResponse <List <EmpresaAfiliadoModel> > response = cliente.Execute <List <EmpresaAfiliadoModel> >(request);
                var result = response.Content;
                if (!string.IsNullOrWhiteSpace(result))
                {
                    var respuesta = Newtonsoft.Json.JsonConvert.DeserializeObject <List <EmpresaAfiliadoModel> >(result);
                    if (respuesta.Count == 0)
                    {
                        resultadoEmp = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.NoExisteEmp; //No existe
                    }
                    else
                    {
                        var EmpresaSystem = respuesta.Where(a => a.estadoEmpresa.ToUpper().Equals("ACTIVA")).FirstOrDefault();
                        if (EmpresaSystem == null)
                        {
                            resultadoEmp = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.ExisteInactivoEmp; //Existe y está Inactiva
                        }
                        else
                        {
                            resultadoEmp = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.ExisteActivoEmp; //Existe y está Activa
                        }
                        var AfilSystem = respuesta.Where(a => a.estadoPersona.ToUpper().Equals("ACTIVO")).FirstOrDefault();
                        if (AfilSystem == null)
                        {
                            resultadoAfi = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.ExisteInactivoAfi; //Existe y está Inactivo
                        }
                        else
                        {
                            resultadoAfi = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.ExisteActivoAfi; //Existe y está Activo
                        }
                        if (EmpresaSystem != null && AfilSystem != null)
                        {
                            objEmpresaAfi = AfilSystem;
                        }
                    }
                }
                return(objEmpresaAfi);
            }
            catch (Exception ex)
            {
                registroLog.RegistrarError(typeof(HomeController), string.Format("Error en la Acción ConsultarAfiliadoEmpresaActivos: {0}: {1}", DateTime.Now, ex.StackTrace), ex);
                resultadoEmp = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.NoExisteEmp;
                resultadoAfi = (int)Enumeraciones.EnumAdministracionUsuarios.ValidaEstadoEmpAfi.NoExisteAfi;
                return(null);
            }
        }
 public RestClient(Uri baseAddress, Uri resource) : base(baseAddress, resource)
 {
     _restClient = new RSharp.RestClient(baseAddress);
     _restClient.ClearHandlers();
     _restClient.AddHandler("application/json", new RSharp.Serialization.Json.JsonDeserializer());
 }
 public ContactRepository(string baseUrl)
 {
     _baseUrl = baseUrl;
     client   = new  RestSharp.RestClient(new Uri(baseUrl));
 }
Example #59
0
 private RestClient()
 {
     client           = new RestSharp.RestClient();
     client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
 }
        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;
        }