public void GetById_ShouldReturnStatusOk()
        {
            var ingredientRequest = new RestRequest("Ingredient", Method.POST);
            var ingredient = new IngredientModel
            {
                Name = "ingredient1",
                Price = 123
            };
            ingredientRequest.AddJsonBody(ingredient);

            var ingredientResponse = Client.Execute(ingredientRequest);

            Assert.That(ingredientResponse, Is.Not.Null);
            Assert.That(ingredientResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created));
            var returnedIngredientModel = _jsonDeserializer.Deserialize<IngredientModel>(ingredientResponse);

            var pizzaRequest = new RestRequest("Pizza", Method.POST);
            var pizza = new PizzaModel
            {
                Name = "pizza1",
                Price = 123,
                Toppings = new List<IngredientModel> { returnedIngredientModel }
            };
            pizzaRequest.AddJsonBody(pizza);

            var pizzaResponse = Client.Execute(pizzaRequest);

            Assert.That(pizzaResponse, Is.Not.Null);
            Assert.That(pizzaResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created));
            var returnedPizzaModel = _jsonDeserializer.Deserialize<PizzaModel>(pizzaResponse);

            var request = new RestRequest(ResourceName, Method.POST);
            var order = new OrderModel
            {
                CreationDate = DateTimeOffset.Now,
                Price = 123,
                Address = "address",
                Pizzas = new List<PizzaModel> { returnedPizzaModel }
            };
            request.AddJsonBody(order);

            var response = Client.Execute(request);

            Assert.That(response, Is.Not.Null);
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created));

            var orderModel = _jsonDeserializer.Deserialize<OrderModel>(response);

            var getRequest = new RestRequest(ResourceNameWithParameter, Method.GET);
            getRequest.AddUrlSegment("id", orderModel.Id.ToString());
            var getResponse = Client.Execute(getRequest);

            Assert.That(getResponse, Is.Not.Null);
            Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            var returnedOrderModel = _jsonDeserializer.Deserialize<IngredientModel>(getResponse);
            Assert.That(returnedOrderModel, Is.Not.Null);
            Assert.That(returnedOrderModel.Id, Is.EqualTo(orderModel.Id));
        }
示例#2
0
 public async Task <IRestResponse <RegisterResponse> > SuccessfulRegistration(string email, string password)
 {
     if (email != null && password != null)
     {
         RegisterRequest req = new RegisterRequest();
         req.email             = email;
         req.password          = password;
         request.RequestFormat = DataFormat.Json;
         request.AddJsonBody(req);
     }
     return(await _client.ExecutePostAsync <RegisterResponse>(request));
 }
示例#3
0
        public User GetUserByUserId(string userId)
        {
            var request = new RestSharp.RestRequest(AccountAPI.SearchUsers)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };
            var user = new User {
                UserName = userId
            };

            request.AddJsonBody(new
            {
                Key   = "UserId",
                Value = userId
            });

            IRestResponse response = _client.Post(request);
            var           json     = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content);

            if (json.success)
            {
                var users = JsonConvert.DeserializeObject <List <User> >(json.result.ToString());
                if (users.Any())
                {
                    return(users.First());
                }
                return(null);
            }
            else
            {
                return(null);
            }
        }
示例#4
0
        public Dictionary <int?, string> GetPositions(List <int?> items)
        {
            RestClient client = new RestClient(path)
            {
                Encoding = new UTF8Encoding(false)
            };

            client.AddDefaultHeader("Accept", "application/json");
            client.AddDefaultHeader("Accept-Encoding", "gzip, deflate");
            client.AddDefaultHeader("Content-Type", "application/json");

            var request = new RestSharp.RestRequest(resourcesPosition)
            {
                Method        = Method.POST,
                RequestFormat = DataFormat.Json
            };

            request.AddJsonBody(items);

            var response = client.Execute(request);

            if (!response.IsSuccessful)
            {
                return(null);
            }

            var dictionary = JsonConvert.DeserializeObject <Dictionary <int?, string> >(response.Content);

            return(dictionary);
        }
        static void Main(string[] args)
        {
            while (true) {
            string choice;
            string id;
            int status;

            var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
            var request = new RestRequest("relays", Method.GET);
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

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

            Console.WriteLine(RelayCollection.Content);
            Console.WriteLine("What id do you want to change?");
            id = Console.ReadLine();
            Console.WriteLine("We will change id:{0}\nwhat do you want to do?\n0 = off 1 = on", id);
            choice = Console.ReadLine();
            if(choice == "1")
            {
                status = 1;
            }
            else
            {
                status = 0;
            }

            var putRequest = new RestRequest("relays/" + id, Method.PUT);
            putRequest.AddJsonBody(new { status = status });
            client.Execute(putRequest);

            }
        }
示例#6
0
        public List <User> SerachUsers(string keyword)
        {
            var request = new RestSharp.RestRequest(AccountAPI.SearchUsers)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };

            request.AddJsonBody(new
            {
                Key   = "UserName",
                Value = keyword
            });

            IRestResponse response = _client.Post(request);
            var           json     = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content);

            if (json.success)
            {
                var users = JsonConvert.DeserializeObject <List <User> >(json.result.ToString());
                return(users);
            }
            else
            {
                return(new List <User>());
            }
        }
示例#7
0
        public SignUpResult SignUp(SignUpViewModel signUpViewModel)
        {
            var request = new RestSharp.RestRequest(AccountAPI.SignUp)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };

            request.AddJsonBody(signUpViewModel);
            var           user     = new User();
            IRestResponse response = _client.Post(request);
            var           json     = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content);

            if (json.success)
            {
                user = new User()
                {
                    UserName     = signUpViewModel.UserName,
                    PasswordHash = signUpViewModel.Password,
                    Email        = signUpViewModel.Email,
                    UserId       = signUpViewModel.UserId
                };
            }

            return(new SignUpResult()
            {
                Succeed = json.success,
                ErrorMessage = json.error,
                user = user
            });
        }
