AddParameter() public method

public AddParameter ( Parameter p ) : RestRequest
p Parameter
return RestRequest
        private string ExecuteJobRequest(RestClient client)
        {
            var req = new RestRequest(@"1/job", Method.POST);
            req.AlwaysMultipartFormData = true;

            req.AddParameter("apikey", ApiKey);

            req.AddParameter("job", JsonConvert.SerializeObject(_batch));

            foreach (var v in _files)
            {
                req.AddFile(v.Key, v.Value);
            }

            string resp = null;
            client.ExecuteAsync(req, response => { resp = response.Content; });

            DateTime timeoutTime = DateTime.Now + TimeoutSpan;
            while (string.IsNullOrEmpty(resp) && DateTime.Now < timeoutTime)
            {
                System.Threading.Thread.Sleep(1000);
            }

            if (resp == null)
            {
                throw new TimeoutException("Initial job request timed out");
            }

            return resp;
        }
    public static void Main()
    {
        Console.WriteLine ("Trying to send");

        var client = new RestClient("https://api.46elks.com/a1/SMS");
        var request = new RestRequest(Method.POST);

        client.Authenticator = new RestSharp.Authenticators.
            HttpBasicAuthenticator(
                "<API Username>",
                "<API Password>");

        request.AddParameter(
            "to", "+46723175800",
            ParameterType.GetOrPost);

        request.AddParameter(
            "from", "+46766862078",
             ParameterType.GetOrPost);

        request.AddParameter(
            "message",
            "Hi! This is a message from me! Have åäö a nice day!",
            ParameterType.GetOrPost);

        IRestResponse response = client.Execute(request);
        Console.WriteLine(response.Content);
    }
Example #3
0
File: Mailer.cs Project: kioltk/mvc
 public static void EmailSubmit(string email, string code)
 {
     RestClient client = new RestClient();
     client.BaseUrl = "https://api.mailgun.net/v2";
     client.Authenticator =
             new HttpBasicAuthenticator("api",
                                        "key-032hr3-4h-s2w-esvcatgkvrra5kubs1");
     RestRequest request = new RestRequest();
     request.AddParameter("domain",
                          "nocompany.azurewebsites.net", ParameterType.UrlSegment);
     request.Resource = "{domain}/messages";
     request.AddParameter("from", "Idodil Agency <*****@*****.**>");
     request.AddParameter("to", email);
     request.AddParameter("subject", "Idodil");
     request.AddParameter("html",
         "<html><p>" + GlobalRes.MailerHello +
         "</p><p>" + GlobalRes.MailerEmailNotify +
         "</p><p>" + GlobalRes.MailerEmailBody +
         "</p><p><a href='" + "http://www.idodil.com/account/emailsubmit?token=" + code +"'>"+GlobalRes.EmailSubmitButton+"</a>"+
         "</p><p>" + GlobalRes.MailerEmailFill + code +
         "</p><p>" + GlobalRes.MailerBye +
         "</p></html>");
     request.Method = Method.POST;
     client.ExecuteAsync(request, response =>
     {
         var resp = response.Content;
     });
 }
        /// <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;
                }
            }
        }
        public static string Login(string login, string password)
        {
            var request = new RestRequest("rest/user/login", Method.POST);
            request.AddParameter("login", login);
            request.AddParameter("password", password);

            var client = new RestClient();
            client.BaseUrl = GetBaseUrl().ToString();

            var response = client.Execute(request);

            switch (response.StatusCode)
            {
                case HttpStatusCode.OK:
                    CookieAuthenticator.RedirectFromLogin(login, response.Cookies);
                    return null;
                case HttpStatusCode.Forbidden:
                    dynamic x = JsonConvert.DeserializeObject(response.Content);
                    string error = x.value;
                    return error;
                default:
                    return string.Format("YouTrack returned {0}: {1}",
                                         (int) response.StatusCode,
                                         response.StatusDescription);
            }
        }
Example #6
0
        //expiration date was added
        public string AddExpiration(string month, string year, int PulaID, int loggedInID)
        {
            try
            {
                //build the date
                string Month = month;
                string fullDate = Month + "/01/" + year;
                DateTime ExpireDate = Convert.ToDateTime(fullDate);

                //get the version
                BLTServiceCaller serviceCaller = BLTServiceCaller.Instance;
                var request = new RestRequest();
                request.Resource = "/PULAs/{entityID}/updateStatus?status={status}&statusDate={date}";
                request.RootElement = "ACTIVE_INGREDIENT_PULA";
                request.AddParameter("entityID", PulaID, ParameterType.UrlSegment);
                request.AddParameter("status", "EXPIRED", ParameterType.UrlSegment);
                request.AddParameter("date", ExpireDate, ParameterType.UrlSegment);
                serviceCaller.Execute<ACTIVE_INGREDIENT_PULA>(request);

                return "<label class='inline'>" + fullDate + "</label>";
            }
            catch
            {
                return "Did not work";
            }
        }
Example #7
0
        public static string SendMail(string tittel, string tekst, List<Data.MailPerson> personer)
        {
            foreach (var person in personer)
            {
                var message = tekst.Replace("[competitionlink]", "alf.apphb.com/Competition/SignUp/" + person.Id.ToString());
                message = message.Replace("[betalingslink]", "https://www.deltager.no/participant/arrangement.aspx?id=66098");
                message = message.Replace("[navn]", person.Navn);

                var client = new RestClient();
                client.BaseUrl = "https://api.mailgun.net/v2";
                client.Authenticator = new HttpBasicAuthenticator("api", "key-95iv2azanw509luzmo3a7eepdkfy3uu8");

                var request = new RestRequest();
                request.AddParameter("domain", "app13455.mailgun.org", ParameterType.UrlSegment);
                request.Resource = "{domain}/messages";
                request.AddParameter("from", "Another Lindyhop Festival <*****@*****.**>");
                request.AddParameter("to", person.Adresse);
                request.AddParameter("subject", tittel);
                request.AddParameter("text", message);
                request.Method = Method.POST;

                var response = client.Execute(request);
            }

            return "Ok.";
        }
        public void SendPush(PushNotificationPayload payload)
        {
            try
            {
                var client = new RestClient("https://api.cloud.appcelerator.com")
                                 {
                                     CookieContainer = new System.Net.CookieContainer()
                                 };
                var request = new RestRequest("/v1/push_notification/notify_tokens.json?key=" + appKey, Method.POST)
                                  {
                                      RequestFormat = DataFormat.Json,
                                      Method = Method.POST
                                  };

                request.AddParameter("channel", payload.Channel);
                request.AddParameter("to_tokens", string.Join(",", payload.DeviceTokens));
                request.AddParameter("payload", "{ 'alert': '" + payload.Message + "', 'icon': '" + payload.Icon + "', 'badge': " + payload.Badge + ", 'title': '" + payload.Title + "', 'vibrate': " + payload.Vibrate.ToString().ToLower() + " }");
                var response = client.Execute(request);
                var error = response.ErrorMessage;
                var content = response.Content;
                Console.WriteLine(content);
                Console.WriteLine("");
                Console.WriteLine(error);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Message " + ex.Message + " \n Inner Exception " + ex.InnerException + " \n Stack Trace" + ex.StackTrace);
            }
        }
