internal static ValidationException GetExceptionFromResponse(IRestResponse response)
        {
            var serializer = new RestSharp.Deserializers.JsonDeserializer();
            switch (response.StatusCode)
            {
                case HttpStatusCode.Conflict:
                    return new ValidationException(response, serializer.Deserialize<List<ObjectValidationError>>(response));

                default:
                    return new ValidationException(response);
            }
        }
		public async Task<List<Game>> GetGamesAsync(){
			Application.Current.Properties ["CartQuantity"] = "0";
			var client = new RestClient("http://dev.envocsupport.com/GameStore2/");
			var request = new RestRequest ("api/Games", Method.GET);
			request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

			var apiKey = Application.Current.Properties ["ApiKey"];
			var userId = Application.Current.Properties ["UserId"];

			try
			{
				request.AddHeader ("xcmps383authenticationkey",apiKey.ToString ());
				request.AddHeader ("xcmps383authenticationid",userId.ToString ());
			} 
			catch{}

			IRestResponse response = client.Execute(request);

			statusCodeCheck (response);
			Console.WriteLine ("here" + response.Content);

			if (response.StatusCode == HttpStatusCode.OK) {

				var rootObject = new RestSharp.Deserializers.JsonDeserializer().Deserialize<List<Game>>(response);
				return rootObject;
			}
			else {
				return null;
			}


		}
        public SuTToken getToken()
        {
            // Set up the POST request object.
            var request = new RestRequest();
            request.AddHeader("Accept", "application/json");
            request.Method = Method.POST;

            // Set the endpoint
            request.Resource = this.endpoint;

            // Iterate over the parameters and set them accordingly.
            foreach (string key in this.parameters.Keys)
            {
                request.AddParameter(key, (string)this.parameters[key]);
            }

            // Create the rest client and execute the request
            RestClient client = new RestClient(this.server);
            IRestResponse restResponse = client.Execute(request);

            var response = new PMAPIResponse<Token>();

            if (restResponse.StatusCode == HttpStatusCode.Accepted)
            {
                var deserializer = new RestSharp.Deserializers.JsonDeserializer();
                response.Data = deserializer.Deserialize<PMAPIResponseSuccessEnvelope<Token>>(restResponse);
                // TODO - we don't know if deserializer worked.
            }
            else if (restResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new PMAPITokenAuthorizationException(restResponse.ErrorMessage);
            }
            else
            {
                throw new PMAPITokenException(restResponse.ErrorMessage);
            }

            var data = response.Data.response.data[0];
            string token = data.token;
            uint expiry = data.expiry;

            return new SuTToken(token, expiry);
        }
Example #4
-1
        /// <summary>
        /// Returns a Gene obj from specified gene ID, data is retrieved via Rest.
        /// </summary>
        /// <param name="geneID"></param>
        /// <returns></returns>
        public static SiteConf.Gene.Object GetGene(int geneID)
        {
            RestClient client = new RestClient(RestAPI.URL);
            client.AddHandler("application/json", new RestSharp.Deserializers.JsonDeserializer());
            client.Proxy = _proxy;

            // setup request params
            RestRequest request = RestRequest(Method.GET, SiteConf.Model.gene);
            request.AddParameter("ID", geneID.ToString());
            
            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception("Could not get resource from REST service.");

            // Deserialize json object
            RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();
            List<SiteConf.Gene.RootObject> resultList = deserial.Deserialize<List<SiteConf.Gene.RootObject>>(response);

            if (resultList.Count != 1)
                throw new Exception("Error!!!");

            return resultList[0].objects[0];
        }
Example #5
-1
 private MailgunResponse DeserializeJsonResponse(IRestResponse response)
 {
     RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();
     return deserial.Deserialize<MailgunResponse>(response);
 }
 private void ValidateResponse(IRestResponse Response, HttpStatusCode SuccessCode)
 {
     //make sure status code is the one we wants.
     if (Response.StatusCode != SuccessCode)
     {
         //check for specific status codes.
         if (Response.StatusCode == HttpStatusCode.PaymentRequired)
         {
             throw new ApplicationException("This feature requires a payment plan.");
         }
         if (Response.StatusCode == HttpStatusCode.Conflict)
         {
             throw new ApplicationException("A 'conflict' status code has been returned. This can happen when trying to cancel a failed job.");
         }
         else if (!string.IsNullOrEmpty(Response.Content) && Response.Content.Trim().Length > 0)
         {
             //parse error messages.
             var json = new RestSharp.Deserializers.JsonDeserializer { RootElement = "errors" };
             var errors = json.Deserialize<List<string>>(new RestResponse { Content = Response.Content });
             if (errors.Count > 0)
             {
                 string error = errors.First();
                 //improve some of the error messages.
                 if (error == "invalid api_key")
                 {
                     error = "Zencoder return the error 'invalid api_key'. If you're sure you have the correct Api Key this can indicate a malformed json request.";
                 }
                 else if (errors.Count > 1)
                 {
                     for (int xx = 1; xx < errors.Count; xx++)
                     {
                         error += Environment.NewLine + errors[xx];
                     }
                 }
                 throw new ApplicationException(error);
             }
             else
             {
                 throw new ApplicationException("An unknown error has occurred.");
             }
         }
         else
         {
             throw new ApplicationException("An unknown error has occurred.");
         }
     }
 }
        protected override bool ShouldStartLoad(NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            var url = request.Url;
            if(url.Scheme.Equals("app")) {
                var func = url.Host;
                if(func.Equals("comment")) {
                    var r = new RestSharp.Deserializers.JsonDeserializer().Deserialize<CreateChangesetCommentModel>(new RestSharp.RestResponse { Content = Decode(url.Fragment) });
                    AddComment(r);
                    return false;
                }
            }

            return base.ShouldStartLoad(request, navigationType);
        }
