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");
        }
        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());
                }
            }
        }
Exemplo n.º 4
0
        public RestSharp.IRestResponse SendRequest(int maxRetry = 10)
        {
            var client = new RestSharp.RestClient();

            RestSharp.IRestResponse response = client.Execute(Request);
            return(response);
        }
Exemplo n.º 5
0
        public string GetKB(string question)
        {
            string qnamakerUriBase = $"https://{ConfigurationManager.AppSettings["QnAApiHostName"]}/qnamaker/v1.0";
            string apiApppId       = ConfigurationManager.AppSettings["QnAKnowledgebaseId"];
            string apiKey          = ConfigurationManager.AppSettings["QnASubscriptionKey"];

            string body = $"{{\"question\" : \"{question}\"}}";

            qnamakerUriBase += $"/knowledgebases/{apiApppId}/generateAnswer";

            RestSharp.RestClient client = new RestSharp.RestClient(qnamakerUriBase)
            {
                Encoding = System.Text.Encoding.UTF8,
            };

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

            // Add Header
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Ocp-Apim-Subscription-Key", apiKey);
            request.AddHeader("cache-control", "no-cache");

            // Add Body
            request.AddParameter("undefined", body, RestSharp.ParameterType.RequestBody);

            // Send the Post Request
            RestSharp.IRestResponse response = client.Execute(request);

            return(response.Content);
        }
Exemplo n.º 6
0
        public JsonAddress GetAddressDetails(Address address)
        {
            var addressDetails = address.Street + " " + address.BuildingNumber + " " + address.City;
            var client         = new RestSharp.RestClient("https://eu1.locationiq.com/");
            var request        = new RestSharp.RestRequest("v1/search.php", RestSharp.Method.GET);

            request.AddParameter("key", "c24325218ea6eb");
            request.AddParameter("accept-language", "he");
            request.AddParameter("q", addressDetails);
            request.AddParameter("format", "json");
            var res = client.Execute(request);

            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var content    = JsonConvert.DeserializeObject <object>(res.Content);
                var parsedJson = JArray.Parse(content.ToString());
                var Jaddress   = new JsonAddress
                {
                    Latitude    = parsedJson[0]["lat"].ToString(),
                    Longitude   = parsedJson[0]["lon"].ToString(),
                    DisplayName = parsedJson[0]["display_name"].ToString()
                };
                return(Jaddress);
            }
            return(null);
        }
Exemplo n.º 7
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();
        }
        private string Upload(byte[] bytes, string fileName)
        {
            var campaignApiUrl   = _siteSettingsService.GetSettingsOrDefault().CampaignApiUrl;
            var campaignAuthCode = _siteSettingsService.GetSettingsOrDefault().CampaignTransactionalAuthorizationCode;

            if (string.IsNullOrEmpty(campaignApiUrl) || string.IsNullOrEmpty(campaignAuthCode))
            {
                Log.Error($"Error uploading file to Campaign. Campaign settings are missing.");
                return(null);
            }

            //using RestSharp for the assistance with the image post
            var restClient = new RestSharp.RestClient(campaignApiUrl.Trim('/'));
            var request    = new RestSharp.RestRequest($"{campaignAuthCode.Trim()}/uploadpersonalizedattachments", RestSharp.Method.POST)
            {
                AlwaysMultipartFormData = true
            };

            request.AddHeader("Content-Type", "multipart/form-data");
            request.AddFile(MessageArgument.AttachmentFile.Value, bytes, fileName, System.Web.MimeMapping.GetMimeMapping(fileName));
            var restResponse = restClient.Execute(request);

            if (!restResponse.Content.ToLower().StartsWith("ok"))
            {
                Log.Error($"Error uploading attachment to Campaign. Campaign message: {restResponse.Content}. Filename: {fileName}");
                return(string.Empty);
            }

            return(restResponse.Content.Replace("ok:", "").Trim()); //return the attachment token value wich will be sent with a message as an additional argument
        }