示例#8
0
        public bool Update(INode node)
        {
            RestClient client = new RestClient(path)
            {
                Encoding = new UTF8Encoding(false)
            };

            client.AddDefaultHeader("Accept", "application/json");
            client.AddDefaultHeader("Accept-Encoding", "gzip, deflate");
            client.AddDefaultHeader("Content-Type", "application/json");

            var request = new RestSharp.RestRequest(resources)
            {
                Method        = Method.PUT,
                RequestFormat = DataFormat.Json
            };

            request.AddJsonBody(node);

            var response = client.Execute(request);

            if (!response.IsSuccessful)
            {
                return(false);
            }

            return(true);
        }
示例#9
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 object HttpRequest(string url, HttpMethod method, object body = null)
        {
            RestSharp.RestRequest req = string.IsNullOrEmpty(url) ? new RestRequest() : new RestRequest(new Uri(url));
            RestSharp.Method      meth;
            switch (method)
            {
            case HttpMethod.GET:
                meth = Method.GET;
                break;

            case HttpMethod.POST:
                meth = Method.POST;
                if (body != null)
                {
                    req.AddJsonBody(jsonConvert.JsonSerialize(body));
                }
                break;

            case HttpMethod.PUT:
                meth = Method.PUT;
                break;

            case HttpMethod.DELETE:
                meth = Method.DELETE;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(method), method, null);
            }

            client = !string.IsNullOrEmpty(BaseUrl) ? new RestClient(BaseUrl) : new RestClient();
            var response = client.Execute(req, meth);

            return(response.Content);
        }
示例#11
0
        public List <User> GetAllFollowingUsersByUserId(string userId)
        {
            //callAPI get all following users;

            var followingUsers = new List <User>();

            var request = new RestSharp.RestRequest(AccountAPI.Followee)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };

            request.AddJsonBody(new
            {
                UserId = userId
            });

            IRestResponse response = _client.Post(request);
            var           json     = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content);

            if (json.success)
            {
                JArray js   = JArray.Parse(json.result.ToString());
                var    list = js.Select(x => x["Followee"].ToString()).Select(x => GetUserByUserId(x)).ToList();
                followingUsers = list;
            }

            return(followingUsers);
        }
 public IRestResponse Send(string text)
 {
     var client = new RestClient(_slackApiUrl);
     var request = new RestRequest(Method.POST);
     request.AddJsonBody(new payload {text = text});
     return client.Execute(request);
 }
示例#13
0
        public static async Task<IRestResponse<ResultValue>> SaveWidget(string widgetString)
        {
            var request = new RestRequest(SystemResource.SaveWidgetRequest, Method.POST);
            request.AddJsonBody(widgetString);

            return await Client.ExecutePostTaskAsync<ResultValue>(request);
        }
        private void crearDetallePlantilla(Plantilla pPlantilla)
        {
            List<int> ids = (List<int>)HttpContext.Current.Session["IdsPreguntaPlantilla"];
            List<Pregunta> preguntas = new List<Pregunta>();

            foreach (int valor in ids) {

                RestClient client = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
                RestRequest request = new RestRequest("Preguntas/{id}", Method.GET);

                request.AddUrlSegment("id", Convert.ToString(valor));

                var response = client.Execute(request);

                string json = response.Content;

                Pregunta nuevaPregunta = JsonConvert.DeserializeObject<Pregunta>(json);

                preguntas.Add(nuevaPregunta);

            }

            RestClient client2 = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));

            foreach (Pregunta item in preguntas) {

                RestRequest request2 = new RestRequest("PlantillaDetalle/", Method.POST);
                PlantillaDetalle x = new PlantillaDetalle(0, pPlantilla, item);

                request2.AddJsonBody(x);

                var response = client2.Execute(request2);
                Console.WriteLine(response.Content.ToString());
            }
        }
示例#15
0
        private void deleteBookButton_Click(object sender, EventArgs e)
        {
            booksGridView.Rows[booksGridView.SelectedCells[0].RowIndex].Selected = true;
            int index = Int32.Parse(booksGridView.SelectedRows[0].Cells[0].Value.ToString());

            var request = new rs.RestRequest(rs.Method.DELETE);

            request.RequestFormat = rs.DataFormat.Json;

            request.AddJsonBody(new
            {
                u  = textBox1.Text,
                p  = textBox2.Text,
                id = index
            });

            var response = userClient.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                MessageBox.Show(response.StatusDescription);
                return;
            }

            MessageBox.Show(string.Format("The book {0} deleted", booksGridView.SelectedRows[0].Cells[1].Value.ToString()));
            refreshBooks();
        }
示例#16
0
        public void Flush(Workspace workspace)
        {
            ConsoleEx.Info($"Running sink: {this.GetType().Name}");

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

            var restClient = new RestClient(serviceUri);
            var response = restClient.Post(request);
            if(response.StatusCode == HttpStatusCode.OK)
            {
                ConsoleEx.Ok("Workspace analysis report published.");
                var locationHeader = response.Headers.FirstOrDefault(h=> h.Name == "Location");
                if (locationHeader != null)
                {
                    string workspaceLocation = locationHeader.Value.ToString().ToLower();
                    ConsoleEx.Ok($"Visit {workspaceLocation}");
                }
            }
            else
            {
                ConsoleEx.Error($"Workspace not published to target sink.");
                ConsoleEx.Error($"Status: {response.StatusCode}, Response: {response.Content}");
            }
        }
示例#17
0
        public object SendRequest(string path, Method method, object jsonRequest)
        {
            RestClient client = new RestClient(APSController);
            

            RestRequest request = new RestRequest(path, method);

            //let's ignore the certificate error from the APSC
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            request.AddHeader("APS-Token", APSToken);

            request.AddJsonBody(jsonRequest);

            var result = client.Execute(request);

            dynamic jsonResponse = Newtonsoft.Json.Linq.JObject.Parse(result.Content);

            if(result.StatusCode.GetHashCode() >= 300)
                throw new Exception(result.ErrorMessage);
            if (result.StatusCode == HttpStatusCode.OK)
                return jsonResponse;

            return null;
        }