Example #8
-1
        /// <summary>
        /// Try to download incidents from the server.
        /// </summary>
        /// <param name="deployment"></param>
        public void DownloadIncidents(Deployments deployment)
        {
            var restClient = new RestClient(deployment.url + "/api?task=incidents&by=all&limit=100");
            var request = new RestRequest(Method.GET);
            //request.AddParameter("by", "all");
            //request.AddParameter("limit", "100");
            restClient.ExecuteAsync(request, response =>
             {

                 if (response.Content.Trim() == string.Empty)
                 {
                     DataDownloadComplete.Invoke(this, new DownloadCompleteArgs()
                     {
                         DownloadObject = new List<Incident>(),
                         Response = response

                     });
                 }
                 else
                 {

                     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject));
                     RootObject root;
                     using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(response.Content)))
                     {
                         root = serializer.ReadObject(stream) as RootObject;
                     }

                     if (root.payload == null)
                     {
                         RestSharp.Deserializers.JsonDeserializer dj = new RestSharp.Deserializers.JsonDeserializer();
                         Error requestError = dj.Deserialize<Error>(response);
                         DataDownloadCompleteWithError.Invoke(this, new DownloadCompleteArgs()
                         {
                             DownloadObject = requestError,
                             Response = response

                         });

                     }
                     else
                     {
                         DataDownloadComplete.Invoke(this, new DownloadCompleteArgs()
                         {
                             DownloadObject = root.payload.incidents,
                             Response = response

                         });
                     }
                 }

             });
        }
Example #9
-1
        private static void _CheckIfNeedUpdate()
        {
            String serverAddress = "http://192.168.1.161:8000/";
            //String serverAddress = "https://securebox.io/";
            var client = new RestClient(serverAddress);
            var request = new RestRequest("check-update/", Method.POST);
            var uniqueId = Securebox.GetUniqueSystemIdentifier();
            var currentSecureboxVersion = Securebox.GetVersion();
            request.AddParameter("os", "windows");
            request.AddParameter("uuid", uniqueId);
            request.AddParameter("current_version", currentSecureboxVersion);
            string osVersion = Environment.OSVersion.ToString();
            request.AddParameter("os_version", osVersion); 
            IRestResponse<MyToken> response = client.Execute<MyToken>(request);

            try
            {
                //var token = response.Content.ToString();
                RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();
                MyToken token = deserial.Deserialize<MyToken>(response);  
                if ( token != null )
                {
                    String updateURL = token.Url;
                    if( currentSecureboxVersion != token.Version )
                    {
                        Securebox._getUpdate(serverAddress + updateURL);
                    }
                    
                }
                else
                {
                    throw new HttpException(404, "Are you sure you're in the right place?");
                }
            }
            catch(Exception ex)
            {
                Trace.TraceError(ex.Message);
            }
        }
Example #10
-1
        /// <summary>
        /// Returns a list of Upload obj where DataSourceType is Spreadsheet, data is retrieved via Rest.
        /// </summary>
        /// <param name="OrgHashCode"></param>
        /// <returns></returns>
        public static List<SiteConf.Upload.Object> GetSpreadSheetUploadList(string OrgHashCode)
        {
            RestClient client = new RestClient(RestAPI.URL);
            client.AddHandler("application/json", new RestSharp.Deserializers.JsonDeserializer());
            client.Proxy = _proxy;

            // setup request params
            RestRequest request = RestRequest(Method.GET, SiteConf.Model.upload);
            request.AddParameter("DataSourceType", SiteConf.DataSourceType.Spreadsheet);
            request.AddParameter("orgsite__OrgHashCode", OrgHashCode);

            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception("Could not get resource from REST service.");

            // Deserialize json object
            RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();
            List<SiteConf.Upload.RootObject> resultList = deserial.Deserialize<List<SiteConf.Upload.RootObject>>(response);

            if (resultList.Count != 1)
                throw new Exception("Error!!!");

            return resultList[0].objects;
        }
Example #11
-1
        /// <summary>
        /// Returns a OrgSite obj from specified OrgHashCode, data is retrieved via Rest.
        /// </summary>
        /// <param name="ParamName"></param>
        /// <param name="ParamValue"></param>
        /// <returns></returns>
        public static SiteConf.OrgSite.Object GetOrgSite(string paramName, string paramValue)
        {
            RestClient client = new RestClient(RestAPI.URL);
            client.AddHandler("application/json", new RestSharp.Deserializers.JsonDeserializer());
            client.Proxy = _proxy;

            // setup request params
            RestRequest request = RestRequest(Method.GET, SiteConf.Model.orgsite);
            //request.AddParameter("OrgHashCode", OrgHashCode);
            request.AddParameter(paramName, paramValue);

            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception("Could not get resource from REST service.");
                
            // Deserialize json object
            RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer();
            List<SiteConf.OrgSite.RootObject> resultList = deserial.Deserialize<List<SiteConf.OrgSite.RootObject>>(response);
            
            if (resultList.Count != 1)
                throw new Exception("Error!!!");

            if (resultList[0].objects.Count < 1)
                return null;
            
            return resultList[0].objects[0];
        }
Example #12
-2
        public void Load()
        {
            var json = "{\"id\":\"[13]\", \"value\": [true]}";

            // load the defaults
            // load user settings
            var ds = new RestSharp.Deserializers.JsonDeserializer();
            var jss = new JavaScriptSerializer();
            var table = jss.Deserialize<Dictionary<string, List<object>>>(json);
        }