Exemplo n.º 9
0
        private static ConventerInfo GetLatestRatesFromApi()
        {
            string method = "latest";

            var request = new RestSharp.RestRequest(method);

            request.Method = RestSharp.Method.GET;
            request.AddParameter("base", baseCurrency);
            request.AddParameter("symbols", symbols);

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

            if (response.IsSuccessful && response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                lastErrorMessage = null;
                if (!DoesRatesFileExist(response.Data))
                {
                    SaveIntoFile(response.Data);
                }
                return(response.Data);
            }

            else
            {
                lastErrorMessage = response.StatusDescription;
                LogMessage(String.Format("Failed getting the latest data from api: {0}", lastErrorMessage));
                return(null);
            }
        }
Exemplo n.º 10
0
        //public string PrivateAccountKey ="PrivateAccountKey";
        public static string PostPurchase()
        {
            var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Purchase")
            {
                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", "{" +
                                 "\"TrxToken\": \"CT__6NBt_OO5gfCg7RUCF_xdtRuaohj8YOAjLqkyXVed23g_\",\n" +
                                 "\"Order\": \"000001\",\n" +
                                 "\"Amount\": 13000,\n" +
                                 "\"Tip\": 000,\n" +
                                 "\"Currency\": \"DOP\",\n" +
                                 "\"Capture\": true,\n" +
                                 "\"CustomerIP\": \"100.0.0.2\",\n" +
                                 "\"DataDo\": { \"Tax\": 000,\n \"Invoice\": \"000001\",\n }" +
                                 "}", RestSharp.ParameterType.RequestBody);

            RestSharp.IRestResponse response = client.Execute(request);
            return(response.Content);
        }
Exemplo n.º 11
0
        public string post(string url, string payload, bool requestId)
        {
            string time    = this.srvrTime();
            var    client  = new RestSharp.RestClient(this.urlRoot);
            var    request = new RestSharp.RestRequest(url);

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

            string nonce  = Guid.NewGuid().ToString();
            string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "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", this.apiKey + ":" + digest);
            request.AddHeader("X-Organization-Id", this.orgId);

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

            var response = client.Execute(request, RestSharp.Method.POST);
            //Console.Out.WriteLine("res: [" + response.Content + "]");
            var content = response.Content;

            return(content);
        }
Exemplo n.º 12
0
        private String DoUploadTags(IList <String> files, String user, bool includeLog)
        {
            m_Monitor.SetIndeterminate(StringResources.UploadingTags);

            var proxy = System.Net.WebRequest.GetSystemWebProxy();

            // upload in chunks; otherwise request size gets too large
            const int     MAX_FILES_PER_REQUEST = 50;
            int           nrOfRequests          = (files.Count + MAX_FILES_PER_REQUEST - 1) / MAX_FILES_PER_REQUEST;
            StringBuilder logBuilder            = new StringBuilder();

            for (int i = 0; i < nrOfRequests; ++i)
            {
                List <String> filesInRequest = new List <string>();
                for (int j = i * MAX_FILES_PER_REQUEST; j < (i + 1) * MAX_FILES_PER_REQUEST; ++j)
                {
                    if (j >= files.Count)
                    {
                        break;
                    }
                    filesInRequest.Add(files[j]);
                }
                var exportedData = Ares.Tags.TagsModule.GetTagsDB().FilesInterface.ExportDatabaseForGlobalDB(filesInRequest);

                var request = new RestSharp.RestRequest(GlobalDb.UploadPath, RestSharp.Method.POST);
                request.RequestFormat = RestSharp.DataFormat.Json;
                String serializedTagsData = ServiceStack.Text.TypeSerializer.SerializeToString <Ares.Tags.TagsExportedData <Ares.Tags.FileIdentification> >(exportedData);
                request.AddParameter("TagsData", serializedTagsData);
                request.AddParameter("User", ObfuscateUser(user));
                request.AddParameter("IncludeLog", includeLog);
                if (Settings.Default.UseTestDB)
                {
                    request.AddParameter("Test", true);
                }
                var client = new RestSharp.RestClient();
                client.BaseUrl = GlobalDb.BaseUrl;
                client.Timeout = 20 * 1000;
                var response = client.Execute <UploadResponse>(request);

                m_Token.ThrowIfCancellationRequested();
                if (response.ErrorException != null)
                {
                    throw new GlobalDbException(response.ErrorException);
                }
                if (response.Data == null)
                {
                    throw new GlobalDbException(String.IsNullOrEmpty(response.ErrorMessage) ? "No data received" : response.ErrorMessage);
                }
                if (response.Data.Status != 0)
                {
                    throw new GlobalDbException(response.Data.ErrorMessage);
                }
                if (i > 0)
                {
                    logBuilder.AppendLine("---------------------------------------------------------");
                }
                logBuilder.Append(response.Data.Log);
            }
            return(logBuilder.ToString());
        }
