public ActionResult Index(string projectName, string gitUrl)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Projects/" + projectName + "/" + gitUrl;

            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());

            var response = client.Execute(request);

            return Redirect("/Projects/" + projectName);
        }
        public ActionResult Index(string projectName, string applicationName, string clusterName, Dictionary<string, string> config)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            if (config.ContainsKey("controller"))
                return RedirectToAction("Index");

            var url = hostName + "/api/Clusters/" + projectName + "/" + applicationName + "/" + clusterName;

            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.PUT);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());

            request.AddBody(JsonConvert.SerializeObject(config));

            var response = client.Execute(request);

            if (!string.IsNullOrWhiteSpace(response.ErrorMessage))
            {
                throw response.ErrorException;
            }

            return RedirectToAction("Index");
        }
Пример #3
0
        public void ExecuteAsync <T>(RestSharp.RestRequest request, Action <T, Exception> callBack)
        {
            var client = CreateHttpClient();

            T         result = default(T);
            Exception ex     = null;
            var       h      = client.ExecuteAsync <T>(request, (response, handle) =>
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    if (response.ErrorException != null)
                    {
                        ex = response.ErrorException;
                    }
                    else
                    {
                        result = response.Data;
                    }
                }
                else
                {
                    ex = CreateException(response);
                }
                callBack.Invoke(result, ex);
            });
        }
        private async Task <bool> FetchWH()
        {
            RestSharp.RestClient client = new RestSharp.RestClient();
            string path = "GetWarehouses";

            client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath + path);
            {
                string str     = $"GET?";
                var    Request = new RestSharp.RestRequest();
                Request.Resource = str;
                Request.Method   = RestSharp.Method.GET;
                var cancellationTokenSource = new CancellationTokenSource();
                var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                if (res.Content.ToString().Contains("WHID"))
                {
                    DataSet myds = new DataSet();
                    myds = Newtonsoft.Json.JsonConvert.DeserializeObject <DataSet>(res.Content);
                    foreach (DataRow row in myds.Tables[0].Rows)
                    {
                        WHIDs.Add(row["WHID"].ToString());
                    }
                    txfAccWH.ItemsSource = WHIDs;
                    txfRejWH.ItemsSource = WHIDs;
                    return(true);
                }
            }
            return(false);
        }
Пример #5
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var name    = (String)username.Text;
            var passw   = (String)password.Password;
            var client  = new RestSharp.RestClient("http://" + Config.WebHostIP + ":" + Config.WebHostPort + "/omlate");
            var request = new RestSharp.RestRequest("/Instructor/validateUsernamePassword", RestSharp.Method.POST);

            request.AddParameter("username", name);
            request.AddParameter("password", passw);
            RestSharp.IRestResponse response = client.Execute(request);
            var  content = response.Content;
            bool cont    = Convert.ToBoolean(content);

            if (cont)
            {
                Properties.Settings.Default["username"] = name;
                this.Hide();
                if (swindow == null)
                {
                    swindow = new StartLectureWindow();
                }
                swindow.ShowDialog();
            }
            else
            {
                label.Content = "*Invalid Username or Password!";
                Properties.Settings.Default["username"] = "******";
            }


            Properties.Settings.Default.Save();
            //Toolbar toolbar = new Toolbar();
            //toolbar.Show();
            //this.Close();
        }
Пример #6
0
        public ApiResult <Dictionary <string, DSX.Ticker> > GetTicker2(string symbol)
        {
            var request  = new RestSharp.RestRequest($"{Get24hrPriceTickerEndpoint}/{symbol}", RestSharp.Method.GET);
            var response = ExecutePublicRequest <Dictionary <string, DSX.Ticker> >(request);

            return(response);
        }
Пример #7
0
        public static string UpdateCustomer()
        {
            var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Customer/1047/update")
            {
                Timeout = -1
            };
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);

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

            request.AddParameter("application/json", "{" +
                                 "\"CustomerID\": 1047,\n" +
                                 "\"Email\": \"[email protected]\",\n" +
                                 "\"ShippingAddress\": \"Calle Max Henriquez Ureña No. 6\",\n" +
                                 "\"BillingAddress\": \"Calle 1 No 10, Piantini\",\n" +
                                 "\"FirstName\": \"Emmanuel\",\n" +
                                 "\"LastName\": \"De los Santos\",\n" +
                                 "\"DocumentTypeId\": 2,\n" +
                                 "\"DocNumber\": \"00114918123\",\n" +
                                 "\"PhoneNumber\": \"8096043111\" ,\n" +
                                 "\"Enable\": true  }"
                                 , RestSharp.ParameterType.RequestBody);
            RestSharp.IRestResponse response = client.Execute(request);
            return(response.Content);
        }
Пример #8
0
        string GetWeiXinToken(string originalId)
        {
            int platform = -1;

            Flatform.TryGetValue(originalId, out platform);
            var client  = new RestSharp.RestClient(WeiXinApi);
            var request = new RestSharp.RestRequest("packet/test?platform=" + platform, RestSharp.Method.GET);

            request.AddHeader("access_token", "access_token");
            var response = client.Execute(request);

            if (response.IsSuccessful)
            {
                try
                {
                    var model = JsonConvert.DeserializeObject <WeixinApiResponse>(response.Content);
                    if (model != null)
                    {
                        return(model.access_token);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("GetWeiXinToken", e);
                }
            }
            return(string.Empty);
        }
Пример #9
0
        public bool PushConsumeMessage(string token, dynamic jsonObject)
        {
            var client  = new RestSharp.RestClient(URL_CUSTOM_SEND);
            var request = new RestSharp.RestRequest($"cgi-bin/message/custom/send?access_token={token}", RestSharp.Method.POST);

            request.AddJsonBody(jsonObject);
            var response = client.Execute(request);

            if (response.IsSuccessful)
            {
                try
                {
                    var model = JsonConvert.DeserializeObject <ConsumeMessageResponse>(response.Content);
                    if (model.errcode == 0)
                    {
                        return(true);
                    }
                    Logger.Info(
                        $"PushConsumeMessage Faild errorcode = {model.errcode} errormsg={model.errmsg} body={JsonConvert.SerializeObject(jsonObject)}");
                    return(false);
                }
                catch (Exception e)
                {
                    Logger.Error("PushConsumeMessage Error", e);
                }
            }
            return(false);
        }
Пример #10
0
        public ApiResult <DSX.ExchangeInfo> GetExchangeInfo()
        {
            var request  = new RestSharp.RestRequest(GetExchangeInfoEndpoint, RestSharp.Method.GET);
            var response = ExecutePublicRequest <DSX.ExchangeInfo>(request);

            return(response);
        }
Пример #11
0
        public static void sendException(Exception exception)
        {
            BusinessLogic.ApplicationLog appLog = new BusinessLogic.ApplicationLog();
            appLog.log_date         = DateTime.Now.ToLongTimeString();
            appLog.log_level        = "Error";
            appLog.log_logger       = "REST SERVICE";
            appLog.log_message      = exception.Message;
            appLog.log_machine_name = System.Environment.MachineName;
            appLog.log_user_name    = "WPF TechDashboard";
            appLog.log_call_site    = App.Database.GetApplicationSettings().SDataUrl;  // we're going to use their SDATA root
            appLog.log_thread       = "";
            appLog.log_stacktrace   = exception.StackTrace;

            var client  = new RestSharp.RestClient("http://50.200.65.158/tdwsnew/tdwsnew.svc/i/ApplicationLog"); //hard coded to get it back to us
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);

            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddBody(appLog);

            try
            {
                var response = client.Execute(request) as RestSharp.RestResponse;
            }
            catch (Exception restException)
            {
                // can't do much
            }
        }