示例#18
0
        /// <summary>
        /// Get All User's posts except user
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IPagedList <PostDto> GetPosts(string userId, int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var request = new RestSharp.RestRequest(PostAPI.GetRecentPost)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };
            var limits = (pageIndex + 1) * pageSize;

            request.AddJsonBody(new { UserId = userId, Limit = limits });

            IRestResponse response = _client.Post(request);
            var           json     = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content);


            if (json.success)
            {
                List <PostDto> items = new List <PostDto>();
                items = JsonConvert.DeserializeObject <List <PostDto> >(json.result.ToString());
                return(new PagedList <PostDto>(items, pageIndex, pageSize));
            }
            else
            {
                return(null);
            }
        }
示例#19
0
        private void updateBookSubmit_Click(object sender, EventArgs e)
        {
            var request = new rs.RestRequest(rs.Method.PUT);

            request.RequestFormat = rs.DataFormat.Json;

            request.AddJsonBody(new
            {
                id     = newBookId.Text,
                name   = newbookname.Text,
                author = newbookauthor.Text,
                year   = newbookyear.Text,
                price  = newbookprice.Text,
                u      = textBox1.Text,
                p      = textBox2.Text
            });

            var response = userClient.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                MessageBox.Show(response.StatusDescription);
                return;
            }

            MessageBox.Show(string.Format("The book {0} updated", newbookname.Text));
            updateBookSubmit.Enabled  = false;
            tabControl1.SelectedIndex = 2;
            refreshBooks();
        }
        public void Should_update_users_status()
        {
            var url = string.Format("https://{0}/v2", EndpointHost);

            var client = new RestClient(url);
            var request = new RestRequest("/user/" + RestSharp.Contrib.HttpUtility.UrlEncode(Email), Method.PUT);
            request.AddQueryParameter("auth_token", Token);

            var user = new HipChatUser()
            {
                name = "",
                email = Email,
                presence = new Presence()
                {
                    status = "blah",
                    show = "away"
                },
                mention_name = ""
            };

            request.AddJsonBody(user);

            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-type", "application/json");
            request.AddHeader("Accept", "application/json");
            var response = client.Execute(request);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
示例#21
0
        private void button2_Click(object sender, EventArgs e)
        {
            var request = new rs.RestRequest(rs.Method.POST);

            request.RequestFormat = rs.DataFormat.Json;

            request.AddJsonBody(new
            {
                u        = textBox1.Text,
                p        = textBox2.Text,
                username = textBox3.Text,
                password = textBox4.Text
            });

            var response = userClient.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                MessageBox.Show(response.StatusDescription);
                return;
            }

            MessageBox.Show(string.Format("The user {0} added", textBox3.Text));
            tabControl1.SelectedIndex = 0;
            refreshUsers();
        }
        public void GetById_ShouldReturnStatusCodeOk()
        {
            var postRequest = new RestRequest(ResourceName, Method.POST);
            var expectedIngredient = new IngredientModel
            {
                Name = "ingredient1",
                Price = 123
            };
            postRequest.AddJsonBody(expectedIngredient);

            var postResponse = Client.Execute(postRequest);
            Assert.That(postResponse, Is.Not.Null);
            Assert.That(postResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created));

            var ingredientModel = _jsonDeserializer.Deserialize<IngredientModel>(postResponse);

            var getRequest = new RestRequest(ResourceNameWithParameter, Method.GET);
            getRequest.AddUrlSegment("id", ingredientModel.Id.ToString());
            var getResponse = Client.Execute(getRequest);

            Assert.That(getResponse, Is.Not.Null);
            Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            var returnedIngredientModel = _jsonDeserializer.Deserialize<IngredientModel>(getResponse);
            Assert.That(returnedIngredientModel, Is.Not.Null);
            Assert.That(returnedIngredientModel.Id, Is.EqualTo(ingredientModel.Id));
        }
        public virtual dynamic Post(AuthRequestModel model)
        {
            var request = new RestRequest(Method.POST);
            if (string.IsNullOrEmpty(model.client_id))
            {
                model.client_id = ClientId;
            }
            if (string.IsNullOrEmpty(model.grant_type) && GrantTypeDetection)
            {
                model.grant_type = DetectGrantType(model);
            }
            request.AddJsonBody(model);

            var response = restClient.Execute<AuthorizationResponse>(request);
            if (response.ErrorException == null && response.StatusCode.Equals(HttpStatusCode.OK))
            {
                return Json(response.Data);
            }
            else
            {
                var responseProxy = new HttpResponseMessage(response.StatusCode);
                var mimeType = new System.Net.Mime.ContentType(response.ContentType);
                responseProxy.Content = new StringContent(response.Content, System.Text.Encoding.GetEncoding(mimeType.CharSet), mimeType.MediaType);
                return responseProxy;
            }
        }
        /// <summary>
        /// Sends the formatted messages.
        /// </summary>
        /// <param name="messages">The messages to send.</param>
        /// <param name="succeededAction">A success action that should be called for successfully sent messages.</param>
        /// <param name="failedAction">A failure action that should be called when a message send operation fails.</param>
        public void Send(IEnumerable<ProviderNotificationMessage> messages, 
            Action<ProviderNotificationMessage> succeededAction, 
            Action<ProviderNotificationMessage, Exception> failedAction)
        {
            foreach (var message in messages)
            {
                try
                {
                    // create a new rest request and add the message to the http message body
                    var request = new RestRequest(Method.POST);
                    request.AddJsonBody(message);

                    // send the POST request and call success action if everything went fine
                    _client.Post<ProviderNotificationMessage>(request);
                    if (succeededAction != null)
                        succeededAction(message);
                }
                catch(Exception e)
                {
                    // if the post fails call the failedAction
                    if(failedAction != null)
                        failedAction(message, e);
                }
            }
        }
示例#25
0
        public static RestRequest GetDefaultRestRequest(string paramResource, Method paramMethod, Object paramBody)
        {
            SimpleJson.SimpleJson.CurrentJsonSerializerStrategy = new IgnoreNullValuesJsonSerializerStrategy();

            RestRequest localRequest = new RestRequest
            {
                Resource       = paramResource,
                Method         = paramMethod,
                RequestFormat  = DataFormat.Json,
                JsonSerializer = new NewtonsoftJsonSerializer()
            };

            localRequest.AddHeader("Accept-Encoding", "gzip");

            if (paramBody != null)
            {
                if (paramMethod == Method.GET || paramMethod == Method.DELETE)
                {
                    foreach (var localJProperty in JObject.FromObject(paramBody).Properties().Where(x => !String.IsNullOrEmpty(x.Value.ToString())))
                    {
                        localRequest.AddQueryParameter(localJProperty.Name, localJProperty.Value.ToString());
                    }
                }
                else
                {
                    localRequest.AddJsonBody(paramBody);
                }
            }
            localRequest.Timeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds;
            return(localRequest);
        }