Example #9
0
        // Creates and sets up a RestRequest prior to a call.
        private RestRequest PrepareRequest(
            String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
            Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
            Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams)
        {
            var request = new RestRequest(path, method);
   
            // add path parameter, if any
            foreach(var param in pathParams)
                request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); 

            // add header parameter, if any
            foreach(var param in headerParams)
                request.AddHeader(param.Key, param.Value);

            // add query parameter, if any
            foreach(var param in queryParams)
                request.AddQueryParameter(param.Key, param.Value);

            // add form parameter, if any
            foreach(var param in formParams)
                request.AddParameter(param.Key, param.Value);

            // add file parameter, if any
            foreach(var param in fileParams)
                request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);

            if (postBody != null) // http body (model) parameter
                request.AddParameter("application/json", postBody, ParameterType.RequestBody);
    
            return request;
        }
Example #10
0
        public static void SendRegistrationConfirmed(string userid, string mail)
        {
            var message = string.Format(
            @"Thank you for registering for ALF!

            Your personal registration for the competition can be accessed here: alf.apphb.com/Competition/SignUp/{0}

            Payment information:
            To pay for your attendace at ALF 2013 we will accept payments through deltager.no here https://www.deltager.no/participant/arrangement.aspx?id=66098

            We are looking forward to seeing you at ALF 2013 this April.

            Regards
            Stig Johnsen
            ALF 2013
            ", userid);

            var client = new RestClient();
            client.BaseUrl = "https://api.mailgun.net/v2";
            client.Authenticator = new HttpBasicAuthenticator("api", "key-95iv2azanw509luzmo3a7eepdkfy3uu8");

            var request = new RestRequest();
            request.AddParameter("domain", "app13455.mailgun.org", ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", "Another Lindyhop Festival <*****@*****.**>");
            request.AddParameter("to", mail);
            request.AddParameter("subject", "Payment and competitions for ALF");
            request.AddParameter("text", message);
            request.Method = Method.POST;
            var response = client.Execute(request);
        }
Example #11
0
 public object GetIssueStatus(int key, int deploymentProjectId)
 {
     RestRequest request = new RestRequest { Resource = "deploy/issue-status/{key}/{deploymentProjectId} ", Method = Method.GET };
     request.AddParameter("key", key, ParameterType.UrlSegment);
     request.AddParameter("deploymentProjectId", key, ParameterType.UrlSegment);
     return Client.Execute<object>(request);
 }
        public static void MoveObjects(IRestClient restClient, long[] pFileIds, long pFromId, long pToId,
            TransactionResponse transaction = null)
        {
            if (pFileIds == null || pFileIds.Length == 0)
                return;

            var createRequest = new RestRequest("api/rest/object/move/{id}", Method.POST);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);

            for (var i = 0; i < pFileIds.Length; i++)
            {
                if (i == 0)
                    createRequest.AddUrlSegment("id", pFileIds[i].ToString("D"));
                else
                    createRequest.AddParameter("id", pFileIds[i].ToString("D"));
            }
            createRequest.AddParameter("target", pToId.ToString("D"));
            createRequest.AddParameter("parameters", createRequest.JsonSerializer.Serialize(new
            {
                parent = new[] {pFromId.ToString("D")},
                inheritAcl = true
            }));

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);
        }
        /// <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);
        }
        public StripeObject CreateRecipient(string name, string type,
            ICreditCard card = null, IBankAccount bankAccount = null, 
            string taxId = null, string email = null, string description = null)
        {
            Require.Argument("name", name);
            Require.Argument("type", type);

            if (card != null) card.Validate();
            if (bankAccount != null) bankAccount.Validate();

            var request = new RestRequest();
            request.Method = Method.POST;
            request.Resource = "recipients";

            request.AddParameter("name", name);
            request.AddParameter("type", type);

            if (taxId.HasValue()) request.AddParameter("tax_id", taxId);
            if (email.HasValue()) request.AddParameter("email", email);
            if (description.HasValue()) request.AddParameter("description", description);
            if (card != null) card.AddParametersToRequest_Old(request);
            if (bankAccount != null) bankAccount.AddParametersToRequest(request);

            return ExecuteObject(request);
        }
        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 #16
0
        public IEnumerable<ValidationResult> Login(string login, string password)
        {
            Logger.Info(string.Format("Trying to login user {0}", login));

            if (password == null)
            {
                password = string.Empty;
            }

            var client = new RestClient(this.AuthUri);
            // client.Authenticator = new HttpBasicAuthenticator(username, password);

            var request = new RestRequest("api/user/login", Method.GET);
            request.AddParameter("email", login); // adds to POST or URL querystring based on Method
            request.AddParameter("password", password); // adds to POST or URL querystring based on Method

            // or automatically deserialize result
            // return content type is sniffed but can be explicitly set via RestClient.AddHandler();
            IRestResponse<LoginResponseModel> response = client.Execute<LoginResponseModel>(request);
            if (!string.IsNullOrEmpty(response.Data.UserName))
            {
                Settings.Default.UserName = response.Data.UserName;
                Settings.Default.Token = response.Data.Token;
                return Enumerable.Empty<ValidationResult>();
            }

            return new List<ValidationResult> {new ValidationResult("Login or password is wrong")};
        }
Example #17
0
        public static string URClusterSignIn(string clusterID, string clusterName, string username, string password)
        {
            if (clusterID == "" || clusterName == "" || username == "" || password == "")
                return "insufficient input";

            // TODO(MN): revisit this logic. 
            // what will be the accepted ways to define a cluster name?
            string clusterUrl = clusterName;
            if (!clusterName.Contains( "https" ) )
                clusterUrl = "https://" + clusterName + ".ufora.com:443";

            string answ = UforaSession.Instance.AddCluster(clusterID, clusterUrl);
            if (answ != clusterID)
                return answ;

            var request = new RestRequest("/login", Method.POST);
            request.AddParameter("username", username);
            request.AddParameter("password", password);
            request.RequestFormat = DataFormat.Json;

            UforaCluster aCluster = UforaSession.Instance.GetCluster(clusterID);
            aCluster.SetUser(username);

            ClusterResponse response = aCluster.RunRequest(request);
            if (response.success)
                return "connected to " + clusterUrl;
            else
                return response.message;
        }
Example #18
0
        //get player's ships
        private static List<Ship> GetShips(long playerId)
        {
            string appKey = @"11749197d5c8ca823ed4beb2199922aa";
            string url = @"https://api.worldofwarships.com/wows/ships/stats/";
            string.Format(url, appKey);
            var restClient = new RestClient(url);
            var request = new RestRequest(Method.GET);
            request.AddParameter("application_id", appKey);
            request.AddParameter("account_id", playerId.ToString());
            request.AddParameter("in_garage", "1");
            var response = restClient.Execute(request);
            string tmp = response.Content;

            //File.WriteAllText(@"D:\projects\tmp\ships.json", response.Content);

            List<Ship> results = new List<Ship>();
            //String tmp = File.ReadAllText(@"D:\projects\tmp\zigships.json");

            JObject d = JObject.Parse(tmp);
            //Dictionary<string, JObject> ships = d["data"].First()[0].First().ToObject<Dictionary<string, JObject>>();

            foreach (var s in d["data"].First().First())
            {
                try
                {
                    Ship ship = new Ship();  ;// = GetShip(s["ship_id"].ToString());
                    //ship.Experience = Convert.ToInt32(s["pvp"]["xp"].ToString());
                    results.Add(ship);
                }
                catch
                { }
            }
            return results;
        }