Пример #12
0
        public ApiResult <Dictionary <string, DSX.Trade[]> > GetTrades(string symbol, int limit = 150)
        {
            var request  = new RestSharp.RestRequest($"{GetTradesEndpoint}/{symbol}?{limit}", RestSharp.Method.GET);
            var response = ExecutePublicRequest <Dictionary <string, DSX.Trade[]> >(request);

            return(response);
        }
Пример #13
0
        public async Task <DSX.AccountInfo> GetAccountInfoAsync()
        {
            const string endpoint = "tapi/v2/info/account";
            var          request  = new RestSharp.RestRequest(endpoint, RestSharp.Method.POST);
            //request.AddParameter("nonce", nonce);
            //var content = new FormUrlEncodedContent(request.Parameters.Select(x => new KeyValuePair<string, string>(x.Name, x.Value.ToString())));
            //var body = await content.ReadAsStringAsync();
            //request.AddHeader("Key", ApiKey.ToManagedString());
            //request.AddHeader("Sign", SignRequest(body));

            //var response = await client.ExecuteTaskAsync(request);
            var response = await RequestSignedApiAsync(request);

            if (response.IsSuccessful)
            {
                response.Content = response.Content.Replace("\"return\"", "\"result\"");
                var apiResult = client.Deserialize <DSX.ApiResult <DSX.AccountInfo> >(response).Data;
                if (apiResult.success)
                {
                    return(apiResult.result);
                }
                else
                {
                    throw new Exception(apiResult.error);
                }
            }
            else
            {
                throw new Exception(response.ErrorMessage);
            }
        }
        public static async Task <string> GetTwitter([ActivityTrigger] string request,
                                                     ILogger log)
        {
            client = new RestSharp.RestClient("https://we-factsearch-fa.azurewebsites.net");

            RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/api/SearchTwitter", RestSharp.Method.POST);

            restRequest.AddHeader("Content-Type", "application/json");
            Model.RootObject requestData = JsonConvert.DeserializeObject <Model.RootObject>(request);

            string query = string.Empty;

            foreach (var item in requestData.documents[0].keyPhrases)
            {
                query += item + " ";
            }

            Model.SearchQuery searchQuery = new Model.SearchQuery()
            {
                query = query
            };

            restRequest.AddJsonBody(searchQuery);

            var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

            return(response.Content);
        }
Пример #15
0
        public RestSharp.IRestResponse CreateQuestion(CreateQuestionDTO createQuestionDTO)
        {
            JsonObject json = new JsonObject();

            json.Add("professionCode", createQuestionDTO.ProfessionCode);
            json.Add("imageUrl", createQuestionDTO.ImageUrl);
            json.Add("correctAnswerIndex", createQuestionDTO.CorrectAnswerIndex);
            json.Add("content", createQuestionDTO.Question);

            JsonArray answers = new JsonArray();

            foreach (var answer in createQuestionDTO.Answers)
            {
                answers.Add(answer);
            }

            json.Add("answers", answers);

            RestSharp.RestRequest request = new RestSharp.RestRequest("question", RestSharp.Method.POST);
            request.AddJsonBody(json);

            RestSharp.IRestResponse response = Execute(request);

            return(response);
        }
Пример #16
0
		/// <summary>
		/// Ejecuta la llamada al servicio REST con RestSharp
		/// </summary>
		/// <typeparam name="T">Tipo de dato del objeto de retorno</typeparam>
		/// <param name="uri">url del endpoint del servicio rest</param>
		/// <param name="httpMethod">Método HTTP</param>
		/// <param name="objJsonBody">Objeto request body</param>
		/// <returns>Interface IRestResponse<T></returns>
		public static RestSharp.IRestResponse<T> Execute<T>(string uri, RestSharp.Method httpMethod, object objJsonBody = null, string authorizationHeader = null) where T : new()
		{
			var client = new RestSharp.RestClient(uri);
			var request = new RestSharp.RestRequest(httpMethod);

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

			if (!string.IsNullOrEmpty(authorizationHeader))
			{
				request.AddHeader("Authorization", authorizationHeader);
			}

			if (objJsonBody != null)
				request.AddParameter("application/json", objJsonBody, RestSharp.ParameterType.RequestBody);
            //request.AddJsonBody(objJsonBody);
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            RestSharp.IRestResponse<T> response = null;
			for (int i = 0; i < 2; i++)
			{
                response = client.Execute<T>(request);
                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                    break;
                else if (response.StatusCode == HttpStatusCode.RequestTimeout || (int)response.StatusCode > 500)
                    Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["timer_web_api"]));
            }

			return response;
		}
Пример #17
0
        private bool IsTheDriverReallyReallyReallyAbleToTalkToItsBrowser(IAttachableSeleniumSession attachableSeleniumSession)
        {
            // UNFORTUNATELY: Just because (say) chromedriver.exe says it is ready does not mean it is actually able to do anything.
            // chromedriver.exe will spawn multiple chrome.exe processes.
            // If we close the browser (manually), then the browsers go away - but chromedriver.exe is left orphaned.
            //    Worse, chromedriver.exe will return ready:true in the IsChromeDriverReady check (technically: this is correct; but its misleading)
            //
            // The only way we can really know if a chromedriver.exe can talk to a browser is to issue it a command
            //    Unfortunately, this takes 10-20 seconds to timeout: so instead I set a hard limit here defined by PROBE_TIMEOUT
            //       The assumption being that if it hasn't responded in that time, the browsers are likely dead.
            //       On a local machine, the response is usually in the order of a few hundred milliseconds.
            //       This might cause problems when attaching to remotely running browsers due to latency.
            try
            {
                var client  = new RestSharp.RestClient(attachableSeleniumSession.RemoteServerUri);
                var request = new RestSharp.RestRequest($"/session/{attachableSeleniumSession.Response.SessionId}/url", RestSharp.Method.GET);
                request.Timeout = 5000;

                var response = client.Execute(request);

                return(response.StatusCode == System.Net.HttpStatusCode.OK);
            }
            catch
            {
                return(false);
            }
        }