示例#26
0
        public int?Create(INode node)
        {
            RestClient client = new RestClient(path)
            {
                Encoding = new UTF8Encoding(false)
            };

            client.AddDefaultHeader("Accept", "application/json");
            client.AddDefaultHeader("Accept-Encoding", "gzip, deflate");
            client.AddDefaultHeader("Content-Type", "application/json");

            var request = new RestSharp.RestRequest(resources)
            {
                Method        = Method.POST,
                RequestFormat = DataFormat.Json
            };

            request.AddJsonBody(node);

            var response = client.Execute(request);

            if (!response.IsSuccessful)
            {
                return(null);
            }

            var id = JsonConvert.DeserializeObject <int?>(response.Content);

            return(id);
        }
示例#27
0
        public async Task <ResponseData> XoaKho(int idKho)
        {
            try
            {
                string url     = string.Format("{0}/api/warehouse/delete-warehouse", Config.HOST);
                var    client  = new RestSharp.RestClient(url);
                var    request = new RestSharp.RestRequest(Method.DELETE);
                request.AddHeader("content-type", "application/json; charset=utf-8");
                request.AddHeader("x-access-token", UserResponse.AccessToken);
                request.AddJsonBody(new
                {
                    warehouseId = idKho
                });
                var response = await client.ExecuteTaskAsync(request);

                var responseParse = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(response.Content);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return(new ResponseData()
                    {
                        Status = Config.CODE_OK,
                        Data = null,
                        Message = responseParse["message"]
                    });
                }
                else
                {
                    return(Util.GenerateErrorResponse(response, responseParse));
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
示例#28
0
        private void AddBookButton_Click(object sender, EventArgs e)
        {
            var request = new rs.RestRequest(rs.Method.POST);

            request.RequestFormat = rs.DataFormat.Json;

            request.AddJsonBody(new
            {
                name   = newbookname.Text,
                author = newbookauthor.Text,
                year   = newbookyear.Text,
                price  = newbookprice.Text,
                u      = textBox1.Text,
                p      = textBox2.Text
            });

            var response = userClient.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                MessageBox.Show(response.StatusDescription);
                return;
            }

            MessageBox.Show(string.Format("The book {0} added", newbookname.Text));
        }
示例#29
0
        public OnfleetRecipient CreateRecipient(string name, string phone, string notes, bool skipSMSNotifications,
            bool skipPhoneNumberValidation)
        {
            var recipient = new OnfleetRecipient()
            {
                name = name,
                phone = "+1" + phone,
                notes = notes,
                skipPhoneNumberValidation = skipPhoneNumberValidation,
                skipSMSNotifications = skipSMSNotifications
            };
            var request = new RestRequest("recipients", Method.POST);
            request.JsonSerializer.ContentType = "application/json; charset=utf-8";
            request.AddHeader("Content-Type", "application/json");
            request.AddJsonBody(recipient); 

            var response = _client.Execute(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<OnfleetRecipient>(response.Content);
            }
            else
            {
                _logger.ErrorFormat("Onfleet Create Recipient  : {0}", response.ErrorMessage);
                return null;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var client = new RestClient("http://www.soawebservices.com.br/restservices/test-drive/cdc/pessoafisicasimplificada.ashx");
            var request = new RestRequest(Method.POST);

            // Credenciais de Acesso
            Credenciais credenciais = new Credenciais();
            credenciais.Email = "seu email";
            credenciais.Senha = "sua senha";

            // Requisicao
            Requisicao requisicao = new Requisicao();
            requisicao.Credenciais = credenciais;
            requisicao.Documento = "99999999999";
            requisicao.DataNascimento = "01/01/1900";

            // Adiciona Payload a requisicao
            request.AddJsonBody(requisicao);

            IRestResponse<Simplificada> response = client.Execute<Simplificada>(request);
            Simplificada simplificada = new Simplificada();

            simplificada = response.Data;

            if (simplificada.Status == true)
            {
                this.nome.InnerText = simplificada.Nome;
            }
            else
            {
                this.nome.InnerText = String.Format("Ocorreu um erro: {}", simplificada.Mensagem);
            }
        }
示例#31
0
        public bool ConnectionNode(Node connectionNode, int?nodeIdInGroup)
        {
            RestClient client = new RestClient(path)
            {
                Encoding = new UTF8Encoding(false)
            };

            client.AddDefaultHeader("Accept", "application/json");
            client.AddDefaultHeader("Accept-Encoding", "gzip, deflate");
            client.AddDefaultHeader("Content-Type", "application/json");

            var request = new RestSharp.RestRequest(resources)
            {
                Method        = Method.PUT,
                RequestFormat = DataFormat.Json
            };

            request.AddJsonBody(new Tree(connectionNode, new Models.Groups()
            {
                id = nodeIdInGroup
            }));

            var response = client.Execute(request);

            if (!response.IsSuccessful)
            {
                return(false);
            }

            return(true);
        }
 /// <summary>
 /// Creates an agreement. Sends it out for signatures, and returns the agreementID in the response to the client
 /// </summary>
 /// <param name="info"></param>
 public virtual Task<AgreementCreationResponse> CreateAsync(AgreementCreationInfo info)
 {
     var request = new RestRequest(Method.POST);
     request.JsonSerializer = new Serialization.NewtonSoftSerializer();
     request.Resource = "agreements";
     request.AddJsonBody(info);
     return this.Sdk.ExecuteAsync<AgreementCreationResponse>(request);
 }
 /// <summary>
 /// Sends a reminder for an agreement.
 /// </summary>
 public virtual Task<ReminderCreationResult> SendReminderAsync(ReminderCreationInfo info)
 {
     var request = new RestRequest(Method.POST);
     request.JsonSerializer = new Serialization.NewtonSoftSerializer();
     request.Resource = "reminders";
     request.AddJsonBody(info);
     return this.Sdk.ExecuteAsync<ReminderCreationResult>(request);
 }
 public void Publish(AtlasMetrics metrics)
 {
     var request = new RestRequest(resourceLocation, Method.POST);
     request.AddJsonBody(metrics);
     var response = client.Execute(request);
     if (response.StatusCode != System.Net.HttpStatusCode.OK)
         log.ErrorException("Failed to push metrics. Details: " + response.Content, response.ErrorException);
 }
 private async Task ChangeState(LifxHttpLight light, object payload)
 {
     var client = new RestClient(BaseUrl);
     var request = new RestRequest($"v1/lights/{light.Id}/state");
     request.AddHeader("Authorization", $"Bearer {_token}");
     request.AddJsonBody(payload);
     await client.PutTaskAsync<object>(request);
 }
示例#36
0
 public PictureDto Create(PictureDto picture, string cookie)
 {
     var request = new RestRequest();
     request.AddJsonBody(picture);
     var response = _client.Post<PictureDto>(request);
     request.AddHeader(Headers.SessionId, cookie);
     return response.Data;
 }
        private async Task <bool> SendData()
        {
            var ds = new DataSet();

            try
            {
                var     t1  = new DataTable();
                DataRow row = null;
                t1.Columns.Add("CountID");
                t1.Columns.Add("BarCode");
                t1.Columns.Add("ItemDesc");
                t1.Columns.Add("FirstScanQty");
                t1.Columns.Add("SecondScanQty");
                t1.Columns.Add("SecondScanAuth");
                t1.Columns.Add("CountUser");
                t1.Columns.Add("isFirst");
                t1.Columns.Add("Complete");
                t1.Columns.Add("Bin");
                t1.Columns.Add("FinalScanQty");
                InventoryItem iut = currentItem;
                row                   = t1.NewRow();
                row["CountID"]        = countID;
                row["BarCode"]        = iut.BarCode;
                row["FirstScanQty"]   = iut.FirstScanQty;
                row["SecondScanQty"]  = iut.SecondScanQty;
                row["SecondScanAuth"] = iut.SecondScanAuth;
                row["ItemDesc"]       = iut.ItemDesc;
                row["CountUser"]      = iut.CountUser;
                row["isFirst"]        = iut.isFirst;
                row["Complete"]       = iut.Complete;
                row["Bin"]            = iut.Bin;
                row["FinalScanQty"]   = iut.FinalQTY;
                t1.Rows.Add(row);
                ds.Tables.Add(t1);
            }
            catch (Exception)
            {
                return(false);
            }
            string myds = Newtonsoft.Json.JsonConvert.SerializeObject(ds);

            RestSharp.RestClient client = new RestSharp.RestClient();
            client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath);
            {
                var Request = new RestSharp.RestRequest("Inventory", RestSharp.Method.POST);
                Request.RequestFormat = RestSharp.DataFormat.Json;
                Request.AddJsonBody(myds);
                var cancellationTokenSource = new CancellationTokenSource();
                var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                if (res.IsSuccessful && res.Content.Contains("Complete"))
                {
                    return(true);
                }
            }
            return(false);
        }
示例#38
0
 public UserDto Update(UserDto userDto, string cookie)
 {
     var request = new RestRequest();
     request.AddJsonBody(userDto);
     request.AddParameter("Application/Json", userDto, ParameterType.RequestBody);
     request.AddHeader(Headers.SessionId, cookie);
     var response = _client.Put<UserDto>(request);
     return response.Data;
 }
 public async Task<AddACHNodeResponse> AddACHNodeAsync(AddACHNodeRequest msg)
 {
     var req = new RestRequest("node/add", Method.POST);
     var body = new
     {
         login = new
         {
             oauth_key = msg.OAuth.Key
         },
         user = new
         {
             fingerprint = msg.Fingerprint
         },
         node = new
         {
             type = "ACH-US",
             info = new
             {
                 nickname = msg.Nickname,
                 name_on_account = msg.NameOnAccount,
                 account_num = msg.AccountNumber,
                 routing_num = msg.RoutingNumber,
                 type = msg.AccountType.ToString().ToUpper(),
                 @class = msg.AccountClass.ToString().ToUpper()
             },
             extra = new
             {
                 supp_id = msg.LocalId
             }
         }
     };
     req.AddJsonBody(body);
     var resp = await this._api.ExecuteTaskAsync(req);
     RaiseOnAfterRequest(body, req, resp);
     dynamic data = SimpleJson.DeserializeObject(resp.Content);
     if (resp.IsHttpOk() && data.success)
     {
         var node = data.nodes[0];
         var info = node.info;
         return new AddACHNodeResponse
         {
             Success = true,
             IsActive = node.is_active,
             Permission = ParseNodePermission(node.allowed),
             Message = ApiHelper.TryGetMessage(data),
             SynapseNodeOId = node._id["$oid"]
         };
     }
     else
     {
         return new AddACHNodeResponse
         {
             Success = false,
             Message = ApiHelper.TryGetError(data)
         };
     }
 }
        private async Task <bool> SaveData()
        {
            var ds = new DataSet();

            try
            {
                var     t1  = new DataTable();
                DataRow row = null;
                t1.Columns.Add("DocNum");
                t1.Columns.Add("ItemBarcode");
                t1.Columns.Add("ScanAccQty");
                t1.Columns.Add("Balance");
                t1.Columns.Add("ScanRejQty");
                t1.Columns.Add("PalletNumber");
                t1.Columns.Add("GRV");
                string         s    = txfSOCode.Text;
                List <DocLine> docs = (await GoodsRecieveingApp.App.Database.GetSpecificDocsAsync(s)).ToList();
                foreach (string str in docs.Select(x => x.ItemDesc).Distinct())
                {
                    foreach (int ints in docs.Select(x => x.PalletNum).Distinct())
                    {
                        row                 = t1.NewRow();
                        row["DocNum"]       = docs.Select(x => x.DocNum).FirstOrDefault();
                        row["ScanAccQty"]   = docs.Where(x => x.PalletNum == ints && x.ItemDesc == str).Sum(x => x.ScanAccQty);
                        row["ScanRejQty"]   = 0;
                        row["ItemBarcode"]  = docs.Where(x => x.PalletNum == ints && x.ItemDesc == str).Select(x => x.ItemBarcode).FirstOrDefault();
                        row["Balance"]      = 0;
                        row["PalletNumber"] = ints;
                        row["GRV"]          = false;
                        t1.Rows.Add(row);
                    }
                }
                ds.Tables.Add(t1);
            }
            catch (Exception)
            {
                return(false);
            }
            string myds = Newtonsoft.Json.JsonConvert.SerializeObject(ds);

            RestSharp.RestClient client = new RestSharp.RestClient();
            client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath);
            {
                var Request = new RestSharp.RestRequest("SaveDocLine", RestSharp.Method.POST);
                Request.RequestFormat = RestSharp.DataFormat.Json;
                Request.AddJsonBody(myds);
                var cancellationTokenSource = new CancellationTokenSource();
                var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                if (res.IsSuccessful && res.Content.Contains("COMPLETE"))
                {
                    return(true);
                }
            }
            return(false);
        }