Example #19
0
 private IRestResponse ExecuteWebRequest(string apiLocation, string filename)
 {
     var request = new RestRequest(apiLocation, Method.GET);
     request.AddParameter("user", UserInfo.Username, ParameterType.UrlSegment);
     request.AddParameter("file", EncodeFilename(filename), ParameterType.UrlSegment);
     return _apiClient.Execute(request);
 }
Example #20
0
        /// <summary>
        /// Uploads a file, if the request fails this overload will delete the note record
        /// </summary>
        /// <param name="module">Notes</param>
        /// <param name="id">Record ID</param>
        /// <param name="filePath">Path to file on local disk</param>
        /// <param name="deleteOnFailure">Bool: deletes record if upload fails</param>
        /// <returns>Bool</returns>
        public bool UploadFile(string module, string id, string filePath, bool deleteOnFailure)
        {
            var request = new RestRequest("{module}/{id}/file/filename", Method.POST);
            request.AddUrlSegment("module", module);
            request.AddUrlSegment("id", id);

            request.AddParameter("format", "sugar-html-json");
            request.AddParameter("delete_if_fails", deleteOnFailure);

            if (deleteOnFailure)
            {
                request.AddParameter("oauth_token", Token);
            }

            if (!File.Exists(filePath))
            {
                //@todo create a SugarFileException class
                throw new SugarException("Can not locate file path. Path attempted = " + filePath);
            }

            request.AddFile("filename", filePath);//?

            FileUploadResponse response = Execute<FileUploadResponse>(request);

            return ! string.IsNullOrEmpty(response.filename.name);
        }
 private RestRequest GetBaseRestRequest(string requestUri)
 {
     var request = new RestRequest(requestUri, Method.GET);
     request.AddParameter("api_key", _apiKey);
     request.AddParameter("pretty", 1);
     return request;
 }
        private void GetToken_Click(object sender, RoutedEventArgs e)
        {
            var client = new RestClient("https://api.home.nest.com/oauth2/access_token");
            var request = new RestRequest(Method.POST);
            request.AddParameter("client_id", TextNestClientId.Text);
            request.AddParameter("code", TextNestPin.Text);
            request.AddParameter("client_secret", PwNestSecret.Password);
            request.AddParameter("grant_type", "authorization_code");
            var response = client.Execute(request);

            JsonDeserializer deserializer = new JsonDeserializer();

            var json = deserializer.Deserialize<Dictionary<string, string>>(response);

            if (json.ContainsKey("access_token"))
            {
                TextNestAccessToken.Text = json["access_token"];
                return;
            }

            if (json.ContainsKey("message"))
            {
                TextNestAccessToken.Text = json["message"];
                return;                
            }

            if (json.ContainsKey("error_description"))
            {
                TextNestAccessToken.Text = json["error_description"];
                return;
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            string customerId = "";
            string apikey = "";
            string address = "address1=2905+premiere+parkway+ste+200&zipcode=30097";
            string url = "https://rapid.peachtreedata.com/api/v1/AddressCleanseGeoCode";
            string fullurl = url + "?CustomerID=" + customerId + "&APIKEY=" + apikey + "&" + address;

            var client = new RestClient(url);
            var request = new RestRequest();

            request.AddParameter("CustomerID", "XXX999");
            request.AddParameter("apikey", "e78f9d79-8710-4753-a099-88c95ea11d0f");
            request.AddParameter("Address1", "2905 premiere parkway");
            request.AddParameter("ZIPCode", "30097");
            request.AddParameter("CompanyName", "peachtree  ");

            var response = client.Execute <AddressCleanseGeoCodeResponse>(request);

            Console.WriteLine("Primary Address:   {0}", response.Data.PrimaryAddress);
            Console.WriteLine("Secondary Address: {0}", response.Data.SecondaryAddress);
            Console.WriteLine("ZIP Code:          {0}", response.Data.Zip10);
            Console.WriteLine("Latitude:          {0}", response.Data.Latitude);
            Console.WriteLine("Longitude:         {0}", response.Data.Longitude);
            Console.WriteLine("Geo Assignment:    {0}", response.Data.AssignmentLevel);
            Console.WriteLine("Status:            {0}", response.Data.StatusMessage);
            Console.WriteLine("\n\nPress any key to continue...");
            Console.ReadKey();
        }
Example #24
0
 void IObjectValidation.AddParametersToRequest(RestRequest request)
 {
     request.AddParameter("bank_account[currency]", Currency);
     request.AddParameter("bank_account[country]", Country);
     request.AddParameter("bank_account[routing_number]", RoutingNumber);
     request.AddParameter("bank_account[account_number]", AccountNumber);
 }
Example #25
0
        private void SignIn(String username, String password)
        {
            bool isValid = this.ValidateForm(username, password);
            if (isValid)
            {
                SignInButton.IsEnabled = false;
                var client = new RestClient("https://securebox.io/");
                var request = new RestRequest("api-token-auth/", Method.POST);
                request.AddParameter("username", username); // adds to POST or URL querystring based on Method
                request.AddParameter("password", password); // adds to POST or URL querystring based on Method
                IRestResponse<MyToken> response = client.Execute<MyToken>(request);

                try
                {
                    var token = response.Data.Token;
                    if (token != null)
                    {
                        this.RedirectToMainForm();
                    }
                    else
                    {
                        ValidationMessage.Content = "Invalid login";
                        SignInButton.IsEnabled = true;
                    }
                    //MessageBox.Show(token.ToString());
                    //System.Windows.MessageBox.Show(token.ToString());
                }
                catch
                {
                    var content = response;
                    System.Windows.MessageBox.Show("Error");
                }
            }
        }
Example #26
0
 public IRestRequest GetTicket(string apiKey)
 {
     var restRequest = new RestRequest("1.0/rest");
     restRequest.AddParameter("action", "get_ticket");
     restRequest.AddParameter("api_key", apiKey);
     return restRequest;
 }
Example #27
0
        //TO:DO:  Error Handling

        /// <summary>
        /// Handles the Sending of the reset password email.
        /// </summary>
        /// <param name="user">UserReset Model</param>
        /// <returns>client.Execute(request)</returns>
        public async Task<IRestResponse> SendResetMessage()
        {
            string subjectParam = "Reset Password";
            
            RestClient client = new RestClient();
            client.BaseUrl = "https://api.mailgun.net/v2";
            client.Authenticator =
                    new HttpBasicAuthenticator("api",
                                               mailGunApiKey);
            RestRequest request = new RestRequest();
            request.AddParameter("domain",
                                 mailGunDomain, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", mailGunEmail);
            request.AddParameter("to", EmailAddress);
            request.AddParameter("subject", subjectParam);
            request.AddParameter("html", await ResetMessage());

            //upload token to parse
            await SendKey();


            request.Method = Method.POST;
            return client.Execute(request);
        }
Example #28
0
        //Not working.
        public Book BookIdForIsbn(String isbn, out Boolean success)
        {
            try
            {
                _restClient.BaseUrl = ApiBaseUrl;
                _restClient.Authenticator = PublicMethods();

                var request = new RestRequest("book/isbn", Method.GET);
                request.AddParameter("isbn", isbn);
                request.AddParameter("key", _apiKey);
                request.AddParameter("format", "xml");
                //_restClient.AddHandler();
                var response = _restClient.Execute<Book>(request);

                if (response.ResponseStatus == ResponseStatus.Error)
                {
                    success = false;
                    return null;
                }
                else
                {
                    success = true;
                    return response.Data;
                }

            }
            catch (Exception ex)
            {
                success = false;
                return null;

            }
        }
Example #29
0
        public IRestResponse<MarketplaceSearchResponse> Search(string query = "", int start = 0, int count = 10)
        {
            var client = new MarketplaceClient(BaseUrl);

            var request = new RestRequest("/", Method.GET);
            request.AddHeader("Accept", "*/*");
            request.AddHeader("Accept-Enclding", "gzip,deflat,sdch");
            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("HOST", "steamcommunity.com");

            request.AddCookie("__ngDebug", "false");
            request.AddCookie("Steam_Language", "english");
            request.AddCookie("sessionid", "MTE3OTk1OTgyNQ");
            request.AddCookie("steamCC_67_167_177_70", "US");
            request.AddCookie("__utma", "268881843.805413192.1378770011.1382167972.1382171160.10");
            request.AddCookie("__utmb", "268881843.1.10.1382171160");
            request.AddCookie("__utmc", "268881843");
            request.AddCookie("__utmz", "268881843.1382171160.10.6.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)");
            //request.AddCookie("timezoneOffset", "-14400,0");

            //request.Timeout = 5*1000;
            request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");

            request.AddParameter("query", query, ParameterType.GetOrPost);
            request.AddParameter("start", start, ParameterType.GetOrPost);
            request.AddParameter("count", count, ParameterType.GetOrPost);

            var response = client.Get<MarketplaceSearchResponse>(request);

            return response;
        }
Example #30
0
        public override async Task <CheckResult> CheckPerson(string token, string vSearch_string)
        {
            var request = new RestSharp.RestRequest($"api/sp_v0/sp_covid_gp_check_person", RestSharp.Method.POST, RestSharp.DataFormat.Json);

            request.AddHeader("Authorization", $"Bearer {token}");
            request.AddParameter("vSearch_string", vSearch_string);
            await Task.Delay(500);

            logger.LogInformation($"eHealth: Checking person {vSearch_string.GetSHA256Hash()}");
            var response = await client.ExecuteAsync(request);

            if (!response.IsSuccessful)
            {
                return(null);
            }
            var jArr = JArray.Parse(response.Content);

            if (jArr.Count == 0)
            {
                return(null);
            }
            var json = JsonConvert.SerializeObject(jArr[0]);

            var ret = JsonConvert.DeserializeObject <Model.EZdravie.Payload.CheckResult[]>(json, deserializeSettings);

            if (ret.Length == 0)
            {
                return(null);
            }
            return(ret[0]);
        }
Example #31
0
        private void RefreshToken()
        {
            RestSharp.RestRequest r = new RestSharp.RestRequest("oauth/v2/token", Method.POST);
            r.AlwaysMultipartFormData = true;
            r.AddParameter("client_id", clientId, ParameterType.GetOrPost);
            r.AddParameter("client_secret", clientSecret, ParameterType.GetOrPost);
            r.AddParameter("refresh_token", refreshToken, ParameterType.GetOrPost);
            r.AddParameter("grant_type", "refresh_token", ParameterType.GetOrPost);
            r.RequestFormat = DataFormat.Json;

            var response = restTokenClient.Execute <ZohoTokenInformation>(r);

            ResponseErrorCheck(response);
            Token = response.Data;
            InitializeDataClient();
        }
Example #32
0
        public async Task <List <Bittrex.Transfer> > GetWithdrawalHistoryAsync(string asset = null)
        {
            var endpoint = $"/account/getwithdrawalhistory?apikey={ApiKey.ToManagedString()}&nonce={nonce}";
            var request  = new RestSharp.RestRequest(endpoint, RestSharp.Method.GET);

            if (asset != null)
            {
                request.AddParameter("currency", asset);
            }
            var uri     = client.BuildUri(request);
            var apiSign = SignRequest(uri.AbsoluteUri);

            request.AddHeader("apisign", apiSign);
            var response = await client.ExecuteTaskAsync <Bittrex.ApiResult <List <Bittrex.Transfer> > >(request);

            if (response.IsSuccessful)
            {
                var apiResult = response.Data;
                if (apiResult.success)
                {
                    return(apiResult.result);
                }
                else
                {
                    throw new Exception(apiResult.message);
                }
            }
            else
            {
                throw new Exception(response.ErrorMessage);
            }
        }
Example #33
0
        public async Task <CouchResponse> InsertManually(string path, object content)
        {
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);

            request.AddParameter("application/json", content, ParameterType.RequestBody);
            request.Resource = path;
            return(await http.ExecuteAsync(request));
        }
Example #34
0
        public HtmlDocument GetBuildingPage(string id)
        {
            var request = new RestSharp.RestRequest(buildUrl, Method.GET);

            request.AddParameter("id", id);
            request.AddParameter("category", "1");

            IRestResponse response = client.Execute(request);

            if (response.IsSuccessful)
            {
                var content = response.Content; // raw content as string
                var doc     = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);
                return(doc);
            }
            return(null);
        }