Exemplo n.º 13
0
        public IResponse Execute(IRequest request, HttpStatusCode andExpect)
        {
            var rc = new RestSharp.RestClient(_testSettings.BaseUrl);
            var rr = new RestSharp.RestRequest(request.RelativeUrl, request.Method);

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

            _logger.Information("{Event} {HttpMethod} {BaseUrl}{RelativeUrl} {@request}", "TestStartHttpRequest", request.Method, _testSettings.BaseUrl, request.RelativeUrl, request);
            var response = rc.Execute(rr);

            _logger.Write(response.StatusCode == andExpect ?
                          Serilog.Events.LogEventLevel.Information :
                          Serilog.Events.LogEventLevel.Error,
                          "{Event} {HttpMethod} {BaseUrl}{RelativeUrl} {StatusCode} {ExpectedStatusCode}", "TestEndHttpRequest", request.Method, _testSettings.BaseUrl, request.RelativeUrl, response.StatusCode, andExpect);

            if (response.StatusCode != andExpect)
            {
                throw new WebException($"The call to {request.Method} {_testSettings.BaseUrl}{request.RelativeUrl} was expected to return {andExpect} but returned {response.StatusCode}");
            }

            return(new Response(response));
        }
Exemplo n.º 14
0
        public string delete(string url, bool requestId)
        {
            string time    = this.srvrTime();
            var    client  = new RestSharp.RestClient(this.urlRoot);
            var    request = new RestSharp.RestRequest(url);

            string nonce  = Guid.NewGuid().ToString();
            string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "DELETE", getPath(url), getQuery(url), null);

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

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

            var response = client.Execute(request, RestSharp.Method.DELETE);

            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.Out.WriteLine("res: [" + response.Content + "]");

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return("{error_id: -1}");
            }
            return(response.Content);
        }
Exemplo n.º 15
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);
        }
Exemplo n.º 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;
		}
Exemplo n.º 17
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);
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Faz uma pesquisa no Github buscandos todos os repositórios publicos.
        /// </summary>
        /// <param name="termpoPesquisa">Nome ou parte do repositório que deseja pesquisar.</param>
        /// <param name="pagina">Página atual de pesquisa.</param>
        /// <returns>Retorna um objeto com o resultado da consulta ao Github.</returns>
        /// <exception cref="NullReferenceException">Quando o termo da pesquisa informado é inválido.</exception>
        /// <exception cref="IndexOutOfRangeException">Quando o número da página é menor ou igual a zero.</exception>
        /// <exception cref="RepositorioGitHubException">Ocorre quando ocorre algum erro na consulta da API do GitHub.</exception>
        public Entidades.GitSearch ProcurarRepositorios(string termpoPesquisa, int pagina)
        {
            if (String.IsNullOrEmpty(termpoPesquisa) || String.IsNullOrWhiteSpace(termpoPesquisa))
            {
                throw new NullReferenceException("Termo utilizado na pesquisa é inválido.");
            }

            if (pagina <= 0)
            {
                throw new IndexOutOfRangeException("Página inválida, ela deve ser um número maior que zero.");
            }

            Entidades.GitSearch resultado = null;
            var client  = new RestSharp.RestClient("https://api.github.com/");
            var request = new RestSharp.RestRequest("search/repositories?q={repositorio}&page={pagina}&per_page=20", RestSharp.Method.GET);

            request.AddUrlSegment("repositorio", termpoPesquisa);
            request.AddUrlSegment("pagina", pagina.ToString());

            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                resultado = Newtonsoft.Json.JsonConvert.DeserializeObject <Entidades.GitSearch>(response.Content);
            }
            else
            {
                throw new Excecoes.RepositorioGitHubException(String.Format("Ocorreu erro no momento da consulta. Código: {0} com a mensagem: {1}.", response.StatusCode, response.ErrorMessage));
            }

            return(resultado);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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");
        }
        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);
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
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
            }
        }