示例#41
0
        public IRestResponse UpdateBook(BookBinding book)
        {
            var request = new RestRequest("Books/UpdateBook", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddJsonBody(book);

            IRestResponse<List<BookBinding>> response = _client.Execute<List<BookBinding>>(request);

            return response;
        }
示例#42
0
        /// <summary>
        /// Sends HTTP request to the server and gets number of animals inside the oasis
        /// </summary>
        public static int[] GetOasisAnimals(Account acc, Coordinates oasis)
        {
            var    htmlDoc = new HtmlAgilityPack.HtmlDocument();
            string html    = "";

            switch (acc.AccInfo.ServerVersion)
            {
            case Classificator.ServerVersionEnum.T4_4:
                var ajaxToken = DriverHelper.GetJsObj <string>(acc, "ajaxToken");

                var req = new RestSharp.RestRequest
                {
                    Resource = "/ajax.php?cmd=viewTileDetails",
                    Method   = Method.POST,
                };

                req.AddParameter("cmd", "viewTileDetails");
                req.AddParameter("x", oasis.x.ToString());
                req.AddParameter("y", oasis.y.ToString());
                req.AddParameter("ajaxToken", ajaxToken);

                var resString = HttpHelper.SendPostReq(acc, req);

                var root = JsonConvert.DeserializeObject <TileDetailsT4_4>(resString);
                if (root.response.error)
                {
                    throw new Exception("Unable to get T4.4 tile details!\n" + root.response.error);
                }

                html = WebUtility.HtmlDecode(root.response.data.html);
                break;

            case Classificator.ServerVersionEnum.T4_5:
                var bearerToken = DriverHelper.GetBearerToken(acc);

                var reqMapInfo = new RestSharp.RestRequest
                {
                    Resource      = "/api/v1/ajax/viewTileDetails",
                    Method        = Method.POST,
                    RequestFormat = DataFormat.Json
                };
                reqMapInfo.AddHeader("authorization", $"Bearer {bearerToken}");
                reqMapInfo.AddHeader("content-type", "application/json; charset=UTF-8");
                reqMapInfo.AddJsonBody(oasis);

                var tileDetails = HttpHelper.SendPostReq(acc, reqMapInfo);

                var tile = JsonConvert.DeserializeObject <TileDetailsT4_5>(tileDetails);
                html = WebUtility.HtmlDecode(tile.html);
                break;
            }

            htmlDoc.LoadHtml(html);
            return(TroopsParser.GetOasisAnimals(htmlDoc));
        }
示例#43
0
        public RegisterExternalOutput RegisterExternal(RegisterExternalInput input)
        {
            RestHTTP http = new RestHTTP();

            RestSharp.RestRequest req = new RestSharp.RestRequest("api/accounts/RegisterExternal", RestSharp.Method.POST);
            req.AddJsonBody(input);

            var response = http.HttpPost <RegisterExternalOutput>(req);

            return(response);
        }
 public void Send(string text)
 {
     var client = new RestClient(_slackApiUrl);
     var request = new RestRequest(Method.POST);
     request.AddJsonBody(new payload {text = text});
     var response = client.Execute(request);
     if (response.StatusCode != HttpStatusCode.OK)
     {
         throw new HttpException((int) response.StatusCode, "Error Sending To Slack. " + response.ErrorMessage);
     }
 }
 public Graph PostGraph(GraphRequest graph)
 {
     var client = new RestClient(_baseUrl);
     var request = new RestRequest{Resource = _postGraphEndpoint};
     request.AddJsonBody(graph);
     request.AddHeader("Authentication", _apiKey);
     request.Method = Method.POST;
     var response = client.Execute(request);
     var graphResponse = JsonConvert.DeserializeObject<GraphResponse>(response.Content);
     return graphResponse.graph;
 }
示例#46
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);
        }