Example #35
0
        internal IEnumerable <ISearchResult> GetSimilarSearchResults(string id, int pageSize, int pageIndex, out int?totalNumberOfResults)
        {
            // Console.WriteLine("Searching Freesound for \"{0}\" (page index {1} sized {2}", query, pageIndex, pageSize);

            //var proxy = System.Net.WebRequest.GetSystemWebProxy(); // Unused!
            var request = new RestSharp.RestRequest(Settings.Default.SimilarSearchPath, RestSharp.Method.GET);

            request.AddParameter("page", pageIndex + 1);
            request.AddParameter("page_size", pageSize);
            request.AddParameter("fields", "id,url,name,tags,images,description,license,duration,username,previews,num_downloads,avg_rating,num_ratings");

            request.AddParameter("target", id);
            request.AddParameter("token", Freesound.ApiKey.Key);

            request.RequestFormat = DataFormat.Json;

            return(ExecuteSearch(request, out totalNumberOfResults));
        }
Example #36
0
        public HtmlDocument PostTrainUnit(string unit, string building, string count)
        {
            var request = new RestSharp.RestRequest(buildUrl, Method.POST);

            request.AddParameter("id", "{" + building + "}");
            request.AddParameter("ft", "t1");
            request.AddParameter("{" + unit + "}", "{" + count + "}");

            IRestResponse response = client.Execute(request);

            if (response.IsSuccessful)
            {
                var content = response.Content; // raw content as string
                var doc     = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);
                return(doc);
            }
            return(null);
        }