Пример #18
0
        /// <summary>
        /// http://docs.couchdb.org/en/2.0.0/api/database/find.html
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task <CouchResponse> SelectAsync(FindBuilder expression)
        {
            var request = new RestSharp.RestRequest("/_find", RestSharp.Method.POST);

            request.AddParameter("application/json", expression.ToString(), RestSharp.ParameterType.RequestBody);
            return(await client.http.ExecuteAsync(request));
        }
Пример #19
0
        public void DeleteUserByIdTest()
        {
            RestSharp.RestClient  client  = new RestSharp.RestClient("http://localhost:50235/api/user");
            RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.GET);
            List <User>           users   = new List <User>();

            users = client.Execute <List <User> >(request).Data;

            User user = users.FirstOrDefault();

            if (user == null)
            {
                Assert.Fail();
            }
            var url = string.Format("http://localhost:50235/api/user/{0}", user.Id);

            client  = new RestSharp.RestClient(url);
            request = new RestSharp.RestRequest(RestSharp.Method.DELETE);

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

            Assert.IsTrue(response.Data);
            client  = new RestSharp.RestClient("http://localhost:50235/api/user");
            request = new RestSharp.RestRequest(RestSharp.Method.GET);
            var oldUserCount = users.Count;

            users = new List <User>();
            users = client.Execute <List <User> >(request).Data;
            Assert.IsTrue(users.Count == oldUserCount - 1);
        }
Пример #20
0
        public string Post(string url, string payload, string time, bool requestId)
        {
            var client  = new RestSharp.RestClient(_apiDomain);
            var request = new RestSharp.RestRequest(url);

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

            string nonce  = Guid.NewGuid().ToString();
            string digest = HashBySegments(_apiSecret, _apiKey, time, nonce, _organizationID, "POST", GetPath(url), GetQuery(url), payload);

            if (payload != null)
            {
                request.AddJsonBody(payload);
            }

            request.AddHeader("X-Time", time);
            request.AddHeader("X-Nonce", nonce);
            request.AddHeader("X-Auth", _apiKey + ":" + digest);
            request.AddHeader("X-Organization-Id", _organizationID);

            if (requestId)
            {
                request.AddHeader("X-Request-Id", Guid.NewGuid().ToString());
            }

            var response = client.Execute(request, RestSharp.Method.POST);
            var content  = response.Content;

            return(content);
        }
Пример #21
0
        public void UpdateUserTest()
        {
            RestSharp.RestClient  client  = new RestSharp.RestClient("http://localhost:50235/api/user");
            RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.GET);
            List <User>           users   = new List <User>();

            users = client.Execute <List <User> >(request).Data;
            if (users == null || users.Count == 0)
            {
                Assert.Fail();
            }
            var user = users.FirstOrDefault();

            var updateUser = user;

            updateUser.Phone = "2500";
            client           = new RestSharp.RestClient("http://localhost:50235/api/user/");
            request          = new RestSharp.RestRequest(RestSharp.Method.PUT);
            request.AddJsonBody(updateUser);
            var responesUpdate = client.Execute <bool>(request);

            Assert.IsTrue(responesUpdate.Data);
            client  = new RestSharp.RestClient("http://localhost:50235/api/user");
            request = new RestSharp.RestRequest(RestSharp.Method.GET);
            users   = new List <User>();
            users   = client.Execute <List <User> >(request).Data;
            Assert.IsTrue(users.FirstOrDefault().Phone.Equals("2500"));
        }
Пример #22
0
        public object PostRest(IConfiguration _config, string Method, string Inst, string Type, string entity, out string Error)
        {
            object obj = new object();

            Error = string.Empty;
            try
            {
                var client  = new RestSharp.RestClient(_config.GetConnectionString("UrlConnectEpicor") + Method + Inst);
                var request = new RestSharp.RestRequest(RestSharp.Method.POST);
                request.AddHeader("authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", _config["UserEpicor"], _config["PassEpicor"]))));
                request.AddHeader("content-type", "application/json");
                request.AddParameter("application/json", entity, RestSharp.ParameterType.RequestBody);
                var response = client.Execute(request);
                if (response.StatusCode.ToString() != "OK")
                {
                    Error = response.Content;
                }

                obj = JObject.Parse(response.Content).SelectToken(Type, false);
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }
            return(obj);
        }
Пример #23
0
        public async Task <T> Get <T>(string url, Dictionary <string, object> formdata = null)
        {
            try
            {
                var client  = new RestSharp.RestClient(url);
                var request = new RestSharp.RestRequest(RestSharp.Method.GET);
                foreach (var item in formdata)
                {
                    request.AddParameter(item.Key, item.Value);
                }
                System.Diagnostics.Debug.WriteLine(url);
                var response = await client.ExecuteTaskAsync(request);

                if (response != null)
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(response.Content));
                    }
                }
            }
            catch
            {
            }
            return(default(T));
        }
Пример #24
0
        private static void UpdateUserAccess(User user, string projectName, string applicationName, string cluster, Access access)
        {
            user.Access.AddRule(new AccessRules
            {
                Project = projectName,
                Application = applicationName,
                Cluster = cluster,
                Access = access
            });

            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Users/" + ClaimsPrincipal.Current.Id();

            var restClient = new RestSharp.RestClient(url);

            var editRequest = new RestSharp.RestRequest();
            editRequest.Method = RestSharp.Method.PUT;
            editRequest.RequestFormat = RestSharp.DataFormat.Json;
            editRequest.AddHeader("Content-Type", "application/json;charset=utf-8");
            editRequest.AddHeader("Authorization", "Bearer " + ClaimsPrincipal.Current.IdToken());

            editRequest.AddBody(user);

            var editResult = restClient.Execute(editRequest);
        }
        public Dictionary <string, bool> PerformPOWHealthCheck()
        {
            // health check of POW nodes
            if (Logger != null)
            {
                Logger.LogInformation("Performing health check of POW NODES...");
            }

            var stats = new Dictionary <string, bool>();

            foreach (var node in this.POWStartupNodes) // always starts with all original nodes
            {
                var client = new RestSharp.RestClient(node)
                {
                    Timeout = 1000
                };
                var request = new RestSharp.RestRequest(node, RestSharp.Method.OPTIONS);
                //request.AddJsonBody(new { command = "attachToTangle" });
                var resp = client.Execute(request);

                if (resp.ResponseStatus == RestSharp.ResponseStatus.Completed && resp.StatusCode == System.Net.HttpStatusCode.NoContent)
                {
                    stats.Add(node, true);
                    Logger.LogInformation("POW node {node} is healthy!", node);
                }
                else
                {
                    Logger.LogInformation("Error while checking POW node {node}. Error: {resp.StatusDescription}", node, resp.StatusDescription);
                    stats.Add(node, false);
                }
            }
            return(stats);
        }