示例#47
0
        public static void Main()
        {
            var client = new RestClient("http://localhost:1144/");

            var request = new RestRequest("api/DistanceCalculator", Method.POST);
            var points = new Points() { Start = new Point() { X = 9, Y = 7 }, End = new Point() { X = 3, Y = 2 } };
            request.AddJsonBody(points);

            var response = client.Execute(request);
            Console.WriteLine(response.Content);
        }
示例#48
0
 public UserDto Create(UserDto userDto, string password)
 {
     var request = new RestRequest(Method.POST);
     request.RequestFormat = DataFormat.Json;
     request.AddJsonBody(userDto);
     request.AddHeader("password", password);
     var response = _client.Post<UserDto>(request);
     if (response.StatusCode == HttpStatusCode.Conflict)
     {
         throw new Exception("Пользователь с указанными данными уже существует");
     }
     return response.Data;
 }
示例#49
0
        private void QueueLog(LogMessage message)
        {
            _loggingEvents.Enqueue(message);

            var client = new RestClient(postUrl);
            var request = new RestRequest();
            request.Resource = "api/Logger";
            request.AddJsonBody(message);

            client.ExecuteAsPost(request, "POST");

            var temp = 1;
        }
示例#50
0
        private static dynamic Execute(Options opts, Method method, object body)
        {
            RestClient client = new RestClient(opts.Url)
            {
                Authenticator = new HttpBasicAuthenticator(opts.User, opts.Pass)
            };

            var request = new RestSharp.RestRequest("", method);

            if (method != Method.GET)
            {
                request.AddQueryParameter("action", opts.Action);
            }

            if (body != null && method != Method.GET)
            {
                request.AddJsonBody(body);
            }

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

            if (response.ErrorException != null)
            {
                Console.WriteLine("Exception | {0}", opts.Url);
                Console.WriteLine(response.ErrorException.Message);
                throw new Exception();
            }

            var statusCodes = new List <HttpStatusCode>
            {
                HttpStatusCode.OK,
                HttpStatusCode.Created,
                HttpStatusCode.Accepted,
                HttpStatusCode.NoContent
            };

            if (response.StatusCode == HttpStatusCode.UnprocessableEntity &&
                opts.Action != "upgrade")
            {
                return(response.Data);
            }

            if (statusCodes.Contains(response.StatusCode) == false)
            {
                Console.WriteLine("Invalid StatusCode | {0}", opts.Url);
                Console.WriteLine(response.StatusDescription);
                throw new Exception();
            }

            return(response.Data);
        }
        private async Task <bool> ResetItem(DocLine doc)
        {
            var ds = new DataSet();

            try
            {
                var     t1  = new DataTable();
                DataRow row = null;
                t1.Columns.Add("DocNum");
                t1.Columns.Add("ItemBarcode");
                t1.Columns.Add("ScanAccQty");
                t1.Columns.Add("Balance");
                t1.Columns.Add("ScanRejQty");
                t1.Columns.Add("PalletNumber");
                t1.Columns.Add("GRV");
                row                 = t1.NewRow();
                row["DocNum"]       = doc.DocNum;
                row["ItemBarcode"]  = doc.ItemBarcode;
                row["ScanAccQty"]   = 0;
                row["Balance"]      = 0;
                row["ScanRejQty"]   = 0;
                row["PalletNumber"] = doc.PalletNum;
                row["GRV"]          = false;
                t1.Rows.Add(row);
                ds.Tables.Add(t1);
                string myds = Newtonsoft.Json.JsonConvert.SerializeObject(ds);
                RestSharp.RestClient client = new RestSharp.RestClient();
                client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath);
                {
                    var Request = new RestSharp.RestRequest("SaveDocLine", RestSharp.Method.POST);
                    Request.RequestFormat = RestSharp.DataFormat.Json;
                    Request.AddJsonBody(myds);
                    var cancellationTokenSource = new CancellationTokenSource();
                    var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                    if (res.IsSuccessful && res.Content.Contains("COMPLETE"))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
            }
            return(false);
        }