Exemplo n.º 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);
        }
Exemplo n.º 28
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);
        }
        public IActionResult GetClientComputerName(string ip)
        {
            try
            {
                Config config  = ConfigJSON.Read();
                string url     = "http://" + ip + ":" + config.ClientPort + "/POSClient/GetComputerName";
                var    client  = new RestSharp.RestClient(url);
                var    request = new RestSharp.RestRequest(RestSharp.Method.GET);

                request.AddHeader("Access-Control-Allow-Origin", "*");

                RestSharp.IRestResponse response = client.Execute(request);
                string pcName     = response.Content.Replace("\"", "");
                int    terminalId = 0;
                //check if terminal is assigned
                TerminalMapping terminalMapping = _context.TerminalMapping.FirstOrDefault(x => x.PCName == pcName);
                Terminal        terminal        = new Terminal();
                if (terminalMapping != null)
                {
                    terminal = _context.Terminal.FirstOrDefault(x => x.Id == terminalMapping.TerminalId);
                }

                return(Ok(new { pcName = pcName, terminalId = terminalMapping.TerminalId.ToString(), terminalName = terminal?.Name }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 30
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);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Busca todos os repositórios de um determinado usuário.
        /// </summary>
        /// <returns>Todos os repositórios do usuário informado.</returns>
        /// <exception cref="NullReferenceException">Quando nome do repositório informado é inválido.</exception>
        /// <exception cref="RepositorioGitHubException">Ocorre quando ocorre algum erro na consulta da API do GitHub.</exception>
        public List <Entidades.RootObject> PegarRepositorios(string usuario)
        {
            if (String.IsNullOrEmpty(usuario) || String.IsNullOrWhiteSpace(usuario))
            {
                throw new NullReferenceException("Usuário informado é inválido.");
            }

            List <Entidades.RootObject> resultado = null;
            var client  = new RestSharp.RestClient("https://api.github.com/");
            var request = new RestSharp.RestRequest("users/{user}/repos", RestSharp.Method.GET);

            request.AddUrlSegment("user", usuario);

            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                resultado = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Entidades.RootObject> >(response.Content);
            }
            else
            {
                throw new Excecoes.RepositorioGitHubException(String.Format("Ocorreu erro no momento da consulta. Código: {0} com a mensagem: {1}.", response.StatusCode, response.ErrorMessage));
            }

            return(resultado);
        }
Exemplo n.º 32
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);
            }
        }
Exemplo n.º 33
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"));
        }
Exemplo n.º 34
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);
        }
Exemplo n.º 35
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);
        }
Exemplo n.º 36
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;
            }
        }
Exemplo n.º 37
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));
        }
Exemplo n.º 38
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);
            }
        }
Exemplo n.º 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;
        }
Exemplo n.º 40
0
        protected RestSharp.IRestResponse Delete(string url, string body, List<Header> headers)
        {
            if (headers == null) headers = new List<Header>();

            RestSharp.IRestClient client = new RestSharp.RestClient(Root);
            RestSharp.IRestRequest request = new RestSharp.RestRequest(url, RestSharp.Method.DELETE);
            foreach (var header in headers)
            {
                request.AddParameter(header.Name, header.Value, RestSharp.ParameterType.HttpHeader);
            }
            request.AddBody(body);
            request.RequestFormat = RestSharp.DataFormat.Json;
            var response = client.Execute(request);
            return response;
        }
Exemplo n.º 41
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);
        }
        /// <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;
        }
Exemplo n.º 43
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);
        }
Exemplo n.º 44
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);
        }
Exemplo n.º 45
0
        /// <summary>
        /// Add the given simulation to the running service. 
        /// </summary>
        /// <param name="simulation">The simulation to add. Must not be null. </param>
        /// <returns>Created - the entry was added. Any other error indicates a failure. </returns>
        public HttpStatusCode Add(Simulation simulation)
        {
            if (null == simulation) throw new System.ArgumentNullException("simulation");

            string path = string.Format("{0}", GetSimulationResource());

            RestSharp.IRestClient client = new RestSharp.RestClient(Root);
            RestSharp.IRestRequest request = new RestSharp.RestRequest(path, RestSharp.Method.POST);
            request.AddParameter("application/json", JsonConvert.SerializeObject(simulation, JsonSerializerSettings), RestSharp.ParameterType.RequestBody);
            var response = client.Execute(request);
            return response.StatusCode;
        }
Exemplo n.º 46
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}");
            }
        }
Exemplo n.º 47
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;
            }
        }
Exemplo n.º 48
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");
        }
Exemplo n.º 49
0
        private void GetUserInfo(User user)
        {
            var url = "https://www.googleapis.com/plus/v1/people/" + user.Id;

            var restClient = new RestSharp.RestClient(url);

            var request = new RestSharp.RestRequest();
            request.Method = RestSharp.Method.GET;
            request.AddHeader("Authorization", "Bearer " + User.AccessToken());

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

            var info = result.Data;
            if (info != null)
            {
                user.AvatarUrl = info.Image.Url;
                user.FullName = info.DisplayName;
                user.FirstName = info.Name.GivenName;
                user.LastName = info.Name.FamilyName;

                if (info.Organizations != null)
                {
                    var organization = info.Organizations.FirstOrDefault(x => x.Primay == true);

                    if (organization == null)
                        organization = info.Organizations.FirstOrDefault();

                    if (organization != null)
                        user.Organization = organization.Name;
                }
            }
        }
Exemplo n.º 50
0
        private List<Jar> GetJars(string projectName)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Jars/" + projectName;

            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;
            }

            return JsonConvert.DeserializeObject<List<Jar>>(response.Content);
        }
Exemplo n.º 51
0
        public ActionResult Update(string projectName)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");
            var url = hostName + "/api/Projects/Update/" + projectName;

            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);

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

            return RedirectToAction("Index");
        }
Exemplo n.º 52
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");
        }
Exemplo n.º 53
0
        public ActionResult OpenJson(string projectName, string applicationName)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");

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

            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);

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

            return View("_ApplicationJsonView", model: JsonConvert.SerializeObject(config, Formatting.Indented));
        }
Exemplo n.º 54
0
        public FileResult DownloadJson(string projectName, string applicationName)
        {
            var hostName = ApplicationConfiguration.Get("pandora_api_url");

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

            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);

            string fileName = applicationName + ".json";

            byte[] bytes = new byte[response.Content.Length * sizeof(char)];
            Buffer.BlockCopy(response.Content.ToCharArray(), 0, bytes, 0, bytes.Length);

            return File(bytes, MimeMapping.GetMimeMapping(fileName), fileName);
        }
Exemplo n.º 55
0
        /// <summary>
        /// Return a simulation by name; or null if it does not exist (or an error occurs). 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Simulation GetByName(string name)
        {
            string path = string.Format("{0}('{1}')", GetSimulationResource(), name);

            RestSharp.IRestClient client = new RestSharp.RestClient(Root);
            RestSharp.IRestRequest request = new RestSharp.RestRequest(path, RestSharp.Method.GET);
            var response = client.Execute(request);
            if (response.StatusCode == HttpStatusCode.NotFound) return null;

            var result = JsonConvert.DeserializeObject<Simulation>(response.Content, JsonSerializerSettings);
            return result;
        }
Exemplo n.º 56
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;
 }
Exemplo n.º 57
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;
 }
Exemplo n.º 58
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;
 }
Exemplo n.º 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);
        }
Exemplo n.º 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}");
            }
        }