Example #37
0
        /// <summary>
        /// http://docs.couchdb.org/en/2.2.0/api/database/common.html#post--db
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public async Task <CouchResponse> UpdateAsync(JToken json)
        {
            Ensure.That(json).IsNotNull();
            Ensure.That(json.GetString("_id")).IsNotNullOrWhiteSpace();

            var request = new RestSharp.RestRequest(RestSharp.Method.POST);

            request.AddParameter("application/json", json, ParameterType.RequestBody);
            return(await client.http.ExecuteAsync(request));
        }
Example #38
0
        public HtmlDocument GetBuilding(string map, string building, string captcha)
        {
            var request = new RestSharp.RestRequest(villageUrl, Method.GET);

            request.AddParameter("?%D0%B0", "{" + building + "}");
            request.AddParameter("id", "{" + map + "}");
            request.AddParameter("c", "{" + captcha + "}");

            IRestResponse response = client.Execute(request);

            if (response.IsSuccessful)
            {
                var content = response.Content; // raw content as string
                var doc     = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);
                return(doc);
            }
            return(null);
        }
Example #39
0
 //for Invoice
 #region List Specific Invoice
 public string ListSpecificInvoice(string token, string id)
 {
     this.access_token = token;
     this.ID           = id;
     try
     {
         string url    = "https://api.aligncommerce.com/invoice/retrieve/id";
         var    client = new RestSharp.RestClient();
         client.BaseUrl       = url;
         client.Authenticator = new HttpBasicAuthenticator(user, pass);
         var request = new RestSharp.RestRequest();
         request.Method = Method.GET;
         request.AddParameter("access_token", this.access_token);
         request.AddParameter("id", this.ID);
         //  request.Resource = json;
         IRestResponse response = client.Execute(request);
         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() == "500")
         {
             var js  = new JavaScriptSerializer();
             var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
             this.Message = dic["error_message"];
             return(Message);
         }
         else
         {
             var js  = new JavaScriptSerializer();
             var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
             this.Message = dic["error_message"];
             return(Message);
         }
     }
     catch (Exception e)
     {
         return(e.ToString());
     }
 }
        /// <summary>
        /// http://docs.couchdb.org/en/2.0.0/api/database/bulk-api.html#api-db-all-docs
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public async Task <CouchResponse> BulkInsertAsync(dynamic[] documentsObjects)
        {
            var request = new RestSharp.RestRequest("_bulk_docs", RestSharp.Method.POST);

            FindBuilder expression = new FindBuilder();

            expression.Docs(documentsObjects);

            request.AddParameter("application/json", expression.ToString(), ParameterType.RequestBody);
            return(await client.http.ExecuteAsync(request));
        }
Example #41
0
        /// <summary>
        /// Fire a webhook event
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <param name="trackingGuid"></param>
        /// <param name="attempt"></param>
        /// <returns></returns>
        public async Task FireWebhookEvent(Sheev.Common.Models.WebhookResponse request, IBaseContextModel context, Guid trackingGuid, int attempt = 0)
        {
            try
            {
                // Start Log Here
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"iring webhook event: {request.Scope}. Attempt: {attempt + 1}/3 Note if webhook is not found in the receiver then this is either a clapback or the system is not subscribed to this scope.", "Trigger Webhook Event", LT319.Common.Utilities.Constants.TrackingStatus.Active, context, trackingGuid);

                // Rest Client
                var restClient = new RestSharp.RestClient(context.ApiUrlSettings.Value.Skyhook_URL);

                // Building the request and setting endpoint target
                RestSharp.RestRequest req = new RestSharp.RestRequest("/v2/Event", RestSharp.Method.POST);

                // Serializing the body
                var bodyJSON = JsonConvert.SerializeObject(request);

                // Added the application/json header
                req.AddParameter("application/json", bodyJSON, ParameterType.RequestBody);

                // Execute the request
                var resp = (RestSharp.RestResponse)restClient.Execute(req);

                // Check the response
                if (!resp.IsSuccessful)
                {
                    // Log something here
                    IG2000.Data.Utilities.ErrorLogger.Report(JsonConvert.SerializeObject(resp), "WebhookModel.FireWebhookEvent()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);

                    if (resp.ErrorException != null)
                    {
                        IG2000.Data.Utilities.Logging.LogTrackingEvent($"Webhook was unable to be sent! Reason: {resp.ErrorException.Message}", $"Status Code: {Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError}", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                    }

                    // Retry
                    if (attempt < 3)
                    {
                        await FireWebhookEvent(request, context, trackingGuid, attempt + 1);
                    }
                }

                // End Log Here
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"Webhook {request.Scope} successfully fired on attempt: {attempt + 1}.", "Trigger Webhook Event", LT319.Common.Utilities.Constants.TrackingStatus.Active, context, trackingGuid);
            }
            catch (Exception ex)
            {
                IG2000.Data.Utilities.Logging.LogTrackingEvent($"See logs for additional details", "Failed", LT319.Common.Utilities.Constants.TrackingStatus.Error, context, trackingGuid);
                IG2000.Data.Utilities.ErrorLogger.Report(ex.Message, "WebhookModel.FireWebhookEvent()", context, trackingGuid, System.Diagnostics.EventLogEntryType.Error);

                throw new HttpResponseException()
                      {
                          StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = ex.Message
                      };
            }
        }
Example #42
0
        protected virtual RestRequest CreateRequest(string action, Method method = Method.POST, object body = null)
        {
            var request = new RestRequest(action, method)
            {
                RequestFormat = DataFormat.Json
            };
            var includeBody = new[] { Method.POST, Method.PUT, Method.PATCH }.Contains(method);

            foreach (var header in headers)
            {
                request.AddHeader(header.Key, header.Value);
            }

            request.AddHeader("Authorization", "Bearer " + apiToken);
            request.AddHeader("User-Agent", GetUserAgent());

            request.Timeout = timeout;

            if (body != null)
            {
                if (IsAnonymousType(body.GetType()))
                {
                    if (includeBody)
                    {
                        request.AddJsonBody(body);
                    }
                    else
                    {
                        foreach (var prop in body.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                        {
                            request.AddQueryParameter(prop.Name, prop.GetValue(body).ToString());
                        }
                    }
                }
                else
                {
                    if (includeBody)
                    {
                        request.AddParameter("application/json", JsonConvert.SerializeObject(body), ParameterType.RequestBody);
                    }
                    else
                    {
                        body = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(body));

                        foreach (var prop in JObject.FromObject(body).Properties())
                        {
                            request.AddQueryParameter(prop.Name, prop.Value.ToString());
                        }
                    }
                }
            }

            return(request);
        }