示例#52
0
        public async Task <ResponseData> ThemNhanVien(NhanVien nhanVien)
        {
            try
            {
                string url      = string.Format("{0}/api/employee/add-new-employee", Config.HOST);
                var    client   = new RestSharp.RestClient(url);
                var    request  = new RestSharp.RestRequest(Method.POST);
                var    gioiTinh = false;
                request.AddHeader("content-type", "application/json; charset=utf-8");
                request.AddHeader("x-access-token", UserResponse.AccessToken);
                if (nhanVien.GioiTinh == true)
                {
                    gioiTinh = true;
                }
                request.AddJsonBody(new
                {
                    ma         = nhanVien.Ma,
                    ten        = nhanVien.Ten,
                    gioiTinh   = gioiTinh,
                    ngaySinh   = nhanVien.NgaySinh,
                    diaChi     = nhanVien.DiaChi,
                    CMND       = nhanVien.CMND,
                    SDT        = nhanVien.SDT,
                    email      = nhanVien.Email,
                    ngayVaoLam = nhanVien.NgayVaoLam,
                });
                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"];
                    int employeeId = data["employeeId"];
                    return(new ResponseData()
                    {
                        Status = Config.CODE_OK,
                        Data = employeeId,
                        Message = responseParse["message"]
                    });
                }
                else
                {
                    return(Util.GenerateErrorResponse(response, responseParse));
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
示例#53
0
        public User UpdateProfile(User user)
        {
            var request = new RestSharp.RestRequest(AccountAPI.UpdateUser)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };

            request.AddJsonBody(user);

            IRestResponse response = _client.Post(request);
            var           json     = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content);

            return(user);
        }
示例#54
0
        //public static object msg;
        //private static IRestRequest request;
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine(" Welcome to Slacker");
                Console.WriteLine(" Would you like to Submit a post or Read a post?");
                Console.WriteLine(" type Submit or Read");
                //Console.ReadLine();

                var client = new RestClient("http://localhost:51500/");

                Message msg = new Message();
                if (Console.ReadLine() == "Submit")
                {

                    Console.WriteLine("please enter UserName");
                    msg.UserName = Console.ReadLine();
                    Console.WriteLine("please enter Text");
                    msg.Text = Console.ReadLine();
                    msg.DatePosted = DateTime.Now;
                    var request = new RestRequest("api/messages/", Method.POST)
                    { RequestFormat = DataFormat.Json };
                    request.AddJsonBody(msg);
                    var response = client.Execute<Message>(request);
                    break;
                }

                else if (Console.ReadLine() == "Read")
                {

                   // var response = client.Execute<Message>(request);
                    request = new RestRequest("api/messages", Method.GET);
                    var messages = client.Execute<List<Message>>(request).Data;
                    messages.ForEach(x => Console.WriteLine(x));
                    //foreach (var x in messages)
                    //{

                    //    Console.WriteLine(x.UserName);
                    //    Console.WriteLine(x.Text);
                    //    Console.WriteLine(x.DatePosted);
                    //    Console.ReadLine();
                    //}
                }
                Console.ReadLine();

                Console.Clear();
                //
            }
        }
示例#55
0
        public void CheckIn()
        {
            _logger.Information("Sending Payload @ {now}", _clock.Now);

            var request = new RestRequest("/hello");
            var payload = new Payload
            {
                HostName = "hostname",
                Addresses = new[] { "127.0.0.1", "10.0.1.94" },
                Metadata = "cookbook-developer"
            };

            request.AddJsonBody(payload);
            _client.Post<Payload>(request);
        }