Пример #26
0
        PagedResult <TVShow> ITVShowsStore.ListPopular(int page)
        {
            var client = new RestSharp.RestClient("https://api.themoviedb.org/3");

            // client.Authenticator = new HttpBasicAuthenticator(username, password);
            var request = new RestSharp.RestRequest("tv/popular");

            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            request.AddHeader("Accept", "application/json");
            request.AddParameter("api_key", "ad332258020257fb88e2cc468225dcb0");
            request.AddParameter("language", "en");
            request.AddParameter("page", page);
            request.JsonSerializer = new NewtonsoftJsonSerializer();
            var response = client.ExecuteAsGet <PagedResult <TVShowResponse> >(request, "GET");

            return(new PagedResult <TVShow>
            {
                Results = from showResponse in response.Data.Results
                          select new TVShow
                {
                    Id = showResponse.Id,
                    Genres = String.Join(", ", from genreId in showResponse.GenreIds select GetGenreById(genreId).Name),
                    Name = showResponse.Name,
                    Overview = showResponse.Overview,
                    PosterThumb = "https://image.tmdb.org/t/p/w92" + showResponse.PosterPath,
                    PosterImage = "https://image.tmdb.org/t/p/w300" + showResponse.PosterPath,
                    Popularity = showResponse.Popularity,
                    VoteAverage = showResponse.VoteAverage
                },
                TotalPages = response.Data.TotalPages,
                Page = response.Data.Page,
                TotalResults = response.Data.TotalResults
            });
        }
Пример #27
0
        public ActionResult Index(string projectName, string applicationName, string clusterName)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var newCluster = new Elders.Pandora.Box.Cluster(clusterName, new Dictionary<string, string>());

            var url = hostName + "/api/Clusters/" + projectName + "/" + applicationName + "/" + clusterName;

            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());
            request.AddBody(JsonConvert.SerializeObject(new Dictionary<string, string>()));

            var response = client.Execute(request);

            if (!string.IsNullOrWhiteSpace(response.ErrorMessage))
            {
                throw response.ErrorException;
            }

            Elders.Pandora.Server.UI.ViewModels.User.GiveAccess(User, projectName, applicationName, clusterName, Access.WriteAccess);

            var config = GetConfig(projectName, applicationName);
            config.Clusters.Add(new Configuration.ClusterDTO(new Cluster(newCluster.Name, Access.WriteAccess), newCluster.AsDictionary()));

            return View(config);
        }
Пример #28
0
        private async Task GetDocStatus()
        {
            if (Connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                RestSharp.RestClient client = new RestSharp.RestClient();
                string path = "DocumentSQLConnection";
                client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath + path);
                {
                    string str     = $"GET?qry=SELECT DocStatus FROM tblTempDocHeader WHERE DocNum ='{txfPOCode.Text}'";
                    var    Request = new RestSharp.RestRequest(str, RestSharp.Method.GET);
                    var    cancellationTokenSource = new CancellationTokenSource();
                    await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                    var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                    if (res.Content.ToString().Contains("DocStatus"))
                    {
                        DataSet myds = new DataSet();
                        myds = Newtonsoft.Json.JsonConvert.DeserializeObject <DataSet>(res.Content);
                        if (myds.Tables[0].Rows[0]["DocStatus"] != null)
                        {
                            if (Convert.ToInt32(myds.Tables[0].Rows[0]["DocStatus"]) == 3)
                            {
                                InProccess = true;
                            }
                        }
                    }
                }
            }
            else
            {
                Vibration.Vibrate();
                message.DisplayMessage("No Internet Connection", false);
            }
        }
        public async Task <List <Ticker> > GetTickerAsync()
        {
            const string endpoint = "ticker/?limit=0";
            var          request  = new RestSharp.RestRequest(endpoint, RestSharp.Method.GET);
            var          response = await client.ExecuteTaskAsync <List <CoinMarketCap.PublicAPI.Ticker> >(request);

            //string filename = "coinmarketcap-ticker-" + DateTime.Now.ToString("yyyy-MM-dd");
            //System.IO.File.WriteAllText(System.IO.Path.ChangeExtension(filename, ".json"), response.Content);

            if (response.IsSuccessful)
            {
                // TODO: check for response.Data.metadata.error
                var result = response.Data;
                return(result.Select((arg) => new Ticker {
                    Name = arg.name,
                    Symbol = arg.symbol,
                    Data = new TickerDB
                    {
                        AssetId = arg.id,
                        LastUpdated = DateTimeOffset.FromUnixTimeSeconds(arg.last_updated).DateTime.ToLocalTime(),
                        MarketCapacityUsd = arg.market_cap_usd,
                        PriceBtc = arg.price_btc,
                        PriceUsd = arg.price_usd,
                        Rank = arg.rank,
                        Volume24hUsd = arg.volume_usd
                    }
                }).ToList());
            }
            else
            {
                throw new Exception(response.ErrorMessage);
            }
        }
Пример #30
0
        /// <summary>
        /// http://docs.couchdb.org/en/2.2.0/api/document/common.html#obtaining-a-specific-revision
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <CouchResponse> GetRevisionAsync(string id, string rev)
        {
            var request = new RestSharp.RestRequest(Helper.EncodeID(id), RestSharp.Method.GET);

            request.AddQueryParameter("rev", rev);
            return(await client.http.ExecuteAsync(request));
        }
Пример #31
0
        private IDictionary <long, Genre> ListGenres()
        {
            var client = new RestSharp.RestClient("https://api.themoviedb.org/3");

            IDictionary <long, Genre> dict = new Dictionary <long, Genre>();
            // client.Authenticator = new HttpBasicAuthenticator(username, password);
            var request = new RestSharp.RestRequest("genre/tv/list");

            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            request.AddHeader("Accept", "application/json");
            request.AddParameter("api_key", "ad332258020257fb88e2cc468225dcb0");
            request.JsonSerializer = new NewtonsoftJsonSerializer();

            var response = client.ExecuteAsGet <GenreResponse>(request, "GET");

            response.Data.Genres.ForEach((Genre obj) => dict.Add(obj.Id, obj));
            request = new RestSharp.RestRequest("genre/movie/list");
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            request.AddHeader("Accept", "application/json");
            request.AddParameter("api_key", "ad332258020257fb88e2cc468225dcb0");
            request.JsonSerializer = new NewtonsoftJsonSerializer();

            response = client.ExecuteAsGet <GenreResponse>(request, "GET");
            response.Data.Genres.ForEach((Genre obj) => {
                if (!dict.ContainsKey(obj.Id))
                {
                    dict.Add(obj.Id, obj);
                }
            });
            return(dict);
        }
Пример #32
0
        internal async void DisplayAssetInfo(string asset)
        {
            const string url = "https://s2.coinmarketcap.com/static/img/coins/32x32/";

            if (cmc_listing == null)
            {
                cmc_listing = await CoinMarketCapApiClient.GetListingsAsync();
            }
            var listing = cmc_listing.FirstOrDefault(x => asset.Equals(x.symbol, StringComparison.CurrentCultureIgnoreCase));

            if (listing != null)
            {
                label5.Text = listing.name;
                var client = new RestSharp.RestClient(url);
                var req    = new RestSharp.RestRequest($"{listing.id}.png", RestSharp.Method.GET);
                var resp   = await client.ExecuteTaskAsync(req);

                image1.Pixbuf = new Gdk.Pixbuf(resp.RawBytes);
            }
            else
            {
                label5.Text   = asset;
                image1.Pixbuf = null;
            }
        }
Пример #33
0
        public static void Send(string body, bool IsbodyHtml, string subject, string to)
        {
            //MailMessage msg = new MailMessage();
            //msg.Body = body;
            //msg.IsBodyHtml = IsbodyHtml;
            //msg.From = new MailAddress("*****@*****.**");
            //msg.Subject = subject;
            //msg.To.Add(to);

            //try
            //{
            //    SmtpClient client = new SmtpClient();
            //    client.Send(msg);
            //}
            //catch (System.Exception ex)
            //{

            RestSharp.RestClient client = new RestSharp.RestClient();
            client.BaseUrl       = "https://api.mailgun.net/v2";
            client.Authenticator =
                new RestSharp.HttpBasicAuthenticator("api",
                                                     "key-3g7l0iqd3ioxemch8-hqi04liuel3px9");
            RestSharp.RestRequest request = new RestSharp.RestRequest();
            request.AddParameter("domain",
                                 "asmoney.com", RestSharp.ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", "ManagerWar <*****@*****.**>");
            request.AddParameter("to", to);
            request.AddParameter("subject", subject);
            request.AddParameter("text", body);
            request.Method = RestSharp.Method.POST;
            client.Execute(request);
        }
Пример #34
0
        public void Update(string city)
        {
            try{
                System.Text.StringBuilder str = new System.Text.StringBuilder(city);
                str.Remove(0, 13);
                city = str.ToString();
            } catch (Exception) {
                //todo replace city with user's or use default
            }
            Console.WriteLine(city);
            foreach (var i in cityList)
            {
                if (city.Equals(i.name) | city.Equals(i.name_lowecase))
                {
                    id = i.id;
                }
            }
            var client  = new RestSharp.RestClient("http://api.openweathermap.org/data/2.5");
            var request = new RestSharp.RestRequest("weather?id=" + id + "&APPID=cbe768adbe16ad6ce8c15294944172ac");

            RestSharp.IRestResponse responce = client.Execute(request);
            var content = responce.Content;

            //Console.WriteLine(content);
            Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JToken.Parse(content);
            dynamic obj  = Newtonsoft.Json.JsonConvert.DeserializeObject(content);
            var     main = obj.main;

            value = main.temp - 273.15;
            var weather = obj.weather;

            description = weather[0].description;
            location    = obj.name;
            Console.WriteLine("weather data updated");
        }
        private void web1_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            GTMAccessToken _gtmAccessToken = null;

            if (e.Uri.Query.ToLower().IndexOf("code") != -1 )
            {
                //get the "code" from GTM
                string _code = e.Uri.Query.Replace("?code=", "");
                e.Cancel = true;

                var _rc = new RestSharp.RestClient(@"https://api.citrixonline.com");
                RestSharp.RestRequest _gtmTokenCodeReq = new RestSharp.RestRequest("/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id={api_key}", RestSharp.Method.GET);
                _gtmTokenCodeReq.AddUrlSegment("responseKey", _code);
                _gtmTokenCodeReq.AddUrlSegment("api_key", this.gtmAPIKey.Text);

                var _gtmTokenCodeResp = _rc.Execute(_gtmTokenCodeReq);

                if (_gtmTokenCodeResp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var jsonCode = _gtmTokenCodeResp.Content;
                    _gtmAccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<GTMAccessToken>(jsonCode);
                }

                //now we have the token. Create a meeting
                var _gtmMeetingReq = new RestSharp.RestRequest(@"/G2M/rest/meetings", RestSharp.Method.POST);
                _gtmMeetingReq.AddHeader("Accept", "application/json");
                _gtmMeetingReq.AddHeader("Content-type", "application/json");
                _gtmMeetingReq.AddHeader("Authorization", string.Format("OAuth oauth_token={0}", _gtmAccessToken.access_token));

                //creating the meeting request json for the request.
                Newtonsoft.Json.Linq.JObject _meetingRequestJson = new Newtonsoft.Json.Linq.JObject();
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("subject", "Immediate Meeting"));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("starttime", DateTime.UtcNow.AddSeconds(30).ToString("s")));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("endtime", DateTime.UtcNow.AddHours(1).AddSeconds(30).ToString("s")));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("passwordrequired", "false"));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("conferencecallinfo", "Hybrid"));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("timezonekey", ""));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("meetingtype", "Immediate"));

                //converting the jobject back to string for use within the request
                string gtmJSON = Newtonsoft.Json.JsonConvert.SerializeObject(_meetingRequestJson);

                _gtmMeetingReq.AddParameter("text/json", gtmJSON, RestSharp.ParameterType.RequestBody);

                var _responseMeetingRequest = _rc.Execute(_gtmMeetingReq);

                if (_responseMeetingRequest.StatusCode == System.Net.HttpStatusCode.Created)
                {
                    // meeting created to add a message, format it and add it to the list
                    string _meetingResponseJson = _responseMeetingRequest.Content;

                    Newtonsoft.Json.Linq.JArray _meetingResponse = Newtonsoft.Json.Linq.JArray.Parse(_meetingResponseJson);
                    var _gtmMeetingObject = _meetingResponse[0];

                    MessageBox.Show(_gtmMeetingObject["joinURL"].ToString());
                }
            }
        }
Пример #36
0
        static void Main(string[] args)
        {
            //http://www.omdbapi.com/?t=Frozen&y=&plot=short&r=json

            var client = new RestSharp.RestClient("http://www.omdbapi.com");
            var request = new RestSharp.RestRequest("/?t=Terminator&y=&plot=short&r=json", RestSharp.Method.GET);
            while (true)
            {
                var response = client.Execute(request);
                Console.WriteLine(response.Content);
                Thread.Sleep(4000);
            }
        }
Пример #37
0
        protected RestSharp.IRestResponse Execute(string url, RestSharp.Method method, List<Header> headers)
        {
            if (headers == null) headers = new List<Header>();

            RestSharp.IRestClient client = new RestSharp.RestClient(Root);
            RestSharp.IRestRequest request = new RestSharp.RestRequest(url, method);
            foreach (var header in headers)
            {
                request.AddParameter(header.Name, header.Value, RestSharp.ParameterType.HttpHeader);
            }
            request.RequestFormat = RestSharp.DataFormat.Json;
            var response = client.Execute(request);
            return response;
        }
Пример #38
0
        public void DownloadMessages()
        {
            try
            {
                db = new VehicleDBEntities(Connection.GetConnectionString());
                var ps = db.ProjectSettings.FirstOrDefault();
                if (ps == null)
                    ps = new ProjectSetting() { StopSmsLogService = false, SmsLogUpdateDate = DateTime.Now.AddYears(-1), SmsLogRefreshTime = 1, };
                if (!ps.StopSmsLogService)
                {
                    var d = ps.SmsLogUpdateDate.Value;
                    var twilio = new TwilioRestClient(ConfigHelper.AppSetting("Twilio_AccountSid"), ConfigHelper.AppSetting("Twilio_AuthToken"));
                    var NowDate = DateTime.Now;
                    string resource = string.Format("Accounts/{0}/SMS/Messages.json?DateSent>={1}", ConfigHelper.AppSetting("Twilio_AccountSid"), d.ToString("yyyy-MM-dd HH:mm:ss"));
                    RestSharp.RestRequest rs = new RestSharp.RestRequest();
                    rs.Resource = resource;

                    var smsResult = twilio.Execute<SmsMessageResult>(rs);
                    var smsList = new List<Message>();
                    if (smsResult != null)
                        AutoMapper.Mapper.Map(smsResult.SMSMessages, smsList);
                    if (smsList.Count > 0)
                    {
                        foreach (var item in smsList)
                        {
                            if (!db.Messages.Any(p => p.Sid == item.Sid))
                                db.Messages.AddObject(item);
                        }
                        db.SaveChanges();
                    }
                    ps.SmsLogUpdateDate = NowDate;
                    if (ps.ID == 0)
                        db.ProjectSettings.AddObject(ps);
                    db.SaveChanges();
                    WriteLog(smsList.Count + " Sms read");
                }
                int interval = ps.SmsLogRefreshTime * 60 * 1000;
                if (timer1.Interval != interval)
                {
                    timer1.Stop();
                    timer1.Interval = interval;
                    timer1.Start();
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString());
            }
        }
Пример #39
0
        public static async Task<string> ExecuteReport()
        {
            var sf_client = new Salesforce.Common.AuthenticationClient();
            sf_client.ApiVersion = "v34.0";
            await sf_client.UsernamePasswordAsync(consumerKey, consumerSecret, username, password + usertoken, url);

            string reportUrl = "/services/data/" + sf_client.ApiVersion + "/analytics/reports/" + reportId;

            var client = new RestSharp.RestClient(sf_client.InstanceUrl);
            var request = new RestSharp.RestRequest(reportUrl, RestSharp.Method.GET);
            request.AddHeader("Authorization", "Bearer " + sf_client.AccessToken);
            var restResponse = client.Execute(request);
            var reportData = restResponse.Content;
            return reportData;
        }
        public List<WeatherPoint> GetMetwitWeather(decimal latitude, decimal longitude) {
            var request = new RestSharp.RestRequest("v2/weather", RestSharp.Method.GET);
            request.AddParameter("location_lat", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost);
            request.AddParameter("location_lng", longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost);
            if (!string.IsNullOrEmpty(clientKey)) {
                request.AddHeader("Authorization", string.Format("Bearer {0}", clientKey));
            }

            var response = restClient.Execute<WeatherResponse>(request);
            if (response != null && response.Data != null) {
                return response.Data.Objects;
            } else {
                return null;
            }
        }
        public HourlyWeatherResponse GetHourlyOpenWeatherMapWeather(decimal latitude, decimal longitude) {
            var request = new RestSharp.RestRequest("forecast", RestSharp.Method.GET);
            request.AddParameter("lat", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost);
            request.AddParameter("lon", longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost);
            if (!string.IsNullOrEmpty(apiKey)) {
                //request.AddHeader("Authorization", string.Format("Bearer {0}", clientKey));
            }

            var response = restClient.Execute<HourlyWeatherResponse>(request);
            if (response != null && response.Data != null) {
                return response.Data;
            } else {
                return null;
            }
        }
        public RestSharp.IRestRequest ToRestRequest(string baseUrl, SDK.Http.IHttpRequest request)
        {
            var resourcePath = request.CanonicalUri.ToString().Replace(baseUrl, string.Empty);
            var method = this.ConvertMethod(request.Method);

            var restRequest = new RestSharp.RestRequest(resourcePath, method);
            restRequest.RequestFormat = RestSharp.DataFormat.Json;
            this.CopyHeaders(request.Headers, restRequest);

            if (request.HasBody)
            {
                restRequest.AddParameter(request.BodyContentType, request.Body, RestSharp.ParameterType.RequestBody);
            }

            return restRequest;
        }
        /// <summary>
        /// jogosultság ellenörzés
        /// 
        /// 1. megvizsgálja, hogy kell-e jogosultságot ellenőrizni
        /// 2. ha kell, akkor megvizsgálja a paraméter attribútum tömböt,
        ///     ha nincs eleme, akkor visszatér false-al
        ///     ha van eleme, akkor a bejelentkezett felhasználóhoz kiolvasásra kerülnek a beállított jogosultságok
        ///     ha a felhasynaloi jogosultsagnak és a kontroller (kontroller action)-nek van metszete, akkor true-val, 
        ///     ha nincs, akkor false-val tér vissza 
        /// <param name="httpContext"></param>
        /// <returns>ha a jogosultság megfelelő, akkor true-val tér vissza, egyébként false-al</returns>
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            if (!_authorize) { return true; }

            List<string> groupList = UserGroups != null ? UserGroups.Split(';').ToList() : new List<string>();

            if (groupList.Count.Equals(0))
            {
                return false;
            }

            //olvasás sütiből
            string cookieName = CompanyGroup.Helpers.ConfigSettingsParser.GetString("CookieName", "companygroup");

            System.Web.HttpCookie cookie = httpContext.Request.Cookies.Get(cookieName); 

            if (cookie == null || String.IsNullOrWhiteSpace(cookie.Value))
            {
                return false;
            }

            //szervizhívás, ami kiolvassa a felhasználóhoz tartozó jogosultságokat

            string ServiceBaseUrl = CompanyGroup.Helpers.ConfigSettingsParser.GetString("ServiceBaseUrl", "http://1Juhasza/CompanyGroup.ServicesHost/{0}.svc/");

            RestSharp.RestClient client = new RestSharp.RestClient(String.Format(ServiceBaseUrl, "VisitorService"));

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

            request.RequestFormat = RestSharp.DataFormat.Json;

            request.Resource = "GetRoles"; 

            request.AddBody(new { ObjectId = cookie.Value, DataAreaId = CompanyGroup.Helpers.ConfigSettingsParser.GetString("DataAreaId", "hrp") }); 

            RestSharp.RestResponse<List<string>> response = client.Execute<List<string>>(request);

            List<string> roles =  response.Data;

            return groupList.Intersect(roles).Count() > 0;
        }
Пример #44
0
        private static User GetUser()
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Users/" + ClaimsPrincipal.Current.Id();

            var restClient = new RestSharp.RestClient(url);

            var request = new RestSharp.RestRequest();
            request.Method = RestSharp.Method.GET;
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json;charset=utf-8");
            request.AddHeader("Authorization", "Bearer " + ClaimsPrincipal.Current.Token());

            var result = restClient.Execute(request);

            return JsonConvert.DeserializeObject<User>(result.Content);
        }
        public WeatherData GetWorldWeatherOnlineWeather(decimal latitude, decimal longitude, int numberOfDays) {
            var request = new RestSharp.RestRequest("free/v1/weather.ashx", RestSharp.Method.GET);
            request.AddParameter("q", string.Format("{0},{1}", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)), RestSharp.ParameterType.GetOrPost);
            request.AddParameter("format", "xml", RestSharp.ParameterType.GetOrPost);
            request.AddParameter("num_of_days", numberOfDays, RestSharp.ParameterType.GetOrPost);
            if (numberOfDays <= 0) {
                request.AddParameter("fx", "no", RestSharp.ParameterType.GetOrPost);
            }
            request.AddParameter("includeLocation", "yes", RestSharp.ParameterType.GetOrPost);
            request.AddParameter("key", clientKey, RestSharp.ParameterType.GetOrPost);

            var response = restClient.Execute<WeatherData>(request);
            if (response != null && response.Data != null) {
                return response.Data;
            } else {
                return null;
            }
        }
Пример #46
0
        //[ResourceAuthorize(Resources.Actions.Manage, Resources.Users)]
        public ActionResult Edit(string userId, AccessRules[] access)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Users/" + userId;

            var restClient = new RestSharp.RestClient(url);

            var request = new RestSharp.RestRequest();
            request.Method = RestSharp.Method.PUT;
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json;charset=utf-8");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());

            var securityAccess = new SecurityAccess();

            if (access == null)
                access = new AccessRules[] { };

            foreach (var rule in access)
            {
                securityAccess.AddRule(rule);
            }

            var user = GetUser(userId);

            user.Access = securityAccess;

            request.AddBody(user);

            var result = restClient.Execute(request);

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var identity = (User.Identity as ClaimsIdentity);
                var role = identity.Claims.SingleOrDefault(x => x.Type == "SecurityAccess");

                if (role != null)
                    identity.RemoveClaim(role);

                identity.AddClaim(new Claim("SecurityAccess", JsonConvert.SerializeObject(securityAccess, Formatting.Indented)));
            }

            return RedirectToAction("Edit");
        }
Пример #47
0
        public ActionResult Index()
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Projects";

            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.GET);
            request.AddHeader("Authorization", "Bearer " + User.IdToken());
            var response = client.Execute(request);

            if (!string.IsNullOrWhiteSpace(response.ErrorMessage))
            {
                throw response.ErrorException;
            }

            var projects = JsonConvert.DeserializeObject<List<string>>(response.Content);

            return View(projects);
        }
Пример #48
0
        //todo kick out RestSharp and make it truly async
        public static async Task<MangaResult> GetMangaQueryResultLink(string query) {
            try {
                RefreshAnilistToken();

                var cl = new RestSharp.RestClient("http://anilist.co/api");
                var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
                rq = new RestSharp.RestRequest("/manga/search/" + Uri.EscapeUriString(query));
                rq.AddParameter("access_token", token);

                var smallObj = JArray.Parse(cl.Execute(rq).Content)[0];

                rq = new RestSharp.RestRequest("manga/" + smallObj["id"]);
                rq.AddParameter("access_token", token);
                return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content));
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }
Пример #49
0
        public ActionResult Applications(string projectName, string applicationName, string fileName, string config)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Jars/" + projectName + "/" + applicationName + "/" + fileName;

            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.POST);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());

            if (!string.IsNullOrWhiteSpace(config))
            {
                try
                {
                    var jar = JsonConvert.DeserializeObject<Jar>(config);
                    var box = Box.Box.Mistranslate(jar);
                }
                catch (Exception)
                {
                    var jar = new Jar();
                    jar.Name = applicationName;

                    config = JsonConvert.SerializeObject(jar);
                }
            }
            else
            {
                var jar = new Jar();
                jar.Name = applicationName;

                config = JsonConvert.SerializeObject(jar);
            }

            request.AddBody(config);

            var response = client.Execute(request);

            Elders.Pandora.Server.UI.ViewModels.User.GiveAccess(User, projectName, applicationName, "Defaults", Access.WriteAccess);

            return Redirect("/Projects/" + projectName + "/" + applicationName + "/Clusters");
        }
Пример #50
0
        public static async Task<AnimeResult> GetAnimeData(string query)
        {
            if (string.IsNullOrWhiteSpace(query))
                throw new ArgumentNullException(nameof(query));

            await RefreshAnilistToken();

            var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
            var smallContent = "";
            var cl = new RestSharp.RestClient("http://anilist.co/api");
            var rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query));
            rq.AddParameter("access_token", token);
            smallContent = cl.Execute(rq).Content;
            var smallObj = JArray.Parse(smallContent)[0];

            rq = new RestSharp.RestRequest("/anime/" + smallObj["id"]);
            rq.AddParameter("access_token", token);
            var content = cl.Execute(rq).Content;

            return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
        }
        public WeatherResponse GetForecastIOWeather(decimal latitude, decimal longitude, DateTime? time, string units, string[] excludes) {
            RestSharp.RestRequest request;
            if (time.HasValue) {
                request = new RestSharp.RestRequest("forecast/{apikey}/{latitude},{longitude},{time}", RestSharp.Method.GET);
                request.AddParameter("time", DateTimeToUnix(time.Value), RestSharp.ParameterType.UrlSegment);
            } else {
                request = new RestSharp.RestRequest("forecast/{apikey}/{latitude},{longitude}", RestSharp.Method.GET);
            }
            request.AddParameter("latitude", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.UrlSegment);
            request.AddParameter("longitude", longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.UrlSegment);
            request.AddParameter("apikey", _apiKey, RestSharp.ParameterType.UrlSegment);
            if (!string.IsNullOrEmpty(units)) {
                request.AddParameter("units", units, RestSharp.ParameterType.GetOrPost);
            }
            if (excludes != null && excludes.Length > 0) {
                request.AddParameter("exclude", string.Join(",", excludes), RestSharp.ParameterType.GetOrPost);
            }

            var response = _restClient.Execute<WeatherResponse>(request);
            return response.Data;
        }
Пример #52
0
        //[ResourceAuthorize(Resources.Actions.Read, Resources.Users)]
        public ActionResult Index(int count = 0, int start = 0, string filter = null)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Users";

            var restClient = new RestSharp.RestClient(url);

            var request = new RestSharp.RestRequest();
            request.Method = RestSharp.Method.GET;
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json;charset=utf-8");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());

            var result = restClient.Execute<List<User>>(request);

            foreach (var user in result.Data)
            {
                GetUserInfo(user);
            }

            return View(result.Data);
        }
Пример #53
0
        private string BuildUrlFromPath(string path)
        {
            string result = "https://api-content.dropbox.com/1/files/dropbox" + Uri.EscapeUriString(path) + "?";

            var authenticator = new OAuthAuthenticator(result,
                                                       "tdjfq9pdclgngyt",
                                                       "k6okn03xb6v5lza",
                                                       this.dropNetClient.UserLogin.Token,
                                                       this.dropNetClient.UserLogin.Secret);
            var authenticatorRequest = new RestSharp.RestRequest();
            authenticator.Authenticate(null, authenticatorRequest);

            bool first = true;
            foreach (var parameter in authenticatorRequest.Parameters)
            {
                if (!first)
                {
                    result += "&";
                }
                else
                {
                    first = false;
                }
                result += parameter.Name.ToString() + "=" + HttpUtility.UrlEncode(parameter.Value.ToString());
            }
            return result;
        }
Пример #54
0
 public static List<Screenshot> GetScreenshots(int category)
 {
     var client = new RestSharp.RestClient();
     var request = new RestSharp.RestRequest("http://www.appreciateui.com/api/screenshots.php?cat=" + category);
     return client.Execute<List<Screenshot>>(request).Data;
 }
Пример #55
0
 public static List<Icon> GetIcons()
 {
     var client = new RestSharp.RestClient();
     var request = new RestSharp.RestRequest("http://www.appreciateui.com/api/icons.php");
     return client.Execute<List<Icon>>(request).Data;
 }
Пример #56
0
 public static List<Category> GetCategories()
 {
     var client = new RestSharp.RestClient();
     var request = new RestSharp.RestRequest("http://www.appreciateui.com/api/categories.php");
     return client.Execute<List<Category>>(request).Data;
 }
Пример #57
0
        private async Task<AnimeResult> GetAnimeQueryResultLink(string query) {
            try {
                var cl = new RestSharp.RestClient("http://anilist.co/api");
                var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);

                RefreshAnilistToken();

                rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query));
                rq.AddParameter("access_token", token);

                var smallObj = JArray.Parse(cl.Execute(rq).Content)[0];

                rq = new RestSharp.RestRequest("anime/" + smallObj["id"]);
                rq.AddParameter("access_token", token);
                return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content));
            } catch (Exception) {
                return null;
            }
        }
Пример #58
0
        private void RefreshAnilistToken() {
            try {
                var cl = new RestSharp.RestClient("http://anilist.co/api");
                var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
                rq.AddParameter("grant_type", "client_credentials");
                rq.AddParameter("client_id", "kwoth-w0ki9");
                rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z");
                var exec = cl.Execute(rq);
                /*
                Console.WriteLine($"Server gave me content: { exec.Content }\n{ exec.ResponseStatus } -> {exec.ErrorMessage} ");
                Console.WriteLine($"Err exception: {exec.ErrorException}");
                Console.WriteLine($"Inner: {exec.ErrorException.InnerException}");
                */

                token = JObject.Parse(exec.Content)["access_token"].ToString();
            } catch (Exception ex) {
                Console.WriteLine($"Failed refreshing anilist token:\n {ex}");
            }
        }
Пример #59
-1
        public ActionResult Index(string projectName, string applicationName)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");

            var breadcrumbs = new List<KeyValuePair<string, string>>();
            breadcrumbs.Add(new KeyValuePair<string, string>("Projects", "/Projects"));
            breadcrumbs.Add(new KeyValuePair<string, string>(projectName, "/Projects/" + projectName));
            ViewBag.Breadcrumbs = breadcrumbs;

            var url = hostName + "/api/Jars/" + projectName + "/" + applicationName;

            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.GET);
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", "Bearer " + User.IdToken());

            var response = client.Execute(request);

            if (!string.IsNullOrWhiteSpace(response.ErrorMessage))
            {
                throw response.ErrorException;
            }

            var config = JsonConvert.DeserializeObject<Configuration>(response.Content);

            return View(config);
        }
Пример #60
-1
        private static void RefreshAnilistToken() {
            try {
                var cl = new RestSharp.RestClient("http://anilist.co/api");
                var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
                rq.AddParameter("grant_type", "client_credentials");
                rq.AddParameter("client_id", "kwoth-w0ki9");
                rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z");
                var exec = cl.Execute(rq);

                token = JObject.Parse(exec.Content)["access_token"].ToString();
            } catch (Exception ex) {
                Console.WriteLine($"Failed refreshing anilist token:\n {ex}");
            }
        }