Example #43
0
        async Task UploadScansToServer()
        {
            //      if (IsOnline)
            if (true)
            {
                IsBusy = true;
                await Task.Delay(2000);

                var db = DependencyService.Get <IDatabaseConnection>().DbConnection();

                //                var db = new SQLiteConnection(dbPath);
                db.CreateTable <Scan>();
                var        list   = db.Query <Scan>("Select * from [Scan]");
                HttpClient client = new HttpClient();
                foreach (var s in list)
                {
                    // Connect and Upload to Cloud Server
                    var newscan = new Scan()
                    {
                        ScanTime     = s.ScanTime,
                        StationId    = s.StationId,
                        Item         = s.Item,
                        OperatorId   = s.OperatorId,
                        ActionItemId = s.ActionItemId,
                        Latitude     = s.Latitude,
                        Longitude    = s.Longitude,
                        //    Action = s.Action,
                        //    ActionIsLocked = false,
                        //    Operator = s.Operator,
                        //    Station = s.Station,
                        Processed = false
                    };

                    var rc         = new RestSharp.RestClient();
                    var jsonstring = JsonConvert.SerializeObject(newscan, Formatting.None);
                    var request    = new RestSharp.RestRequest("https://assettrackingwebapi.azurewebsites.net/scan/savescan", RestSharp.Method.POST);
                    request.AddParameter("application/json; charset=utf-8", jsonstring, ParameterType.RequestBody);
                    request.RequestFormat = DataFormat.Json;
                    var response = rc.Execute(request);


                    //var jsonstring = JsonConvert.SerializeObject(newscan, Formatting.None);
                    //var buffer = System.Text.Encoding.UTF8.GetBytes(jsonstring);
                    //var byteContent = new ByteArrayContent(buffer);
                    //byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    //HttpResponseMessage result = await client.PostAsync("https://assettrackingwebapi.azurewebsites.net/scan/savescan", byteContent);
                    //// Mark Scan as Posted
                }
                db.Query <Scan>("Delete from [scan]");
                db.Close();
                IsBusy = false;
            }
        }
Example #44
0
        public static TEntity PostWithStandard <TEntity>(string url, IDictionary <string, string> parameters, string certificatePath, string certificatePassword) where TEntity : class, new()
        {
            var client  = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(Method.POST);

            if (parameters != null)
            {
                foreach (var para in parameters)
                {
                    request.AddParameter(para.Key, para.Value);
                }
            }

#if !DEBUG
            if (client.BaseUrl.Scheme.ToLower() == "https")
            {
                if (string.IsNullOrEmpty(certificatePath))
                {
                    throw new ArgumentNullException("certificatePath");
                }

                client.ClientCertificates = new X509CertificateCollection
                {
                    new X509Certificate(certificatePath, certificatePassword)
                };
                ServicePointManager.ServerCertificateValidationCallback = (sender1, certificate, chain, sslPolicyErrors) =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                    {
                        return(true);
                    }

                    return(false);
                };
            }
#endif
            var response = client.Execute <TEntity>(request);

            //检测异常
            if (response.ErrorException != null)
            {
                //throw new Exception(response.ErrorException.Message + "\r\nUrl:" + url + "\r\n\r\nErrorContent:" + response.Content);//如果有异常就把它抛出来//如果有异常就把它抛出来
                //return JsonHelper.FromJsonTo<TEntity>(response.Content);  //这种方式日期反序列化出错了

                //重要记录,错误叫,“没有找到默认构造函数”,其实就是json数据里多了一个图片地址,json格式没有问题,所以就反序列化到对象继续返回。
                var s = JsonConvert.DeserializeObject <TEntity>(response.Content);
                return(s);
            }
            else
            {
                return(response.Data);
            }
        }
        private T DoSend <T>(RSharp.Method method, object body)
        {
            _request.AddParameter(
                "application/json",
                Newtonsoft.Json.JsonConvert.SerializeObject(body),
                ParameterType.RequestBody);

            var response = _restClient.Execute(_request, method);

            if (response.IsSuccessful)
            {
                return(Deserialize <T>(response));
            }

            if (response.ErrorException != null)
            {
                throw RestClientFactory.CreateErrorException(_restClient, response);
            }

            throw RestClientFactory.CreateFailedException(_restClient, response);
        }
        /// <summary>
        /// http://docs.couchdb.org/en/2.1.2/api/database/common.html#post--db
        /// </summary>
        /// <param name="json"></param>
        /// <param name="batchMode">http://docs.couchdb.org/en/2.1.2/api/database/common.html#batch-mode-writes</param>
        /// <returns></returns>
        public async Task <CouchResponse> InsertAsync(JToken json, bool batchMode = false)
        {
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);

            if (batchMode)
            {
                request.AddQueryParameter("batch", "ok");
            }

            request.AddParameter("application/json", json, ParameterType.RequestBody);
            return(await client.http.ExecuteAsync(request));
        }
Example #47
0
 /// <summary>
 /// Modify the request to add teh calls to the FM scripts.
 /// </summary>
 /// <param name="requestToModify">The request to modify.</param>
 /// <param name="scripts">The List of FMscript objects to add.</param>
 /// <returns>RestSharp.RestRequest.</returns>
 private RestSharp.RestRequest BuildScriptsURLpart(RestSharp.RestRequest requestToModify, List <FMSscript> scripts)
 {
     if (scripts != null && scripts.Count >= 1)
     {
         foreach (FMSscript s in scripts)
         {
             if (s.type == ScriptTypes.after)
             {
                 requestToModify.AddParameter("script", s.name, ParameterType.QueryString);
                 if (s.parameter != null)
                 {
                     requestToModify.AddParameter("script.param", s.parameter, ParameterType.QueryString);
                 }
             }
             else if (s.type == ScriptTypes.before)
             {
                 requestToModify.AddParameter("script,prerequest", s.name, ParameterType.QueryString);
                 if (s.parameter != null)
                 {
                     requestToModify.AddParameter("script.prerequest.param", s.parameter, ParameterType.QueryString);
                 }
             }
             else if (s.type == ScriptTypes.beforeSort)
             {
                 requestToModify.AddParameter("script,presort", s.name, ParameterType.QueryString);
                 if (s.parameter != null)
                 {
                     requestToModify.AddParameter("script.presort.param", s.parameter, ParameterType.QueryString);
                 }
             }
         }
     }
     return(requestToModify);
 }
Example #48
0
        //Method For Getting Access Token
        public string GetAccessToken()
        {
            string url    = "https://api.aligncommerce.com/oauth/access_token";
            var    client = new RestSharp.RestClient();

            client.BaseUrl       = url;
            client.Authenticator = new HttpBasicAuthenticator(user, pass);
            var request = new RestSharp.RestRequest();

            request.AddParameter("grant_type", this.credentials);
            request.AddParameter("client_id", this.client_id);
            request.AddParameter("client_secret", this.client_secret);
            request.AddParameter("scope", this.scope);
            request.AddParameter("state", this.state);

            IRestResponse response = client.Execute(request);

            //Deserialize Responce Object
            if (response.StatusCode.ToString() == "200")
            {
                var js  = new JavaScriptSerializer();
                var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                this.access_token = dic["access_token"];
                return(dic["access_token"]);
            }
            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() == "500")
            {
                var js  = new JavaScriptSerializer();
                var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                this.Message = dic["error_message"];
                return(Message);
            }
            else
            {
                var js  = new JavaScriptSerializer();
                var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                this.Message = dic["access_token"];
                return(Message);
            }
        }
Example #49
0
        public string UpdateProduct(string access_token
                                    , string updateid
                                    , string product_name
                                    , string product_discription
                                    , double product_price
                                    , double product_shipping
                                    , string product_sku)
        {
            this.access_token        = access_token;
            this.product_name        = product_name;
            this.product_sku         = product_sku;
            this.product_price       = product_price;
            this.product_shipping    = product_shipping;
            this.product_description = product_discription;
            this.ID = updateid;

            try
            {
                string url    = "https://api.aligncommerce.com/products/id";
                var    client = new RestSharp.RestClient();
                client.BaseUrl       = url;
                client.Authenticator = new HttpBasicAuthenticator(user, pass);
                var request = new RestSharp.RestRequest();
                request.Method = Method.PUT;
                //  request.Resource = json;
                request.AddParameter("access_token", this.access_token);
                request.AddParameter("product_id", this.ID);
                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);

                IRestResponse response = client.Execute(request);
                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() == "500")
                {
                    var js  = new JavaScriptSerializer();
                    var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                    this.Message = dic["error_message"];
                    return(Message);
                }
                else
                {
                    var js  = new JavaScriptSerializer();
                    var dic = js.Deserialize <Dictionary <string, string> >(response.Content);
                    this.Message = dic["error_message"];
                    return(Message);
                }
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
        public List <ERPObject> ListObjects(DocType docType, FetchListOption listOption = null)
        {
            loginIfNeeded();

            listOption = listOption ?? new FetchListOption();
            RestRequest request = new RestRequest($"/api/resource/{docType}", Method.GET);

            var filters = listOption.Filters ?? new List <ERPFilter>();

            if (filters.Any())
            {
                var filter_val = SerializeUtils.ToString(filters.Select(toFilterObject).ToList());
                request.AddParameter("filters", filter_val);
            }

            var included_fields = listOption.IncludedFields ?? new List <string>();

            if (included_fields.Any())
            {
                var filter_val = SerializeUtils.ToString(included_fields.ToList());
                request.AddParameter("fields", filter_val);
            }

            if (listOption.PageSize > 0)
            {
                request.AddParameter("limit_page_length", listOption.PageSize);
            }

            if (listOption.PageStartIndex > 0)
            {
                request.AddParameter("limit_start", listOption.PageStartIndex);
            }

            var response = this.client.Execute(request);

            assertResponseIsOK(response);

            return(parseManyObjects(docType, response));
        }
Example #51
0
        public static TEntity PostWithApplicationJson <TEntity>(string url, IDictionary <string, string> parameters, string certificatePath, string certificatePassword) where TEntity : class, new()
        {
            var client  = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(Method.POST);

            request.RequestFormat = DataFormat.Json;
            var jsonBody = new StringBuilder("{");

            if (parameters != null)
            {
                foreach (var para in parameters)
                {
                    jsonBody.AppendFormat("\"{0}\":\"{1}\",", para.Key, HttpUtility.HtmlEncode(para.Value));
                }
            }

            jsonBody.Remove(jsonBody.Length - 1, 1).Append("}");
            request.AddParameter(request.JsonSerializer.ContentType, jsonBody, ParameterType.RequestBody);

#if !DEBUG
            if (client.BaseUrl.Scheme.ToLower() == "https")
            {
                if (string.IsNullOrEmpty(certificatePath))
                {
                    throw new ArgumentNullException("certificatePath");
                }

                client.ClientCertificates = new X509CertificateCollection();
                client.ClientCertificates.Add(new X509Certificate(certificatePath, certificatePassword));
                ServicePointManager.ServerCertificateValidationCallback = (sender1, certificate, chain, sslPolicyErrors) =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                    {
                        return(true);
                    }

                    return(false);
                };
            }
#endif

            var response = client.Execute <TEntity>(request);

            //检测异常
            if (response.ErrorException != null)
            {
                throw new Exception(response.ErrorException.Message + "\r\nUrl:" + url + "\r\n\r\nErrorContent:" + response.Content);//如果有异常就把它抛出来
            }

            return(response.Data);
        }
        protected override void AsyncLogMessage(object row, Sheev.Common.BaseModels.IBaseContextModel context)
        {
            TrackingDetailLog logRequest = ((TrackingDetailLog)row);

            if (logRequest.TrackingHeaderLogRequest == null)
            {
                try
                {
                    var restClient            = new RestSharp.RestClient(context.ApiUrlSettings.Value.LT319_URL);
                    RestSharp.RestRequest req = new RestSharp.RestRequest("/v2/Detail", RestSharp.Method.POST);
                    var bodyJSON = JsonConvert.SerializeObject(logRequest.TrackingDetailLogRequest);
                    req.AddHeader("Authorization", $"Bearer {logRequest.Token}");
                    req.AddParameter("application/json", bodyJSON, ParameterType.RequestBody);
                    var resp = (RestSharp.RestResponse)restClient.Execute(req);

                    if (resp.StatusCode != HttpStatusCode.NoContent)
                    {
                        Utilities.ErrorLogger.Report(JsonConvert.SerializeObject(resp), "ThreadedLogger_TrackingDetail.AsyncLogMessage()", context, logRequest.TrackingDetailLogRequest.TrackingGuid, System.Diagnostics.EventLogEntryType.Error);

                        //  throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = resp.ErrorException.Message };
                    }
                }
                catch (Exception ex)
                {
                    Utilities.ErrorLogger.Report(JsonConvert.SerializeObject(ex), "ThreadedLogger_TrackingDetail.AsyncLogMessage()", context, logRequest.TrackingDetailLogRequest.TrackingGuid, System.Diagnostics.EventLogEntryType.Error);
                }
            }
            else
            {
                try
                {
                    var restClient            = new RestSharp.RestClient(context.ApiUrlSettings.Value.LT319_URL);
                    RestSharp.RestRequest req = new RestSharp.RestRequest("/v2/Header", RestSharp.Method.POST);
                    var bodyJSON = JsonConvert.SerializeObject(logRequest.TrackingHeaderLogRequest);
                    req.AddHeader("Authorization", $"Bearer {logRequest.Token}");
                    req.AddParameter("application/json", bodyJSON, ParameterType.RequestBody);
                    var resp = (RestSharp.RestResponse)restClient.Execute(req);

                    if (resp.StatusCode != HttpStatusCode.NoContent)
                    {
                        Utilities.ErrorLogger.Report(JsonConvert.SerializeObject(resp), "ThreadedLogger_TrackingHeader.AsyncLogMessage()", context, logRequest.TrackingHeaderLogRequest.TrackingGuid, System.Diagnostics.EventLogEntryType.Error);

                        //  throw new HttpResponseException() { StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError, ReasonPhrase = resp.ErrorException.Message };
                    }
                }
                catch (Exception ex)
                {
                    Utilities.ErrorLogger.Report(JsonConvert.SerializeObject(ex), "ThreadedLogger_TrackingHeader.AsyncLogMessage()", context, logRequest.TrackingHeaderLogRequest.TrackingGuid, System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }
Example #53
0
        public String RestCaller(String org, String dest, String dat)
        {
            IRestResponse response = null;

            //RESTSHARP
            RestSharp.RestClient  client  = new RestSharp.RestClient("http://testapi.vivaair.com/otatest/");
            RestSharp.RestRequest request = new RestSharp.RestRequest
            {
                Resource = "api/values",
                Method   = RestSharp.Method.POST
            };
            request.AddParameter("Origin", org);
            request.AddParameter("Destination", dest);
            request.AddParameter("From", dat);
            response = client.Execute(request);
            var content = response.Content;

            content = content.TrimStart('\"');
            content = content.TrimEnd('\"');
            content = content.Replace("\\", "");

            return(content);
        }
Example #54
0
        public async Task <CouchResponse> InsertDesignDocumentAsync(string name, object json)
        {
            var request = new RestSharp.RestRequest(RestSharp.Method.PUT);

            request.AddParameter("application/json", json, ParameterType.RequestBody);
            request.Resource = "_design/" + name;
            var res = await client.http.ExecuteAsync(request);

            if (res.ErrorException != null)
            {
                throw res.ErrorException;
            }
            return(res);
        }
Example #55
0
        public void SendTroops(TroopsBody model, string villageid)
        {
            var request = new RestSharp.RestRequest("a2b.php", Method.POST);
            var user    = User.Instance;

            user.messages.Add("Wysyłam wojska");
            foreach (PropertyInfo propertyInfo in model.GetType().GetProperties())
            {
                if (propertyInfo.Name.Contains('t') && propertyInfo.Name != "type")
                {
                    if (propertyInfo.GetValue(model) != null)
                    {
                        request.AddParameter(propertyInfo.Name, propertyInfo.GetValue(model));
                    }
                }
            }
            request.AddParameter("x", model.x);    // adds to POST or URL querystring based on Method
            request.AddParameter("y", model.y);    // adds to POST or URL querystring based on Method
            request.AddParameter("c", model.type); // adds to POST or URL querystring based on Method
            request.AddParameter("s1", "ok");      // adds to POST or URL querystring based on Method
            var           xxx      = GetVillagePage(villageid);
            IRestResponse response = client.Execute(request);

            if (response.IsSuccessful)
            {
                var content = response.Content; // raw content as string
                var doc     = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);
                var node   = doc.DocumentNode.SelectSingleNode("//*[@id=\"content\"]/form");
                var _nodes = node.Descendants("input");
                if (_nodes != null)
                {
                    var request2 = new RestSharp.RestRequest("a2b.php", Method.POST);
                    foreach (var el in _nodes)
                    {
                        request2.AddParameter(el.GetAttributeValue("name", ""), el.GetAttributeValue("value", "")); // adds to POST or URL querystring based on Method
                    }
                    user.messages.Add("Wysyłam wojska..");
                    IRestResponse response2 = client.Execute(request2);
                    if (response.IsSuccessful)
                    {
                        user.messages.Add("Wysyłano wojska");
                        content = response.Content; // raw content as string
                        doc     = new HtmlAgilityPack.HtmlDocument();
                        doc.LoadHtml(content);
                        GetVillagePage();
                    }
                }
            }
        }
Example #56
0
        public List <Game> getGamesByName(string name)
        {
            RestSharp.RestRequest request = new RestSharp.RestRequest("api/games", RestSharp.Method.GET);
            request.AddParameter("api_key", apiKey, RestSharp.ParameterType.QueryString);
            request.AddParameter("format", "json", RestSharp.ParameterType.QueryString);
            request.AddParameter("filter", "name:" + name, RestSharp.ParameterType.QueryString);

            request.AddParameter("limit", "20", RestSharp.ParameterType.QueryString);
            request.AddParameter("sort", "original_release_date:desc", RestSharp.ParameterType.QueryString);

            RestSharp.IRestResponse response = client.Execute(request);

            dynamic results = JsonConvert.DeserializeObject <dynamic>(response.Content);

            JObject obj  = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(response.Content);
            JArray  jarr = (JArray)obj["results"];

            List <Game> games = new List <Game>();

            foreach (var item in jarr)
            {
                string Id = Convert.ToString(item["id"]);

                if (!Id.Equals("67742") && !Id.Equals("59938") && !Id.Equals("71095") && !Id.Equals("70513") && !Id.Equals("65713") && !Id.Equals("66679"))
                {
                    Game game = new Game()
                    {
                        Name  = Convert.ToString(item["name"]),
                        Image = Convert.ToString(item["image"]["original_url"])
                    };

                    games.Add(game);
                }
            }

            return(games);
        }
Example #57
0
        public async Task <RestResponse> GetEndpoint(RestRequest apiRequest)
        {
            RestResponse returnedValue = new RestResponse();

            RestClient client = new RestClient();

            client.BaseUrl = new Uri(apiAddress);

            RestSharp.RestRequest request = new RestSharp.RestRequest(apiRequest.Endpoint);

            request.AddHeader("Authentication", authentication);

            request.Method = (apiRequest.Method == "POST") ? Method.POST : Method.GET;

            if (apiRequest.Parameters != null)
            {
                foreach (RestParameter parameter in apiRequest.Parameters)
                {
                    request.AddParameter
                    (
                        parameter.Name,
                        parameter.Value
                    );
                }
            }

            var cancellationTokenSource = new CancellationTokenSource();

            var response = await client.ExecuteTaskAsync
                           (
                request,
                cancellationTokenSource.Token
                           );

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                returnedValue.Status   = true;
                returnedValue.Response = response.Content;
            }
            else
            {
                returnedValue.Status    = false;
                returnedValue.Message   = $"{response.StatusDescription} {response.ErrorMessage}";
                returnedValue.Response  = response.Content;
                returnedValue.ErrorCode = response.StatusCode.ToString();
            }

            return(returnedValue);
        }
        public ERPObject UpdateObject(DocType docType, string name, ERPObject obj)
        {
            loginIfNeeded();

            RestRequest request   = new RestRequest($"/api/resource/{docType}/{name}", Method.PUT);
            var         args_text = SerializeUtils.ToString(obj.Data);

            request.AddParameter("data", args_text);

            var response = this.client.Execute(request);

            assertResponseIsOK(response);

            return(parseOneObject(docType, response));
        }
Example #59
0
        public static List <Repo> GetRepos()
        {
            RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();
            //Get base url
            var client  = new RestClient(" https://api.github.com");
            var request = new RestSharp.RestRequest("search/repositories", Method.GET);

            //Add headers
            request.AddHeader("User-Agent", "kimlan1510");
            request.AddHeader("Authorization", "token " + EnvironmentVariable.AccessToken);

            //Add params
            var param = HttpUtility.UrlDecode("user:kimlan1510+stars:>=1");

            request.AddParameter("q", param);
            request.AddParameter("per_page", "3");

            //Execute
            IRestResponse response     = client.Execute(request);
            JObject       jsonResponse = JsonConvert.DeserializeObject <JObject>(response.Content);
            var           repoList     = JsonConvert.DeserializeObject <List <Repo> >(jsonResponse["items"].ToString());

            return(repoList);
        }
Example #60
-1
    public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
      Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {

      var request = new RestRequest(Path, Method);

      UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);

      // add default header, if any
      foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap)
        request.AddHeader(defaultHeader.Key, defaultHeader.Value);

      // add header parameter, if any
      foreach(KeyValuePair<string, string> param in HeaderParams)
        request.AddHeader(param.Key, param.Value);
     
      // add query parameter, if any
      foreach(KeyValuePair<string, string> param in QueryParams)
        request.AddQueryParameter(param.Key, param.Value);

      // add form parameter, if any
      foreach(KeyValuePair<string, string> param in FormParams)
        request.AddParameter(param.Key, param.Value);

      // add file parameter, if any
      foreach(KeyValuePair<string, string> param in FileParams)
        request.AddFile(param.Key, param.Value);

      if (PostBody != null) {
        request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter
      }

      return (Object) await restClient.ExecuteTaskAsync(request);

    }