示例#56
0
        public JiraUserLogin Login(string login, string password)
        {
            if (string.IsNullOrWhiteSpace(login))
                throw new ArgumentNullException(nameof(login));
            if (string.IsNullOrWhiteSpace(password))
                throw new ArgumentNullException(nameof(password));

            IRestRequest request = new RestRequest("session", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddJsonBody(new JiraUserAuthentication(login, password));
            IRestResponse<JiraUserLogin> response = _restAuthClient.Execute<JiraUserLogin>(request);
            JiraUserLogin jiraUserLogin = response.Data;
            InitializeAuthenticator(jiraUserLogin.Session.Name, jiraUserLogin.Session.Value);
            return jiraUserLogin;
        }
示例#57
0
        private T ExecuteCall <T>(string baseUrl, Resource resource, object payLoad) where T : new()
        {
            if (!Enum.TryParse(resource.Method.ToUpper(), out Method method))
            {
                return(default(T));
            }
            _restClient.BaseUrl = new Uri(baseUrl);
            var request = new RestSharp.RestRequest(resource.Path, method)
            {
                JsonSerializer = new NewtonsoftJsonSerializer()
            };

            request.AddJsonBody(payLoad);
            var response = _restClient.Execute <T>(request);

            return(response.StatusCode == HttpStatusCode.NotFound ? default(T) : response.Data);
        }
示例#58
0
        private static TestUser CreateUser(string adminAccessToken, string adminClientId, string adminClientSecret)
        {
            string[] entitlements = { "spark", "webExSquared", "squaredCallInitiation", "squaredTeamMember", "squaredRoomModeration" };
            string   scopes       = "spark:people_read spark:rooms_read spark:rooms_write spark:memberships_read spark:memberships_write spark:messages_read spark:messages_write spark:teams_write spark:teams_read spark:team_memberships_write spark:team_memberships_read";
            string   userName     = Guid.NewGuid().ToString();
            string   email        = userName + "@squared.example.com";

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

            request.AddHeader("Authorization", "Bearer " + adminAccessToken);
            request.AddJsonBody(new
            {
                clientId      = adminClientId,
                clientSecret  = adminClientSecret,
                emailTemplate = email,
                displayName   = userName,
                password      = "******",
                entitlements  = entitlements,
                authCodeOnly  = "false",
                scopes        = scopes,
            });

            //Cisco Spark platform is dropping support for TLS 1.0 as of March 16, 2018
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
            var client = new RestClient();

            client.BaseUrl = new System.Uri("https://conv-a.wbx2.com/conversation/api/v1/users/test_users_s");

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

            if (response.StatusCode != System.Net.HttpStatusCode.OK &&
                response.StatusCode != System.Net.HttpStatusCode.NoContent)
            {
                Console.WriteLine($"Error: createUser response: {response.StatusCode} {response.StatusDescription}");
                return(null);
            }

            return(new TestUser
            {
                AccessToken = response.Data.token.access_token,
                Email = response.Data.user.email,
                Name = response.Data.user.name,
                OrgId = response.Data.user.orgId,
                PersonId = GetPersonIdFromUserId(response.Data.user.id),
            });
        }
示例#59
0
        public void Send(Employee item)
        {
            var client    = new RestSharp.RestClient("https://gatewayapi.com/rest");
            var apiKey    = "OCC5QlEiXCdMwZ_8QfI4KNCq";
            var apiSecret = "XBgv72Em&.XtbJE(1(wjoL&6dlA#KYY-Zqs8kDzr";

            client.Authenticator = RestSharp.Authenticators
                                   .OAuth1Authenticator.ForRequestToken(apiKey, apiSecret);

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

            request.AddJsonBody(new
            {
                sender     = "BiciCeco",
                recipients = new[] { new { msisdn = item.CardNumber } },
                message    = item.LockUnlockMessage
            });

            var response = client.Execute(request);

            // On 200 OK, parse the list of SMS IDs else print error
            if ((int)response.StatusCode == 200)
            {
                item.HasReceivedConfirmation = false;
                var res = Newtonsoft.Json.Linq.JObject.Parse(response.Content);
                item.MessageId = res["ids"][0].ToString();
                Console.WriteLine(res);

                //handler res;
                //foreach (var i in res["ids"])
                //{
                //    Console.WriteLine(i);
                //}
            }
            else if (response.ResponseStatus == RestSharp.ResponseStatus.Completed)
            {
                Console.WriteLine(response.Content);
                // response.Content;
            }
            else
            {
                Console.WriteLine(response.ErrorMessage);
                //return response.ErrorMessage;
            }
        }
示例#60
0
        public async Task <ResponseData> CapNhatPhieuXuatKho(XuatKho phieuXuat, List <VatTuNhapXuat> listVatTu)
        {
            try
            {
                string url     = string.Format("{0}/api/export/update-receipt", Config.HOST);
                var    client  = new RestSharp.RestClient(url);
                var    request = new RestSharp.RestRequest(Method.PUT);
                request.AddHeader("content-type", "application/json; charset=utf-8");
                request.AddHeader("x-access-token", UserResponse.AccessToken);
                request.AddJsonBody(new
                {
                    Ma          = phieuXuat.Ma,
                    NgayXuat    = phieuXuat.NgayXuat,
                    DiaChi      = phieuXuat.DiaChi,
                    IdNhanVien  = phieuXuat.NhanVien.Id,
                    IdKho       = phieuXuat.Kho.Id,
                    Id          = phieuXuat.Id,
                    GhiChu      = phieuXuat.GhiChu,
                    listProduct = listVatTu.Select(x => new { x.Id, x.SoLuong, x.GhiChu }).ToList()
                });

                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"];
                    var totalPrice = (decimal)data["totalPrice"];
                    return(new ResponseData()
                    {
                        Status = Config.CODE_OK,
                        Data = totalPrice,
                        Message = ""
                    });
                }
                else
                {
                    return(Util.GenerateErrorResponse(response, responseParse));
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }