public RestSession GetSession(
            RestRequest request, 
            out bool newSession)
        {
            Cookie sessionCookie = request.Cookies[SESSION_KEY];
            string sessionId = "";
            RestSession session = null;

            if (sessionCookie != null)
            {
                sessionId = sessionCookie.Value;
                newSession = false;
            }
            else
            {
                sessionId = GenerateNewSessionKey();
                newSession = true;
            }

            if (!m_sessions.TryGetValue(sessionId, out session))
            {
                // TODO: What about expiring old sessions?
                session = new RestSession(sessionId);
                m_sessions.Add(sessionId, session);
            }

            return session;
        }
Example #2
1
        public void Cannot_Set_Invalid_Host_Header(string value)
        {
            RestRequest request = new RestRequest();
            ArgumentException exception = Assert.Throws<ArgumentException>(() => request.AddHeader("Host", value));

            Assert.AreEqual("value", exception.ParamName);
        }
Example #3
0
        public void InvokeAsyncMethodWithGetRequest()
        {
            //Arrange
            RestInvoker target = new RestInvoker();
            StubModule.HaltProcessing = TimeSpan.FromSeconds(0);
            StubModule.GetPerson = false;
            StubModule.TestHarness = new List<Person> { new Person { Id = 1, Email = "*****@*****.**" } };

            RestRequest request = new RestRequest(HttpMethod.GET, new RestUri(_MyUri, "/Person/{id}").SetParameter("id", "1"));

            //Act
            target.InvokeAsync(request).ContinueWith(task =>
            {
                using (var actual = task.Result)
                {
                    //Assert
                    Assert.True(StubModule.GetPerson);
                    Assert.True(actual.IsSuccessStatusCode);
                    Assert.NotNull(actual);

                    string content = actual.Body.ReadAsString();

                    Assert.Equal("{\"Id\":1,\"UID\":\"00000000-0000-0000-0000-000000000000\",\"Email\":\"[email protected]\",\"NoOfSiblings\":0,\"DOB\":\"\\/Date(-59011459200000)\\/\",\"IsActive\":false,\"Salary\":0}", content);
                }

            }).Wait();

        }
Example #4
0
 public void Handles_Non_Existent_Domain()
 {
     var client = new RestClient("http://nonexistantdomainimguessing.org");
     var request = new RestRequest("foo");
     var response = client.Execute(request);
     Assert.Equal(ResponseStatus.Error, response.ResponseStatus);
 }
Example #5
0
        public void Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler()
        {
            const string baseUrl = "http://localhost:8080/";
            const string ExceptionMessage = "Thrown from OnBeforeDeserialization";

            using (SimpleServer.Create(baseUrl, Handlers.Generic<ResponseHandler>()))
            {
                var client = new RestClient(baseUrl);
                var request = new RestRequest("success");
                request.OnBeforeDeserialization += response =>
                                                   {
                                                       throw new Exception(ExceptionMessage);
                                                   };

                var task = client.ExecuteTaskAsync<Response>(request);

                try
                {
                    // In the broken version of the code, an exception thrown in OnBeforeDeserialization causes the task to
                    // never complete. In order to test that condition, we'll wait for 5 seconds for the task to complete.
                    // Since we're connecting to a local server, if the task hasn't completed in 5 seconds, it's safe to assume
                    // that it will never complete.
                    Assert.True(task.Wait(TimeSpan.FromSeconds(5)), "It looks like the async task is stuck and is never going to complete.");
                }
                catch (AggregateException e)
                {
                    Assert.Equal(1, e.InnerExceptions.Count);
                    Assert.Equal(ExceptionMessage, e.InnerExceptions.First().Message);
                    return;
                }

                Assert.True(false, "The exception thrown from OnBeforeDeserialization should have bubbled up.");
            }
        }
Example #6
0
        public void Writes_Response_To_Stream()
        {
            const string baseUrl = "http://localhost:8888/";

            using (SimpleServer.Create(baseUrl, Handlers.FileHandler))
            {
                string tempFile = Path.GetTempFileName();

                using (var writer = File.OpenWrite(tempFile))
                {
                    var client = new RestClient(baseUrl);
                    var request = new RestRequest("Assets/Koala.jpg");

                    request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);

                    var response = client.DownloadData(request);

                    Assert.Null(response);
                }

                var fromTemp = File.ReadAllBytes(tempFile);
                var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg");

                Assert.Equal(expected, fromTemp);
            }
        }
        public async Task TestMultipleRequests(Type factoryType)
        {
            using (var client = new RestClient("http://httpbin.org/")
            {
                HttpClientFactory = CreateClientFactory(factoryType, false),
            })
            {
                {
                    var request = new RestRequest("post", Method.POST);
                    request.AddParameter("param1", "param1");

                    var response = await client.Execute<HttpBinResponse>(request);
                    Assert.NotNull(response.Data);
                    Assert.NotNull(response.Data.Form);
                    Assert.True(response.Data.Form.ContainsKey("param1"));
                    Assert.Equal("param1", response.Data.Form["param1"]);
                }

                {
                    var request = new RestRequest("post", Method.POST);
                    request.AddParameter("param1", "param1+");

                    var response = await client.Execute<HttpBinResponse>(request);
                    Assert.NotNull(response.Data);
                    Assert.NotNull(response.Data.Form);
                    Assert.True(response.Data.Form.ContainsKey("param1"));
                    Assert.Equal("param1+", response.Data.Form["param1"]);
                }
            }
        }
        public void Handles_Server_Timeout_Error_Async()
        {
            const string baseUrl = "http://localhost:8888/";
            var resetEvent = new ManualResetEvent(false);

            using (SimpleServer.Create(baseUrl, TimeoutHandler))
            {
                var client = new RestClient(baseUrl);
                var request = new RestRequest("404") { Timeout = 500 };
                IRestResponse response = null;

                client.ExecuteAsync(request, responseCb =>
                                             {
                                                 response = responseCb;
                                                 resetEvent.Set();
                                             });

                resetEvent.WaitOne();

                Assert.NotNull(response);
                Assert.Equal(response.ResponseStatus, ResponseStatus.TimedOut);
                Assert.NotNull(response.ErrorException);
                Assert.IsAssignableFrom(typeof(WebException), response.ErrorException);
                Assert.Equal(response.ErrorException.Message, "The request timed-out.");
            }
        }
Example #9
0
        private async Task<Application> AddApplicationAsyncInternal(string friendlyName, ApplicationOptions options)
		{
			var request = new RestRequest();
            request.Method = Method.POST;
			request.Resource = "Accounts/{AccountSid}/Applications.json";
			
			Require.Argument("FriendlyName", friendlyName);
			Validate.IsValidLength(friendlyName, 64);
			request.AddParameter("FriendlyName", friendlyName);

			// some check for null. in those cases an empty string is a valid value (to remove a URL assignment)
			if (options != null)
			{
				if (options.VoiceUrl != null) request.AddParameter("VoiceUrl", options.VoiceUrl);
				if (options.VoiceMethod.HasValue()) request.AddParameter("VoiceMethod", options.VoiceMethod.ToString());
				if (options.VoiceFallbackUrl != null) request.AddParameter("VoiceFallbackUrl", options.VoiceFallbackUrl);
				if (options.VoiceFallbackMethod.HasValue()) request.AddParameter("VoiceFallbackMethod", options.VoiceFallbackMethod.ToString());
				if (options.VoiceCallerIdLookup.HasValue) request.AddParameter("VoiceCallerIdLookup", options.VoiceCallerIdLookup.Value);
				if (options.StatusCallback.HasValue()) request.AddParameter("StatusCallback", options.StatusCallback);
				if (options.StatusCallbackMethod.HasValue()) request.AddParameter("StatusCallbackMethod", options.StatusCallbackMethod.ToString());
				if (options.SmsUrl != null) request.AddParameter("SmsUrl", options.SmsUrl);
				if (options.SmsMethod.HasValue()) request.AddParameter("SmsMethod", options.SmsMethod.ToString());
				if (options.SmsFallbackUrl != null) request.AddParameter("SmsFallbackUrl", options.SmsFallbackUrl);
				if (options.SmsFallbackMethod.HasValue()) request.AddParameter("SmsFallbackMethod", options.SmsFallbackMethod.ToString());
			}

            var result = await ExecuteAsync(request, typeof(Application));
            return (Application)result;
		}
Example #10
0
        public void Can_Perform_GET_Async()
        {
            const string baseUrl = "http://localhost:8084/";
            const string val = "Basic async test";

            var resetEvent = new ManualResetEvent(false);

            using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val)))
            {
                var client = new RestClient(baseUrl);
                var request = new RestRequest("");
                IRestResponse response = null;

                client.ExecuteAsync(request, (resp, asyncHandle) =>
                {
                    response = resp;
                    resetEvent.Set();
                });

                resetEvent.WaitOne();

                Assert.NotNull(response.Content);
                Assert.Equal(val, response.Content);
            }
        }
        public void MultipartFormData_WithParameterAndFile()
        {
            const string baseUrl = "http://localhost:8888/";

            using (SimpleServer.Create(baseUrl, EchoHandler))
            {
                RestClient client = new RestClient(baseUrl);
                RestRequest request = new RestRequest("/", Method.POST)
                                      {
                                          AlwaysMultipartFormData = true
                                      };
                DirectoryInfo directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory())
                                                       .Parent;

                if (directoryInfo != null)
                {
                    string path = Path.Combine(directoryInfo.FullName, "Assets\\TestFile.txt");

                    request.AddFile("fileName", path);
                }

                request.AddParameter("controlName", "test", "application/json", ParameterType.RequestBody);

                IRestResponse response = client.Execute(request);

                Assert.AreEqual(this.expectedFileAndBodyRequestContent, response.Content);
            }
        }
Example #12
0
        public void Cannot_Set_Empty_Host_Header()
        {
            var request = new RestRequest();
            var exception = Assert.Throws<ArgumentException>(() => request.AddHeader("Host", string.Empty));

            Assert.AreEqual("value", exception.ParamName);
        }
Example #13
0
        public async Task MultipleRequestsFromSameClientShouldNotFail()
        {
            // Setup
            var client = new RestClient { BaseUrl = BaseAddress };
            var request = new RestRequest("api/books");
            List<Book> response;

            // Execute
            using (WebApp.Start<WebApiStartup>(BaseAddress))
            {
                response = await client.ExecuteAsync<List<Book>>(request);
            }

            // Validate
            response.Should().NotBeNull();
            response.Count().Should().Be(5);

            var request2 = new RestRequest("api/books");
            List<Book> response2;

            // Execute
            using (WebApp.Start<WebApiStartup>(BaseAddress))
            {
                response2 = await client.ExecuteAsync<List<Book>>(request2);
            }

            // Validate
            response2.Should().NotBeNull();
            response2.Count().Should().Be(5);
        }
    /// <summary>
    /// Retrieves a new token from Webtrends auth service
    /// </summary>
    public string Execute()
    {
        var builder = new JWTBuilder();
        var header = new JWTHeader
        {
            Type = "JWT",
            Algorithm = "HS256"
        };
        var claimSet = new JWTClaimSet
        {
            Issuer = clientId,
            Principal = clientId,
            Audience = audience,
            Expiration = DateTime.Now.ToUniversalTime().AddSeconds(30),
            Scope = scope
        };

        string assertion = builder.BuildAssertion(header, claimSet, clientSecret);
        var client = new RestClient(authUrl);
        var request = new RestRequest("token/", Method.POST);
        request.AddParameter("client_id", clientId);
        request.AddParameter("client_assertion", assertion);
        request.AddParameter("grant_type", "client_credentials");
        request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");

        var response = client.Execute(request).Content;
        return (string)JObject.Parse(response)["access_token"];
    }
Example #15
0
        public static RestRequest DelegateWith(RestClient client, RestRequest request)
        {
            if(request == null)
            {
                throw new ArgumentNullException("request");
            }

            if(!request.Method.HasValue)
            {
                throw new ArgumentException("Request must specify a web method.");
            }

            var method = request.Method.Value;
            var credentials = (OAuthCredentials)request.Credentials;
            var url = request.BuildEndpoint(client).ToString();
            var workflow = new OAuthWorkflow(credentials);
            var uri = new Uri(client.Authority);
            var realm = uri.Host;
            var enableTrace = client.TraceEnabled || request.TraceEnabled;

            var info = workflow.BuildProtectedResourceInfo(method, request.GetAllHeaders(), url);
            var query = credentials.GetQueryFor(url, request, info, method, enableTrace);
            ((OAuthWebQuery) query).Realm = realm;
            var auth = query.GetAuthorizationContent();

            var echo = new RestRequest();
            echo.AddHeader("X-Auth-Service-Provider", url);
            echo.AddHeader("X-Verify-Credentials-Authorization", auth);
            return echo;
        }
Example #16
0
        public void GetAborted()
        {
            //Arrange
            StubModule.HaltProcessing = TimeSpan.FromMilliseconds(1000);
            StubModule.GetPerson = false;
            StubModule.TestHarness = new List<Person> { new Person { Id = 1, Email = "*****@*****.**" } };

            RestRequest target = new RestRequest(HttpMethod.GET, new RestUri(_MyUri, "/Person/{id}").SetParameter("id", "1"));

            //Act
            RestResponse response = null;
            //A completely synchronous GetResponse cannot be aborted.
            //So, spining off a new thread.. And balancing the times between GetResponse() and Abort() methods.
            var task = Task.Factory.StartNew(() =>
            {
                response = target.GetResponse();
            });
            Thread.Sleep(500);
            target.Abort();
            task.Wait();

            //Assert
            Assert.NotNull(response);
            Assert.NotNull(response.Error);
            Assert.Equal("The request was aborted: The request was canceled.", response.Error.InnerException.Message);
            Assert.Equal(0, (int)response.Error.StatusCode);
        }
Example #17
0
        public void BuildResourceUriWhereResourceUriIsNull()
        {
            var request = new RestRequest();

            Assert.AreEqual("https://www.googleapis.com/discovery/v1/apis?&name=adexchangebuyer", 
                request.GetResourceUri("https://www.googleapis.com/discovery/v1/apis?&name=adexchangebuyer").ToString());
        }
        public void Task_Handles_Non_Existent_Domain()
        {
            var client = new RestClient("http://192.168.1.200:8001");
            var request = new RestRequest("/")
            {
                RequestFormat = DataFormat.Json,
                Method = Method.GET
            };

            AggregateException agg = Assert.Throws<AggregateException>(
                delegate
                {
                    var response = client.ExecuteTaskAsync<StupidClass>(request);

                    response.Wait();
                });

            Assert.IsType(typeof(WebException), agg.InnerException);
            Assert.Equal("Unable to connect to the remote server", agg.InnerException.Message);

            //var client = new RestClient("http://nonexistantdomainimguessing.org");
            //var request = new RestRequest("foo");
            //var response = client.ExecuteTaskAsync(request);

            //Assert.Equal(ResponseStatus.Error, response.Result.ResponseStatus);
        }
Example #19
0
        public void Handles_Different_Root_Element_On_Http_Error()
        {
            Uri baseUrl = new Uri("http://localhost:8888/");

            using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic<ResponseHandler>()))
            {
                RestClient client = new RestClient(baseUrl);
                RestRequest request = new RestRequest("error")
                                      {
                                          RootElement = "Success"
                                      };

                request.OnBeforeDeserialization = resp =>
                                                  {
                                                      if (resp.StatusCode == HttpStatusCode.BadRequest)
                                                      {
                                                          request.RootElement = "Error";
                                                      }
                                                  };

                IRestResponse<Response> response = client.Execute<Response>(request);

                Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
                Assert.AreEqual("Not found!", response.Data.Message);
            }
        }
Example #20
0
 public void Can_Handle_Uncompressed_Content()
 {
     var client = new RestClient(BaseUrl);
     var request = new RestRequest("Compression/None");
     var response = client.Execute(request);
     Assert.Equal("This content is uncompressed!", response.Content);
 }
Example #21
0
 public void Handles_GET_Request_404_Error()
 {
     var client = new RestClient(BaseUrl);
     var request = new RestRequest("StatusCode/404");
     var response = client.Execute(request);
     Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
 }
Example #22
0
 public void ShouldParseOutRangeSpecifier()
 {
     var restClient = new RestClient("http://localhost");
     var req = new RestRequest("bob", Method.GET);
     
     req.AddHeader("Range", "pages=1-2");
     var resp = restClient.Execute(req);
 }
Example #23
0
        private async Task<Account> GetAccountAsyncInternal()
		{
			var request = new RestRequest();
			request.Resource = "Accounts/{AccountSid}.json";

            var result = await ExecuteAsync(request, typeof(Account));
            return (Account)result;
		}
Example #24
0
        private async Task<AccountResult> ListSubAccountsAsyncInternal()
		{
			var request = new RestRequest();
			request.Resource = "Accounts.json";

            var result = await ExecuteAsync(request, typeof(AccountResult));
            return (AccountResult)result;
        }
Example #25
0
        public void BuildResourceUriWhereBaseUriHasMultiplePathSegments()
        {
            var request = new RestRequest("apis");

            request.AddQueryString("name", "adexchangebuyer");

            Assert.AreEqual("https://www.googleapis.com/discovery/v1/apis?&name=adexchangebuyer", request.GetResourceUri("https://www.googleapis.com/discovery/v1").ToString());
        }
Example #26
0
 public void CheckMessageBodyXmlWithAttributes()
 {
     var request = new RestRequest("/test?test1={test1}", HttpMethod.Get) {ContentType = ContentTypes.Xml};
     request.AddParameter(new PhoneNumber("1", "514-9700"));
     var body = request.GetRequestBody();
     Assert.IsNotNull(body);
     Assert.AreEqual("<PhoneNumber ID=\"1\">\r\n  <Call />\r\n  <Calls />\r\n  <Number>514-9700</Number>\r\n</PhoneNumber>", body);
 }
Example #27
0
        private async Task<CallResult> ListCallsAsyncInternal()
        {
            var request = new RestRequest();
            request.Resource = "Accounts/{AccountSid}/Calls.json";

            var result = await ExecuteAsync(request, typeof(CallResult));
            return (CallResult)result;
        }
Example #28
0
        public void Can_Handle_Gzip_Compressed_Content()
        {
            var client = new RestClient(BaseUrl);
            var request = new RestRequest("Compression/GZip");
            var response = client.Execute(request);

            Assert.Equal("This content is compressed with GZip!", response.Content);
        }
 /// <summary>
 /// Gets a list of APIs that are available from Google to develop against.
 /// </summary>
 /// <returns>An ApiResult object containing the APIs available from Google.</returns>
 public async Task<string> GetApisRaw(string name = "")
 {
     var request = new RestRequest("apis") {  };
     if (!string.IsNullOrWhiteSpace(name))
     {
         request.AddQueryString("name", name);
     }
     return await ExecuteAsync<string>(request);
 }
        private async Task<OutgoingCallerId> GetOutgoingCallerIdAsyncInternal(string outgoingCallerIdSid)
        {
            var request = new RestRequest();
            request.Resource = "Accounts/{AccountSid}/OutgoingCallerIds/{OutgoingCallerIdSid}.json";
            request.AddParameter("OutgoingCallerIdSid", outgoingCallerIdSid, ParameterType.UrlSegment);

            var result = await ExecuteAsync(request, typeof(OutgoingCallerId));
            return (OutgoingCallerId)result;
        }
Example #31
0
        public async Task Hue(CommandContext ctx, string para1, string para2 = "", string para3 = "")
        {
            var jsonString = string.Empty;

            using (var fs = File.OpenRead("HueConfig.json"))
                using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                    jsonString = await sr.ReadToEndAsync().ConfigureAwait(false);

            var hueConfigJson = JsonConvert.DeserializeObject <HueConfigJson>(jsonString);

            string ip       = hueConfigJson.Ip;
            string username = hueConfigJson.Token;
            string baseUrl  = "http://" + ip + "/api/" + username;

            switch (para1)
            {
            case "status":
                var client = new RestClient(baseUrl + "/lights");
                client.Timeout = -1;
                var           request    = new RestRequest(Method.GET);
                IRestResponse response   = client.Execute(request);
                dynamic       jsonResult = JsonConvert.DeserializeObject(response.Content);
                string        message    = "Aangesloten lampen \n \n";
                foreach (var lampItem in jsonResult)
                {
                    string lampId = ((JToken)lampItem).Path;
                    foreach (var realLampItem in lampItem)
                    {
                        string status     = "Geen idee";
                        bool   lampStatus = realLampItem.state.on;

                        if (lampStatus)
                        {
                            status = ":white_check_mark:";
                        }
                        else
                        {
                            status = ":negative_squared_cross_mark:";
                        }

                        message += "Lamp naam: " + realLampItem.name + ", ID: " + lampId + ", status: " + status + "\n";
                    }
                }
                await ctx.Channel.SendMessageAsync(message).ConfigureAwait(false);

                break;

            case "lamp":
                string lamp          = para2;
                string setLampStatus = "false";

                if (para3 == "aan")
                {
                    setLampStatus = "true";
                }

                string json = "{\"on\":" + setLampStatus + "}";

                var lampClient = new RestClient(baseUrl + "/lights/" + lamp + "/state");
                lampClient.Timeout = -1;
                var lampRequest = new RestRequest(Method.PUT);
                lampRequest.AddParameter("application/json", json, ParameterType.RequestBody);
                IRestResponse lampResponse = lampClient.Execute(lampRequest);

                await ctx.Channel.SendMessageAsync("Lamp " + para2 + " staat nu " + para3).ConfigureAwait(false);

                break;

            case "lampen":
                string setLampenStatus = "true";

                if (para2 == "zwart")
                {
                    setLampenStatus = "false";
                }

                if (para2 == "uit")
                {
                    setLampenStatus = "false";
                }

                var lampenClient = new RestClient(baseUrl + "/lights");
                lampenClient.Timeout = -1;
                var           lampenRequest    = new RestRequest(Method.GET);
                IRestResponse lampenResponse   = lampenClient.Execute(lampenRequest);
                dynamic       lampenJsonResult = JsonConvert.DeserializeObject(lampenResponse.Content);
                foreach (var lampItem in lampenJsonResult)
                {
                    string lampenJson = "{\"on\":" + setLampenStatus + "}";

                    if (GetHueStringToHueInt(para2) != 0)
                    {
                        lampenJson = "{\"on\":" + setLampenStatus + ",\"hue\":" + GetHueStringToHueInt(para2) + ",\"sat\":" + GetHueStringToSatInt(para2) + "}";
                    }
                    else
                    if (para2 == "disco")
                    {
                        lampenJson = "{\"on\":" + setLampenStatus + ",\"effect\":\"colorloop\"}";
                    }

                    var lampenLoopClient = new RestClient(baseUrl + "/lights/" + ((JToken)lampItem).Path + "/state");
                    lampenLoopClient.Timeout = -1;
                    var lampenLoopRequest = new RestRequest(Method.PUT);
                    lampenLoopRequest.AddParameter("application/json", lampenJson, ParameterType.RequestBody);
                    IRestResponse lampenLoopResponse = lampenLoopClient.Execute(lampenLoopRequest);
                }

                await ctx.Channel.SendMessageAsync("Alle lampen staan nu " + para2).ConfigureAwait(false);

                break;

            default:
                await ctx.Channel.SendMessageAsync("Jaja komt eraan").ConfigureAwait(false);

                break;
            }
        }
        public RestClientRequest CreateOrEditContactRestClientRequestObject(Contact contact)
        {
            if (contact.yearsOfExperience != null)
            {
                contact.yearsOfExperience = (decimal)contact.yearsOfExperience;
            }
            string  latitude                 = contact.latitude.HasValue ? "\r\n  \"latitude\": " + contact.latitude + "," : "\r\n  \"latitude\": null,";
            string  longitude                = contact.longitude.HasValue ? "\r\n  \"longitude\": " + contact.longitude + "," : "\r\n  \"longitude\": null,";
            string  companyId                = contact.companyId.HasValue ? "\r\n  \"companyId\": " + contact.companyId + "," : "\r\n  \"companyId\": null,";
            string  countryId                = contact.countryId.HasValue ? "\r\n  \"countryId\": " + contact.countryId + "," : "\r\n  \"countryId\": null,";
            string  stateId                  = contact.stateId.HasValue ? "\r\n  \"stateId\": " + contact.stateId + "," : "\r\n  \"stateId\": null,";
            string  cityId                   = contact.cityId.HasValue ? "\r\n  \"cityId\": " + contact.cityId + "," : "\r\n  \"cityId\": null,";
            string  ratingScaleId            = contact.ratingScaleId.HasValue ? "\r\n  \"ratingScaleId\": " + contact.ratingScaleId + "," : "\r\n  \"ratingScaleId\": null,";
            string  yearsOfExperiance        = contact.yearsOfExperience.HasValue ? "\r\n  \"yearsOfExperience\": " + contact.yearsOfExperience + "," : "\r\n  \"yearsOfExperience\": null,";
            string  contactDataSourceId      = contact.contactDataSourceId.HasValue ? "\r\n  \"contactDataSourceId\": " + contact.contactDataSourceId + "," : "\r\n  \"contactDataSourceId\": null,";
            string  binaryObjectId           = contact.binaryObjectId.HasValue ? "\r\n  \"binaryObjectId\": " + contact.binaryObjectId + "," : "\r\n  \"binaryObjectId\": null,";
            string  fileUploadBinaryObjectId = contact.fileUploadBinaryObjectId.HasValue ? "\r\n  \"fileUploadBinaryObjectId\": " + contact.fileUploadBinaryObjectId + "," : "\r\n  \"fileUploadBinaryObjectId\": null,";
            string  isWhatsAppNumber         = contact.isWhatsAppNumber ? "\r\n  \"isWhatsAppNumber\": 1," : "\r\n  \"isWhatsAppNumber\": 0,";
            string  isVerified               = contact.isVerified ? "\r\n  \"isVerified\": 1," : "\r\n  \"isVerified\": 0,";
            string  isActiveOrPassive        = contact.isActiveOrPassive ? "\r\n  \"isActiveOrPassive\": 1," : "\r\n  \"isActiveOrPassive\": 0,";
            string  isEmployee               = contact.isEmployee ? "\r\n  \"isEmployee\": 1," : "\r\n  \"isEmployee\": 0,";
            string  isArchive                = contact.isArchive ? "\r\n  \"isArchive\": 1," : "\r\n  \"isArchive\": 0,";
            decimal?expe = null;

            var client  = new RestClient(ApiUrl.CreateOrEditContact);
            var request = new RestRequest(Method.POST);

            request.AddHeader("postman-token", "14da01f8-c5ed-075a-09dc-8cc9cf8bb991");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            //string json = JsonConvert.SerializeObject(contact);
            //request.AddParameter("application/json", json);
            request.AddParameter("application/json", "{" +
                                 "\r\n  \"name\": \"" + contact.name + "\"," +
                                 "\r\n  \"firstName\": \"" + contact.firstName + "\"," +
                                 "\r\n  \"lastName\": \"" + contact.lastName + "\"," +
                                 "\r\n  \"customId\": \"" + contact.customId + "\"," +
                                 "\r\n  \"jobTitle\": \"" + contact.jobTitle + "\"," +
                                 "\r\n  \"employer\": \"" + contact.employer + "\"," +
                                 "\r\n  \"publicProfileUrl\": \"" + contact.publicProfileUrl + "\"," +
                                 "\r\n  \"mobile\": \"" + contact.mobile + "\"," +
                                 "" + isWhatsAppNumber + "" +
                                 "\r\n  \"personalEmailAddress\": \"" + contact.personalEmailAddress + "\"," +
                                 "\r\n  \"businessEmailAddress\": \"" + contact.businessEmailAddress + "\"," +
                                 "\r\n  \"officePhone\": \"" + contact.officePhone + "\"," +
                                 "\r\n  \"homePhone\": \"" + contact.homePhone + "\"," +
                                 "\r\n  \"fax\": \"" + contact.fax + "\"," +
                                 "\r\n  \"skype\": \"" + contact.skype + "\"," +
                                 "\r\n  \"fullAddressGoogleMap\": \"" + contact.fullAddressGoogleMap + "\"," +
                                 "" + latitude + "" +
                                 "" + longitude + "" +
                                 "\r\n  \"address1\": \"" + contact.address1 + "\"," +
                                 "\r\n  \"address2\": \"" + contact.address2 + "\"," +
                                 "\r\n  \"cityLocation\": \"" + contact.cityLocation + "\"," +
                                 "\r\n  \"linkedIn\": \"" + contact.linkedIn + "\"," +
                                 "\r\n  \"facebook\": \"" + contact.facebook + "\"," +
                                 "\r\n  \"twitter\": \"" + contact.twitter + "\"," +
                                 "\r\n  \"photoLink\": \"" + contact.photoLink + "\"," +
                                 "\r\n  \"adminNote\": \"" + contact.adminNote + "\"," +
                                 "\r\n  \"fullProfile\": \"" + contact.fullProfile + "\"," +
                                 //"\r\n  \"yearsOfExperience\": " + expe + "," +
                                 "" + yearsOfExperiance + "" +
                                 "\r\n  \"dateOfBirth\": \"" + contact.dateOfBirth + "\"," +
                                 "" + isVerified + "" +
                                 "\r\n  \"zipCode\": \"" + contact.zipCode + "\"," +
                                 "" + isActiveOrPassive + "" +
                                 "\r\n  \"profileSummary\": \"" + contact.profileSummary + "\"," +
                                 "" + isEmployee + "" +
                                 "\r\n  \"availableFromDate\": \"" + contact.availableFromDate + "\"," +
                                 "" + isArchive + "" +
                                 "" + companyId + "" +
                                 "" + countryId + "" +
                                 "" + stateId + "" +
                                 "" + cityId + "" +
                                 "" + ratingScaleId + "" +
                                 "" + contactDataSourceId + "" +
                                 //"" + binaryObjectId + "" +
                                 "" + fileUploadBinaryObjectId + "" +
                                 //"\r\n  \"x\": " + contact.x + "," +
                                 //"\r\n  \"y\": " + contact.y + "," +
                                 //"\r\n  \"width\": " + contact.width + "," +
                                 //"\r\n  \"height\": " + contact.height + "," +
                                 "\r\n  \"id\": " + contact.id + " \r\n}", ParameterType.RequestBody);
            //"{\r\n  \"name\": \"Dawie Pretorius\",\r\n  \"firstName\": \"Dawie\",\r\n  \"lastName\": \"Pretorius\",\r\n  \"customId\": \"D2118-10003\",\r\n  \"jobTitle\": \"Branch Manager\",\r\n  \"employer\": \"\",\r\n  \"publicProfileUrl\": \"\",\r\n  \"mobile\": \"0216921273\",\r\n  \"isWhatsAppNumber\": False,\r\n  \"personalEmailAddress\": \"\",\r\n  \"businessEmailAddress\": \"[email protected]\",\r\n  \"officePhone\": \"\",\r\n  \"homePhone\": \"\",\r\n  \"fax\": \"\",\r\n  \"skype\": \"\",\r\n  \"fullAddressGoogleMap\": \"\",\r\n  \"latitude\": ,\r\n  \"longitude\": ,\r\n  \"address1\": \"\",\r\n  \"address2\": \"\",\r\n  \"cityLocation\": \"\",\r\n  \"linkedIn\": \"\",\r\n  \"facebook\": \"\",\r\n  \"twitter\": \"\",\r\n  \"photoLink\": \"\",\r\n  \"adminNote\": \"\",\r\n  \"fullProfile\": \"\",\r\n  \"yearsOfExperience\": 3,\r\n  \"dateOfBirth\": \"\",\r\n  \"isVerified\": False,\r\n  \"zipCode\": \"\",\r\n  \"isActiveOrPassive\": False,\r\n  \"profileSummary\": \"\",\r\n  \"isEmployee\": True,\r\n  \"availableFromDate\": \"\",\r\n  \"isArchive\": False,\r\n  \"companyId\": ,\r\n  \"countryId\": 154,\r\n  \"stateId\": 543,\r\n  \"cityId\": 12169,\r\n  \"ratingScaleId\": ,\r\n  \"contactDataSourceId\": ,\r\n  \"binaryObjectId\": ceef91e3-4d3d-794c-a4be-39eb9027131c,\r\n  \"fileUploadBinaryObjectId\": ,\r\n  \"fileTokenPdf\": ,\r\n  \"fileToken\": ,\r\n  \"x\": 0,\r\n  \"y\": 0,\r\n  \"width\": 0,\r\n  \"height\": 0,\r\n  \"isDeleted\": False,\r\n  \"deleterUserId\": 0,\r\n  \"deletionTime\": \"\",\r\n  \"lastModificationTime\": \"1/23/2019 10:49:37 PM\",\r\n  \"lastModifierUserId\": 1,\r\n  \"creationTime\": \"12/21/2018 11:09:35 AM\",\r\n  \"creatorUserId\": 1,\r\n  \"id\": 10003\r\n}"
            //request.AddParameter("application/json", "{\r\n  \"name\": \"B.\",\r\n  \"firstName\": \"B. Smile\",\r\n  \"lastName\": \"Smith\",\r\n  \"jobTitle\": \"Branch Manager\",\r\n  \"mobile\": \"0832788095\",\r\n  \"personalEmailAddress\": \"[email protected]\",\r\n  \"businessEmailAddress\": \"[email protected]\",\r\n  \"officePhone\": \"01137516000\",\r\n  \"cityLocation\": \"Dhaka\",\r\n  \"yearsOfExperience\": "+expe+",\r\n  \"dateOfBirth\": \"2019-04-09T10:20:22.340Z\",\r\n  \"countryId\": 154,\r\n  \"stateId\": 536,\r\n  \"cityId\": null,\r\n  \"creatorUserId\": 1,\r\n  \"id\": " + contact.id + "}", ParameterType.RequestBody);
            return(new RestClientRequest()
            {
                client = client,
                request = request
            });
        }
Example #33
0
        public void Can_Authenticate_LinkedIN_With_OAuth()
        {
            const string consumerKey    = "TODO_CONSUMER_KEY_HERE";
            const string consumerSecret = "TODO_CONSUMER_SECRET_HERE";

            // request token
            var client = new RestClient
            {
                BaseUrl       = new Uri("https://api.linkedin.com/uas/oauth"),
                Authenticator = OAuth1Authenticator.ForRequestToken(
                    consumerKey, consumerSecret,
                    "http://localhost"
                    )
            };
            var requestTokenRequest  = new RestRequest("requestToken");
            var requestTokenResponse = client.Execute(requestTokenRequest);

            Assert.NotNull(requestTokenResponse);
            Assert.AreEqual(HttpStatusCode.OK, requestTokenResponse.StatusCode);

            var requestTokenResponseParameters = HttpUtility.ParseQueryString(requestTokenResponse.Content);
            var requestToken  = requestTokenResponseParameters["oauth_token"];
            var requestSecret = requestTokenResponseParameters["oauth_token_secret"];

            Assert.NotNull(requestToken);
            Assert.NotNull(requestSecret);

            // redirect user
            requestTokenRequest = new RestRequest("authenticate?oauth_token=" + requestToken);

            var redirectUri = client.BuildUri(requestTokenRequest);

            Process.Start(redirectUri.ToString());

            const string requestUrl = "TODO: put browser URL here";

            // replace this via the debugger with the return url from LinkedIN. Simply copy it from the opened browser

            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }

            Debugger.Break();

            // get the access token
            var requestTokenQueryParameters = HttpUtility.ParseQueryString(new Uri(requestUrl).Query);
            var requestVerifier             = requestTokenQueryParameters["oauth_verifier"];

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, requestToken, requestSecret, requestVerifier
                );

            var requestAccessTokenRequest  = new RestRequest("accessToken");
            var requestActionTokenResponse = client.Execute(requestAccessTokenRequest);

            Assert.NotNull(requestActionTokenResponse);
            Assert.AreEqual(HttpStatusCode.OK, requestActionTokenResponse.StatusCode);

            var requestActionTokenResponseParameters = HttpUtility.ParseQueryString(requestActionTokenResponse.Content);
            var accessToken  = requestActionTokenResponseParameters["oauth_token"];
            var accessSecret = requestActionTokenResponseParameters["oauth_token_secret"];

            Assert.NotNull(accessToken);
            Assert.NotNull(accessSecret);
        }
Example #34
0
        public void Can_Authenticate_With_OAuth()
        {
            const string consumerKey    = "";
            const string consumerSecret = "";

            var baseUrl = new Uri("https://api.twitter.com");

            var client = new RestClient(baseUrl)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
            };
            var request  = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var qs               = HttpUtility.ParseQueryString(response.Content);
            var oauthToken       = qs["oauth_token"];
            var oauthTokenSecret = qs["oauth_token_secret"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);

            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauthToken);

            var url = client.BuildUri(request).ToString();

            // Breakpoint here, open the URL from the url var in the browser
            // then set verifier in debugger to the value in the URL where you get redirected
            var verifier = "123456";

            request = new RestRequest("oauth/access_token", Method.POST);

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, oauthToken,
                oauthTokenSecret, verifier
                );
            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            qs               = HttpUtility.ParseQueryString(response.Content);
            oauthToken       = qs["oauth_token"];
            oauthTokenSecret = qs["oauth_token_secret"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);

            request = new RestRequest("/1.1/account/verify_credentials.json");

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                consumerKey, consumerSecret, oauthToken,
                oauthTokenSecret
                );

            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Example #35
0
        public void Can_Authenticate_Netflix_With_OAuth()
        {
            const string consumerKey    = "";
            const string consumerSecret = "";

            var baseUrl = new Uri("http://api.netflix.com");

            var client = new RestClient(baseUrl)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
            };
            var request  = new RestRequest("oauth/request_token");
            var response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var qs               = HttpUtility.ParseQueryString(response.Content);
            var oauthToken       = qs["oauth_token"];
            var oauthTokenSecret = qs["oauth_token_secret"];
            var applicationName  = qs["application_name"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);
            Assert.NotNull(applicationName);

            var baseSslUrl = new Uri("https://api-user.netflix.com");
            var sslClient  = new RestClient(baseSslUrl);

            request = new RestRequest("oauth/login");
            request.AddParameter("oauth_token", oauthToken);
            request.AddParameter("oauth_consumer_key", consumerKey);
            request.AddParameter("application_name", applicationName);

            var url = sslClient.BuildUri(request)
                      .ToString();

            Process.Start(url);

            request = new RestRequest("oauth/access_token"); // <-- Breakpoint here, login to netflix

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, oauthToken,
                oauthTokenSecret
                );
            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            qs               = HttpUtility.ParseQueryString(response.Content);
            oauthToken       = qs["oauth_token"];
            oauthTokenSecret = qs["oauth_token_secret"];

            var userId = qs["user_id"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);
            Assert.NotNull(userId);

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                consumerKey, consumerSecret, oauthToken,
                oauthTokenSecret
                );
            request = new RestRequest("users/{user_id}/queues/disc");
            request.AddUrlSegment("user_id", userId);
            request.AddParameter("max_results", "2");

            var queueResponse = client.Execute <Queue>(request);

            Assert.NotNull(queueResponse);
            Assert.AreEqual(HttpStatusCode.OK, queueResponse.StatusCode);
            Assert.NotNull(queueResponse.Data);
            Assert.AreEqual(2, queueResponse.Data.Items.Count);
        }
Example #36
0
        private ApiResponse <T> Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

            if (configuration.Proxy != null)
            {
                client.Proxy = configuration.Proxy;
            }

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            if (configuration.ClientCertificates != null)
            {
                client.ClientCertificates = configuration.ClientCertificates;
            }

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.RetryPolicy != null)
            {
                var policy       = RetryConfiguration.RetryPolicy;
                var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = client.Execute <T>(req);
            }

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                try
                {
                    response.Data = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
                }
                catch (Exception ex)
                {
                    throw ex.InnerException != null ? ex.InnerException : ex;
                }
            }
            else if (typeof(T).Name == "Stream") // for binary response
            {
                response.Data = (T)(object)new MemoryStream(response.RawBytes);
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Example #37
0
 private void AttachTokenAuth(RestRequest request)
 {
     request.AddHeader("Authorization", $"Token {_token}");
 }
Example #38
0
        /// <summary>
        /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
        /// At this point, all information for querying the service is known. Here, it is simply
        /// mapped into the RestSharp request.
        /// </summary>
        /// <param name="method">The http verb.</param>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new RestRequest instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private RestRequest NewRequest(
            HttpMethod method,
            String path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            RestRequest request = new RestRequest(Method(method))
            {
                Resource       = path,
                JsonSerializer = new CustomJsonCodec(configuration)
            };

            if (options.PathParameters != null)
            {
                foreach (var pathParam in options.PathParameters)
                {
                    request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
                }
            }

            if (options.QueryParameters != null)
            {
                foreach (var queryParam in options.QueryParameters)
                {
                    foreach (var value in queryParam.Value)
                    {
                        request.AddQueryParameter(queryParam.Key, value);
                    }
                }
            }

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    request.AddHeader(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        request.AddHeader(headerParam.Key, value);
                    }
                }
            }

            if (options.FormParameters != null)
            {
                foreach (var formParam in options.FormParameters)
                {
                    request.AddParameter(formParam.Key, formParam.Value);
                }
            }

            if (options.Data != null)
            {
                if (options.HeaderParameters != null)
                {
                    var contentTypes = options.HeaderParameters["Content-Type"];
                    if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
                    {
                        request.RequestFormat = DataFormat.Json;
                    }
                    else
                    {
                        // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
                    }
                }
                else
                {
                    // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
                    request.RequestFormat = DataFormat.Json;
                }

                request.AddJsonBody(options.Data);
            }

            if (options.FileParameters != null)
            {
                foreach (var fileParam in options.FileParameters)
                {
                    var bytes      = ClientUtils.ReadAsBytes(fileParam.Value);
                    var fileStream = fileParam.Value as FileStream;
                    if (fileStream != null)
                    {
                        request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)));
                    }
                    else
                    {
                        request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided"));
                    }
                }
            }

            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                foreach (var cookie in options.Cookies)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }
            }

            return(request);
        }
Example #39
0
        private async Task <ApiResponse <T> > ExecAsync <T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            if (configuration.ClientCertificates != null)
            {
                client.ClientCertificates = configuration.ClientCertificates;
            }

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.AsyncRetryPolicy != null)
            {
                var policy       = RetryConfiguration.AsyncRetryPolicy;
                var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false);

                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = await client.ExecuteAsync <T>(req, cancellationToken).ConfigureAwait(false);
            }

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                T          instance = (T)Activator.CreateInstance(typeof(T));
                MethodInfo method   = typeof(T).GetMethod("FromJson");
                method.Invoke(instance, new object[] { response.Content });
                response.Data = instance;
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Example #40
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Connecting to teamviewer web api ...");
                RestClient client = new RestClient(Properties.Settings.Default.BaseUrl);

                Console.WriteLine("Getting device list...");
                RestRequest requestDevices = new RestRequest(Properties.Settings.Default.DevicesUrlPart, Method.GET);
                requestDevices.AddHeader("Authorization", string.Format("Bearer {0}", Properties.Settings.Default.AuthorizationToken));
                IRestResponse <TeamviewerExporter.Devices> responseDevices = client.Execute <TeamviewerExporter.Devices>(requestDevices);

                Console.WriteLine("Getting groups list...");
                RestRequest requestGroups = new RestRequest(Properties.Settings.Default.GroupsUrlPart, Method.GET);
                requestGroups.AddHeader("Authorization", string.Format("Bearer {0}", Properties.Settings.Default.AuthorizationToken));
                IRestResponse <Groups> responseGroups = client.Execute <Groups>(requestGroups);

                Console.WriteLine(string.Format("Got {0} entries and {1} groups.", responseDevices.Data.devices.Count, responseGroups.Data.groups.Count));

                Console.WriteLine("Adding information to original entries...");

                for (int i = 0; i < responseDevices.Data.devices.Count; i++)
                {
                    // set cleaned teamviewer id
                    if (char.IsLetter(responseDevices.Data.devices[i].remotecontrol_id[0]))
                    {
                        responseDevices.Data.devices[i].remotecontrol_id_clean = responseDevices.Data.devices[i].remotecontrol_id.Substring(1);
                    }
                    else
                    {
                        responseDevices.Data.devices[i].remotecontrol_id_clean = responseDevices.Data.devices[i].remotecontrol_id;
                    }

                    // write group name
                    Group inGroup = responseGroups.Data.groups.FirstOrDefault(w => w.id == responseDevices.Data.devices[i].groupid);
                    if (inGroup != null)
                    {
                        responseDevices.Data.devices[i].groupname = inGroup.name;
                    }
                }

                Console.WriteLine("Writing json object to csv file 'original.csv'");
                //TextWriter tw = File.CreateText("original.csv");

                TextWriter tw = new StreamWriter("original.csv", false, Encoding.UTF8);

                CsvWriter csv = new CsvWriter(tw);
                csv.WriteRecords(responseDevices.Data.devices);
                csv.Dispose();

                Console.WriteLine("Wrote original csv file - starting to write RDM import csv.");

                List <ExportToRdm> erdm = new List <ExportToRdm>();
                foreach (TeamviewerExporter.Device dev in responseDevices.Data.devices)
                {
                    ExportToRdm toAdd = new ExportToRdm();
                    toAdd.Description   = dev.description;
                    toAdd.Name          = dev.alias;
                    toAdd.TeamViewer_ID = dev.remotecontrol_id_clean;
                    toAdd.Host          = toAdd.TeamViewer_ID;

                    if (dev.groupname != null)
                    {
                        toAdd.Group = dev.groupname;
                    }

                    erdm.Add(toAdd);
                }

                Console.WriteLine("Writing RDM compatible import file 'rdm.csv'");
                //xtWriter rtw = File.CreateText("rdm.csv");
                TextWriter rtw  = new StreamWriter("rdm.csv", false, Encoding.UTF8);
                CsvWriter  rcsv = new CsvWriter(rtw);
                rcsv.Configuration.RegisterClassMap(typeof(MapClass)); // add custom mapping for headlines
                rcsv.WriteRecords(erdm);                               // write complete object to disc as csv
                rcsv.Dispose();

                Console.WriteLine("Successfully wrote 'rdm.csv' - application finished successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine(string.Format("SOMETHING HAPPENED{0}{1}", Environment.NewLine, ex.ToString()));
            }
            finally
            {
                Console.WriteLine("Press any enter to exit :-)");
                Console.ReadLine();
            }
        }
Example #41
0
        public static async Task <string> ExecuteExternalRequestAsync(string url, Method method)
        {
            var request = new RestRequest(url, method, DataFormat.Json);

            return(await Execute(Scope.ExternalDrugApiUrl, request));
        }
        public ActionResult CSIPersonalRecordsDetails(string indiID)
        {
            CheckLoginState();

            string authtoken = GetLoginToken("*****@*****.**", "P@ssw0rd!");

            if (!tokenValid(authtoken))
            {
                //exit with a warning
            }

            //company search API call
            var url = "https://uatrest.searchworks.co.za/individual/csipersontrace/idnumber/";

            //create RestSharp client and POST request object
            var client  = new RestClient(url);
            var request = new RestRequest(Method.POST);

            //request headers
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            //object containing input parameter data for company() API method
            var apiInput = new
            {
                SessionToken = authtoken,
                Reference    = authtoken,//search reference: probably store in logs
                IDNumber     = indiID,
            };

            //add parameters and token to request
            request.Parameters.Clear();
            request.AddParameter("application/json", JsonConvert.SerializeObject(apiInput), ParameterType.RequestBody);
            request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
            //ApiResponse is a class to model the data we want from the API response

            //make the API request and get a response
            IRestResponse response = client.Execute <RootObject>(request);

            dynamic rootObject = JObject.Parse(response.Content);

            //JObject o = JObject.Parse(response.Content);
            Debug.WriteLine(JObject.Parse(response.Content).Count);
            JObject o = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!

            JToken token = JToken.Parse(response.Content);

            Newtonsoft.Json.Linq.JArray elements      = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JArray elements1     = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JArray totalElements = new Newtonsoft.Json.Linq.JArray();
            Dictionary <string, string> arrayList     = new Dictionary <string, string>();
            Dictionary <string, string> arrayList1    = new Dictionary <string, string>();
            List <string> thatlist  = new List <string>();
            List <string> thatlist1 = new List <string>();
            Dictionary <int, Dictionary <string, string> > MianArrayList  = new Dictionary <int, Dictionary <string, string> >();
            Dictionary <int, Dictionary <string, string> > MianArrayList1 = new Dictionary <int, Dictionary <string, string> >();

            elements             = rootObject.ResponseObject.HistoricalInformation.TelephoneHistory;
            ViewData["TheCount"] = elements.Count;
            var ResponseCount = JObject.Parse(response.Content);

            //System.Diagnostics.Debug.WriteLine(ResponseCount.ResponseObject, "Im here");
            //TempData["ResponseCount"] = JObject.Parse(response.Content).Count;
            elements1 = rootObject.ResponseObject.HistoricalInformation.EmploymentHistory;
            //totalElements = rootObject.ResponseObject;
            //System.Diagnostics.Debug.WriteLine(totalElements);
            //ViewData["TheCount"] = elements1.Count;

            ViewData["ResponseMessage"] = rootObject.ResponseMessage;
            ViewData["PDFCopyURL"]      = rootObject.PDFCopyURL;
            ViewData["FirstName"]       = rootObject.ResponseObject.PersonInformation.FirstName;
            ViewData["Title"]           = rootObject.ResponseObject.PersonInformation.Title;
            ViewData["Surname"]         = rootObject.ResponseObject.PersonInformation.Surname;
            ViewData["Fullname"]        = rootObject.ResponseObject.PersonInformation.Fullname;
            ViewData["IDNumber"]        = rootObject.ResponseObject.PersonInformation.IDNumber;
            ViewData["DateOfBirth"]     = rootObject.ResponseObject.PersonInformation.DateOfBirth;
            ViewData["MaritalStatus"]   = rootObject.ResponseObject.PersonInformation.MaritalStatus;
            ViewData["Gender"]          = rootObject.ResponseObject.PersonInformation.Gender;
            ViewData["Age"]             = rootObject.ResponseObject.PersonInformation.Age;
            ViewData["Quality"]         = rootObject.ResponseObject.PersonInformation.Quality;

            string TypeDescription = "";
            string TypeCode        = "";
            string Number          = "";
            string LastUpdatedDate = "";
            List <TelephoneHistory> telH;

            telH = new List <TelephoneHistory>();

            bool TelephoneHistoryExists  = rootObject.ResponseObject.HistoricalInformation.TelephoneHistory != null;
            bool AddressHistoryExists    = rootObject.ResponseObject.HistoricalInformation.AddressHistory != null;
            bool EmploymentHistoryExists = rootObject.ResponseObject.HistoricalInformation.EmploymentHistory != null;

            System.Diagnostics.Debug.WriteLine(TelephoneHistoryExists);
            System.Diagnostics.Debug.WriteLine(AddressHistoryExists);
            System.Diagnostics.Debug.WriteLine(EmploymentHistoryExists);

            if (TelephoneHistoryExists == true)

            {
                for (int count = 0; count < (elements.Count); count++)
                {
                    TypeDescription = rootObject.ResponseObject.HistoricalInformation.TelephoneHistory[count].TypeDescription;
                    TypeCode        = rootObject.ResponseObject.HistoricalInformation.TelephoneHistory[count].TypeCode;
                    Number          = rootObject.ResponseObject.HistoricalInformation.TelephoneHistory[count].Number;
                    LastUpdatedDate = rootObject.ResponseObject.HistoricalInformation.TelephoneHistory[count].LastUpdatedDate;
                    //string FirstName = rootObject.ResponseObject.Directors[count].FirstName;
                    //string Surname = rootObject.ResponseObject.Directors[count].Surname;
                    //string Fullname = rootObject.ResponseObject.Directors[count].Fullname;
                    //string IdNumber = rootObject.ResponseObject.Directors[count].IdNumber;
                    //string DateOfBirth = rootObject.ResponseObject.Directors[count].DateOfBirth;
                    //string Age = rootObject.ResponseObject.Directors[count].Age;
                    //string StatusCode = rootObject.ResponseObject.Directors[count].StatusCode;
                    //string Status = rootObject.ResponseObject.Directors[count].Status;
                    //string TypeCode = rootObject.ResponseObject.Directors[count].TypeCode;
                    //string Type = rootObject.ResponseObject.Directors[count].Type;
                    //string AppointmentDate = rootObject.ResponseObject.Directors[count].AppointmentDate;
                    //string ResignationDate = rootObject.ResponseObject.Directors[count].ResignationDate;
                    //string MemberContribution = rootObject.ResponseObject.Directors[count].MemberContribution;
                    //string MemberSize = rootObject.ResponseObject.Directors[count].MemberSize;
                    //string ResidentialAddress1 = rootObject.ResponseObject.Directors[count].ResidentialAddress1;
                    //string ResidentialAddress2 = rootObject.ResponseObject.Directors[count].ResidentialAddress2;
                    //string ResidentialAddress3 = rootObject.ResponseObject.Directors[count].ResidentialAddress3;
                    //string ResidentialAddress4 = rootObject.ResponseObject.Directors[count].ResidentialAddress4;
                    //string ResidentialPostCode = rootObject.ResponseObject.Directors[count].ResidentialPostCode;
                    //string PostalAddress1 = rootObject.ResponseObject.Directors[count].PostalAddress1;
                    //string PostalAddress2 = rootObject.ResponseObject.Directors[count].PostalAddress2;
                    //string PostalAddress3 = rootObject.ResponseObject.Directors[count].PostalAddress3;
                    //string PostalAddress4 = rootObject.ResponseObject.Directors[count].PostalAddress4;
                    //string PostalPostCode = rootObject.ResponseObject.Directors[count].PostalPostCode;
                    //string CountryCode = rootObject.ResponseObject.Directors[count].CountryCode;
                    //string Country = rootObject.ResponseObject.Directors[count].Country;
                    //string NationalityCode = rootObject.ResponseObject.Directors[count].NationalityCode;
                    //string Gender = rootObject.ResponseObject.Directors[count].Gender;

                    arrayList.Add(count + "_TypeDescription", TypeDescription);
                    arrayList.Add(count + "_TypeCode", TypeCode);
                    arrayList.Add(count + "_Number", Number);
                    arrayList.Add(count + "_LastUpdatedDate", LastUpdatedDate);

                    telH.Add(new TelephoneHistory
                    {
                        TypeDescription = TypeDescription,
                        TypeCode        = TypeCode,
                        Number          = Number
                    });

                    //arrayList.Add(count + "_IdNumber", IdNumber);
                    //arrayList.Add(count + "_Age", Age);
                    //arrayList.Add(count + "_Status", Status);
                    //arrayList.Add(count + "_ResignationDate", ResignationDate);
                    ViewData["ArrayList"] = arrayList;
                    ViewData["thatlist"]  = thatlist;

                    //System.Diagnostics.Debug.WriteLine(count + " arrayList: " + arrayList);
                    MianArrayList.Add(count, arrayList);
                    //Debug.WriteLine(MianArrayList);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    ViewData["MianArrayList"] = serializer.Serialize(MianArrayList[0]);
                    //ViewData["MianArrayList"] = MianArrayList;
                    //ViewData["elements"] = elements;

                    //ViewData["elementsType"] = elements;
                    // ViewData["DirectorID"] = DirectorID;
                    //ViewData["FirstName"] = FirstName;
                    //ViewData["Surname"] = Surname;

                    ViewData["telH"] = telH;
                    //System.Diagnostics.Debug.WriteLine(" Director ID "+count+" : "+ DirectorID);
                }
                //foreach (KeyValuePair<string, string> item in arrayList)
                //{
                //    System.Diagnostics.Debug.WriteLine( item.Key, item.Value);
                //}
            }
            else
            {
                telH.Add(new TelephoneHistory
                {
                    TypeDescription = "None",
                    TypeCode        = "None",
                    Number          = "None",
                });
                ViewData["empH"] = telH;
            }
            string EmployerName     = "";
            string Designation      = "";
            string LastUpdatedDate1 = "";
            List <EmploymentHistory> empH;

            empH = new List <EmploymentHistory>();

            if (EmploymentHistoryExists == true)
            {
                for (int count = 0; count < (elements1.Count); count++)
                {
                    EmployerName     = rootObject.ResponseObject.HistoricalInformation.EmploymentHistory[count].EmployerName;
                    Designation      = rootObject.ResponseObject.HistoricalInformation.EmploymentHistory[count].Designation;
                    LastUpdatedDate1 = rootObject.ResponseObject.HistoricalInformation.EmploymentHistory[count].LastUpdatedDate;
                    //string FirstName = rootObject.ResponseObject.Directors[count].FirstName;
                    //string Surname = rootObject.ResponseObject.Directors[count].Surname;
                    //string Fullname = rootObject.ResponseObject.Directors[count].Fullname;
                    //string IdNumber = rootObject.ResponseObject.Directors[count].IdNumber;
                    //string DateOfBirth = rootObject.ResponseObject.Directors[count].DateOfBirth;
                    //string Age = rootObject.ResponseObject.Directors[count].Age;
                    //string StatusCode = rootObject.ResponseObject.Directors[count].StatusCode;
                    //string Status = rootObject.ResponseObject.Directors[count].Status;
                    //string TypeCode = rootObject.ResponseObject.Directors[count].TypeCode;
                    //string Type = rootObject.ResponseObject.Directors[count].Type;
                    //string AppointmentDate = rootObject.ResponseObject.Directors[count].AppointmentDate;
                    //string ResignationDate = rootObject.ResponseObject.Directors[count].ResignationDate;
                    //string MemberContribution = rootObject.ResponseObject.Directors[count].MemberContribution;
                    //string MemberSize = rootObject.ResponseObject.Directors[count].MemberSize;
                    //string ResidentialAddress1 = rootObject.ResponseObject.Directors[count].ResidentialAddress1;
                    //string ResidentialAddress2 = rootObject.ResponseObject.Directors[count].ResidentialAddress2;
                    //string ResidentialAddress3 = rootObject.ResponseObject.Directors[count].ResidentialAddress3;
                    //string ResidentialAddress4 = rootObject.ResponseObject.Directors[count].ResidentialAddress4;
                    //string ResidentialPostCode = rootObject.ResponseObject.Directors[count].ResidentialPostCode;
                    //string PostalAddress1 = rootObject.ResponseObject.Directors[count].PostalAddress1;
                    //string PostalAddress2 = rootObject.ResponseObject.Directors[count].PostalAddress2;
                    //string PostalAddress3 = rootObject.ResponseObject.Directors[count].PostalAddress3;
                    //string PostalAddress4 = rootObject.ResponseObject.Directors[count].PostalAddress4;
                    //string PostalPostCode = rootObject.ResponseObject.Directors[count].PostalPostCode;
                    //string CountryCode = rootObject.ResponseObject.Directors[count].CountryCode;
                    //string Country = rootObject.ResponseObject.Directors[count].Country;
                    //string NationalityCode = rootObject.ResponseObject.Directors[count].NationalityCode;
                    //string Gender = rootObject.ResponseObject.Directors[count].Gender;

                    arrayList1.Add(count + "_EmployerName", EmployerName);
                    arrayList1.Add(count + "_Designation", Designation);
                    arrayList1.Add(count + "_LastUpdatedDate", LastUpdatedDate1);
                    //arrayList.Add(count + "_IdNumber", IdNumber);
                    //arrayList.Add(count + "_Age", Age);
                    //arrayList.Add(count + "_Status", Status);
                    //arrayList.Add(count + "_ResignationDate", ResignationDate);

                    empH.Add(new EmploymentHistory
                    {
                        EmployerName    = EmployerName,
                        Designation     = Designation,
                        LastUpdatedDate = LastUpdatedDate1
                    });

                    ViewData["ArrayList1"]    = arrayList1;
                    ViewData["thatlist1"]     = thatlist1;
                    ViewData["MianArrayList"] = MianArrayList;
                    MianArrayList1.Add(count, arrayList1);
                    //ViewData["MianArrayList"] = MianArrayList;
                    //ViewData["elements"] = elements;
                    //ViewData["elementsType"] = elements;
                    // ViewData["DirectorID"] = DirectorID;
                    //ViewData["FirstName"] = FirstName;
                    //ViewData["Surname"] = Surname;

                    //System.Diagnostics.Debug.WriteLine(" Director ID "+count+" : "+ DirectorID);
                }

                //empH = new List<EmploymentHistory>();

                //foreach (var item in arrayList1)
                //{
                //    empH.Add(new EmploymentHistory
                //    {
                //        EmployerName = EmployerName,
                //        Designation = Designation,
                //        LastUpdatedDate = LastUpdatedDate1
                //    });
                //}
                ViewData["empH"] = empH;

                //foreach (KeyValuePair<string, string> item in arrayList1)
                //{
                //    System.Diagnostics.Debug.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
                //}
            }
            else
            {
                empH.Add(new EmploymentHistory
                {
                    EmployerName    = "None",
                    Designation     = "None",
                    LastUpdatedDate = "None",
                });
                ViewData["empH"] = empH;
            }

            if (rootObject.ResponseObject.HomeAffairsInformation.DeceasedStatus != null)
            {
                ViewData["DeceasedStatus"] = rootObject.ResponseObject.HomeAffairsInformation.DeceasedStatus;
                ViewData["DeceasedDate"]   = rootObject.ResponseObject.HomeAffairsInformation.DeceasedDate;
                ViewData["CauseOfDeath"]   = rootObject.ResponseObject.HomeAffairsInformation.CauseOfDeath;
                ViewData["VerifiedDate"]   = rootObject.ResponseObject.HomeAffairsInformation.VerifiedDate;
                ViewData["VerifiedStatus"] = rootObject.ResponseObject.HomeAffairsInformation.VerifiedStatus;
            }

            return(View());
        }
        public ActionResult DeedsOfficeRecordsIndividualResults(Deeds deed)
        {
            CheckLoginState();

            string name  = deed.Firstname;
            string deeds = deed.DeedsOffice;
            string sur   = deed.Surname;
            string id    = deed.IDNumber;
            string refe  = deed.Reference;

            string authtoken = GetLoginToken("*****@*****.**", "P@ssw0rd!");

            if (!tokenValid(authtoken))
            {
                //exit with a warning
            }

            //company search API call
            var url = "https://uatrest.searchworks.co.za/deedsoffice/person/";

            //create RestSharp client and POST request object
            var client  = new RestClient(url);
            var request = new RestRequest(Method.POST);

            //request headers
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            //object containing input parameter data for company() API method
            var apiInput = new
            {
                SessionToken  = authtoken,
                DeedsOffice   = deed,      //company name contains: See documentation
                Reference     = authtoken, //search reference: probably store in logs
                Surname       = sur,
                Firstname     = name,
                IDNumber      = id,
                Sequestration = "false",
            };

            //add parameters and token to request
            request.Parameters.Clear();
            request.AddParameter("application/json", JsonConvert.SerializeObject(apiInput), ParameterType.RequestBody);
            request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
            //ApiResponse is a class to model the data we want from the API response

            //make the API request and get a response
            IRestResponse response = client.Execute <RootObject>(request);

            dynamic rootObject = JObject.Parse(response.Content);

            ViewData["ResponseMessage"] = rootObject.ResponseMessage;
            ViewData["PDFCopyURL"]      = rootObject.PDFCopyURL;

            //extract list of companies returned
            List <DeedsInformation> lst = getCompanyList(response);

            string dbConnectionString = ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString;//string.Format("server={0};uid={1};pwd={2};database={3};", serverIp, username, password, databaseName);

            var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString);

            DateTime time = DateTime.Now;

            string date_add = DateTime.Today.ToShortDateString();
            string time_add = time.ToString("T");
            string page     = "CIPC Company Records";
            string action   = "Company Name:" + name;
            string user_id  = Session["ID"].ToString();
            string us       = Session["Name"].ToString();

            ViewData["user"]    = Session["Name"].ToString();
            ViewData["date"]    = DateTime.Today.ToShortDateString();
            ViewData["ref"]     = refe;
            ViewData["ComName"] = name;

            string query_uid = "INSERT INTO logs (date,time,page,action,user_id,user) VALUES('" + date_add + "','" + time_add + "','" + page + "','" + action + "','" + user_id + "','" + us + "')";

            conn.Open();

            var cmd2 = new MySqlCommand(query_uid, conn);

            var reader2 = cmd2.ExecuteReader();

            conn.Close();

            return(View(lst));
        }
        public ActionResult CSIPersonalRecordsResults(CSI csi)
        {
            CheckLoginState();

            var    arraylist = new ArrayList();
            string name      = csi.FirstName;
            string sur       = csi.Surname;
            string id        = csi.IDNumber;
            string seaType   = csi.seaType;
            string eqType    = csi.eqType;
            string refe      = csi.Reference;

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

            DateTime time = DateTime.Now;

            string date_add = DateTime.Today.ToShortDateString();
            string time_add = time.ToString("T");
            string page     = "CSI Person " + eqType + "By " + seaType;
            string action   = "Name:" + name + "; Surname:" + sur;
            string user_id;

            try
            {
                user_id = Session["ID"].ToString();
            }
            catch (Exception e)
            {
                return(RedirectToAction("Index", "Home"));
            }

            string us = Session["Name"].ToString();

            string dbConnectionString = ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString;//string.Format("server={0};uid={1};pwd={2};database={3};", serverIp, username, password, databaseName);

            var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString);

            string query_uid = "INSERT INTO logs (date,time,page,action,user_id,user) VALUES('" + date_add + "','" + time_add + "','" + page + "','" + action + "','" + user_id + "','" + us + "')";

            TempData["user"] = Session["Name"].ToString();
            TempData["date"] = DateTime.Today.ToShortDateString();
            TempData["ref"]  = refe;
            conn.Open();

            var cmd2 = new MySqlCommand(query_uid, conn);

            var reader2 = cmd2.ExecuteReader();

            conn.Close();
            string authtoken = GetLoginToken("*****@*****.**", "P@ssw0rd!");

            if (!tokenValid(authtoken))
            {
                //exit with a warning
            }
            //request headers
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");

            IRestResponse response = client.Execute <RootObject>(request);
            dynamic       rootObject;
            JObject       o;
            JToken        token;

            try
            {
                switch (seaType + "|" + eqType)
                {
                case "idnumber|trace":
                    url     = "https://uatrest.searchworks.co.za/individual/csipersontrace/idnumber/";
                    client  = new RestClient(url);
                    request = new RestRequest(Method.POST);
                    var apiIdTrace = new
                    {
                        SessionToken = authtoken,
                        Reference    = us, //search reference: probably store in logs
                        IDNumber     = id,
                    };
                    request.Parameters.Clear();
                    request.AddParameter("application/json", JsonConvert.SerializeObject(apiIdTrace), ParameterType.RequestBody);
                    request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
                    //ApiResponse is a class to model the data we want from the API response
                    //make the API request and get a response
                    response   = client.Execute <RootObject>(request);
                    rootObject = JObject.Parse(response.Content);
                    //JObject o = JObject.Parse(response.Content);
                    o     = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!
                    token = JToken.Parse(response.Content);
                    TempData["SearchType"]      = seaType;
                    TempData["ResponseMessage"] = rootObject.ResponseMessage;
                    TempData["PDFCopyURL"]      = rootObject.PDFCopyURL;
                    TempData["FirstName"]       = rootObject.ResponseObject.PersonInformation.FirstName;
                    TempData["Title"]           = rootObject.ResponseObject.PersonInformation.Title;
                    TempData["Surname"]         = rootObject.ResponseObject.PersonInformation.Surname;
                    TempData["Fullname"]        = rootObject.ResponseObject.PersonInformation.Fullname;
                    TempData["IDNumber"]        = rootObject.ResponseObject.PersonInformation.IDNumber;
                    TempData["DateOfBirth"]     = rootObject.ResponseObject.PersonInformation.DateOfBirth;
                    TempData["MaritalStatus"]   = rootObject.ResponseObject.PersonInformation.MaritalStatus;
                    TempData["Gender"]          = rootObject.ResponseObject.PersonInformation.Gender;
                    TempData["Age"]             = rootObject.ResponseObject.PersonInformation.Age;
                    TempData["Quality"]         = rootObject.ResponseObject.PersonInformation.Quality;
                    TempData.Keep();
                    return(View());

                case "name|trace":

                    Debug.WriteLine("name|trace");

                    url = "https://uatrest.searchworks.co.za/individual/csipersonrecords/personverification/name/";

                    client  = new RestClient(url);
                    request = new RestRequest(Method.POST);
                    var apinameTrace = new
                    {
                        sessionToken = authtoken,
                        reference    = us, //search reference: probably store in logs
                        firstName    = name,
                        surname      = sur
                    };
                    //add parameters and token to request
                    request.Parameters.Clear();
                    request.AddParameter("application/json", JsonConvert.SerializeObject(apinameTrace), ParameterType.RequestBody);
                    request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
                    //ApiResponse is a class to model the data we want from the API response
                    //make the API request and get a response
                    response   = client.Execute <RootObject>(request);
                    rootObject = JObject.Parse(response.Content);
                    o          = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!
                    token      = JToken.Parse(response.Content);
                    System.Diagnostics.Debug.WriteLine(JObject.Parse(response.Content));
                    TempData["SearchType"]      = seaType;
                    TempData["ResponseMessage"] = rootObject.ResponseMessage;
                    TempData["PDFCopyURL"]      = rootObject.PDFCopyURL;
                    TempData["FirstName"]       = rootObject.ResponseObject[0].PersonInformation.FirstName;
                    TempData["Title"]           = rootObject.ResponseObject[0].PersonInformation.Title;
                    TempData["Surname"]         = rootObject.ResponseObject[0].PersonInformation.Surname;
                    TempData["Fullname"]        = rootObject.ResponseObject[0].PersonInformation.Fullname;
                    TempData["IDNumber"]        = rootObject.ResponseObject[0].PersonInformation.IDNumber;
                    TempData["DateOfBirth"]     = rootObject.ResponseObject[0].PersonInformation.DateOfBirth;
                    TempData["MaritalStatus"]   = rootObject.ResponseObject[0].PersonInformation.MaritalStatus;
                    TempData["Gender"]          = rootObject.ResponseObject[0].PersonInformation.Gender;
                    TempData["Age"]             = rootObject.ResponseObject[0].PersonInformation.Age;
                    TempData["Quality"]         = rootObject.ResponseObject[0].PersonInformation.Quality;
                    TempData.Keep();
                    //ViewData["FirstName1"] = (Array)o.SelectToken("ResponseObject");
                    //extract list of companies returned

                    //PersonInformation lst = getIndividualList(response);
                    return(View());

                case "nameandidnumber|trace":
                    Debug.WriteLine("nameandidnumber|trace");
                    url     = "https://uatrest.searchworks.co.za/individual/csipersonrecords/personverification/nameidnumber/";
                    client  = new RestClient(url);
                    request = new RestRequest(Method.POST);

                    var apinameidTrace = new
                    {
                        sessionToken = authtoken,
                        reference    = us, //search reference: probably store in logs
                        idNumber     = id,
                        firstName    = name,
                        surname      = sur
                    };
                    //add parameters and token to request
                    request.Parameters.Clear();
                    request.AddParameter("application/json", JsonConvert.SerializeObject(apinameidTrace), ParameterType.RequestBody);
                    request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
                    //ApiResponse is a class to model the data we want from the API response
                    //make the API request and get a response
                    response   = client.Execute <RootObject>(request);
                    rootObject = JObject.Parse(response.Content);
                    o          = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!
                    token      = JToken.Parse(response.Content);
                    System.Diagnostics.Debug.WriteLine(response.Content);
                    TempData["SearchType"]      = seaType;
                    TempData["ResponseMessage"] = rootObject.ResponseMessage;
                    TempData["PDFCopyURL"]      = rootObject.PDFCopyURL;
                    TempData["FirstName"]       = rootObject.ResponseObject[0].PersonInformation.FirstName;
                    TempData["Title"]           = rootObject.ResponseObject[0].PersonInformation.Title;
                    TempData["Surname"]         = rootObject.ResponseObject[0].PersonInformation.Surname;
                    TempData["Fullname"]        = rootObject.ResponseObject[0].PersonInformation.Fullname;
                    TempData["IDNumber"]        = rootObject.ResponseObject[0].PersonInformation.IDNumber;
                    TempData["DateOfBirth"]     = rootObject.ResponseObject[0].PersonInformation.DateOfBirth;
                    TempData["MaritalStatus"]   = rootObject.ResponseObject[0].PersonInformation.MaritalStatus;
                    TempData["Gender"]          = rootObject.ResponseObject[0].PersonInformation.Gender;
                    TempData["Age"]             = rootObject.ResponseObject[0].PersonInformation.Age;
                    TempData["Quality"]         = rootObject.ResponseObject[0].PersonInformation.Quality;
                    TempData.Keep();

                    return(View());

                case "idnumber|verification":
                    //company search API call
                    url = "https://uatrest.searchworks.co.za/individual/csipersonrecords/personverification/idnumber/";
                    //create RestSharp client and POST request object
                    client  = new RestClient(url);
                    request = new RestRequest(Method.POST);
                    //object containing input parameter data for company() API method
                    var apiIdVeri = new
                    {
                        sessionToken = authtoken,
                        reference    = us, //search reference: probably store in logs
                        idNumber     = id,
                    };
                    //add parameters and token to request
                    request.Parameters.Clear();
                    request.AddParameter("application/json", JsonConvert.SerializeObject(apiIdVeri), ParameterType.RequestBody);
                    request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
                    //ApiResponse is a class to model the data we want from the API response
                    //make the API request and get a response
                    response   = client.Execute <RootObject>(request);
                    rootObject = JObject.Parse(response.Content);
                    //JObject o = JObject.Parse(response.Content);
                    o     = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!
                    token = JToken.Parse(response.Content);
                    System.Diagnostics.Debug.WriteLine(response.Content);
                    TempData["SearchType"]      = seaType;
                    TempData["ResponseMessage"] = rootObject.ResponseMessage;
                    TempData["PDFCopyURL"]      = rootObject.PDFCopyURL;
                    TempData["FirstName"]       = rootObject.ResponseObject[0].PersonInformation.FirstName;
                    TempData["Title"]           = rootObject.ResponseObject[0].PersonInformation.Title;
                    TempData["Surname"]         = rootObject.ResponseObject[0].PersonInformation.Surname;
                    TempData["Fullname"]        = rootObject.ResponseObject[0].PersonInformation.Fullname;
                    TempData["IDNumber"]        = rootObject.ResponseObject[0].PersonInformation.IDNumber;
                    TempData["DateOfBirth"]     = rootObject.ResponseObject[0].PersonInformation.DateOfBirth;
                    TempData["MaritalStatus"]   = rootObject.ResponseObject[0].PersonInformation.MaritalStatus;
                    TempData["Gender"]          = rootObject.ResponseObject[0].PersonInformation.Gender;
                    TempData["Age"]             = rootObject.ResponseObject[0].PersonInformation.Age;
                    TempData["Quality"]         = rootObject.ResponseObject[0].PersonInformation.Quality;
                    TempData.Keep();

                    return(View());

                case "name|verification":
                    Debug.WriteLine("name|verification");

                    url = "https://uatrest.searchworks.co.za/individual/csipersonrecords/personverification/name/";

                    client  = new RestClient(url);
                    request = new RestRequest(Method.POST);
                    var apinameVeri = new
                    {
                        sessionToken = authtoken,
                        reference    = us, //search reference: probably store in logs
                        firstName    = name,
                        surname      = sur
                    };
                    //add parameters and token to request
                    request.Parameters.Clear();
                    request.AddParameter("application/json", JsonConvert.SerializeObject(apinameVeri), ParameterType.RequestBody);
                    request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
                    //ApiResponse is a class to model the data we want from the API response
                    //make the API request and get a response
                    response   = client.Execute <RootObject>(request);
                    rootObject = JObject.Parse(response.Content);
                    o          = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!
                    token      = JToken.Parse(response.Content);
                    System.Diagnostics.Debug.WriteLine(response.Content);
                    TempData["SearchType"]      = seaType;
                    TempData["ResponseMessage"] = rootObject.ResponseMessage;
                    TempData["PDFCopyURL"]      = rootObject.PDFCopyURL;
                    TempData["FirstName"]       = rootObject.ResponseObject[0].PersonInformation.FirstName;
                    TempData["Title"]           = rootObject.ResponseObject[0].PersonInformation.Title;
                    TempData["Surname"]         = rootObject.ResponseObject[0].PersonInformation.Surname;
                    TempData["Fullname"]        = rootObject.ResponseObject[0].PersonInformation.Fullname;
                    TempData["IDNumber"]        = rootObject.ResponseObject[0].PersonInformation.IDNumber;
                    TempData["DateOfBirth"]     = rootObject.ResponseObject[0].PersonInformation.DateOfBirth;
                    TempData["MaritalStatus"]   = rootObject.ResponseObject[0].PersonInformation.MaritalStatus;
                    TempData["Gender"]          = rootObject.ResponseObject[0].PersonInformation.Gender;
                    TempData["Age"]             = rootObject.ResponseObject[0].PersonInformation.Age;
                    TempData["Quality"]         = rootObject.ResponseObject[0].PersonInformation.Quality;
                    TempData.Keep();

                    return(View());

                case "nameandidnumber|verification":
                    Debug.WriteLine("nameandidnumber|verification");
                    url     = "https://uatrest.searchworks.co.za/individual/csipersonrecords/personverification/nameidnumber/";
                    client  = new RestClient(url);
                    request = new RestRequest(Method.POST);

                    var apinameidVeri = new
                    {
                        sessionToken = authtoken,
                        reference    = us, //search reference: probably store in logs
                        idNumber     = id,
                        firstName    = name,
                        surname      = sur
                    };
                    //add parameters and token to request
                    request.Parameters.Clear();
                    request.AddParameter("application/json", JsonConvert.SerializeObject(apinameidVeri), ParameterType.RequestBody);
                    request.AddParameter("Authorization", "Bearer " + authtoken, ParameterType.HttpHeader);
                    //ApiResponse is a class to model the data we want from the API response
                    //make the API request and get a response
                    response   = client.Execute <RootObject>(request);
                    rootObject = JObject.Parse(response.Content);
                    o          = JObject.Parse(response.Content);//Newtonsoft.Json.Linq.JObject search!!!!
                    token      = JToken.Parse(response.Content);
                    System.Diagnostics.Debug.WriteLine(response.Content);
                    TempData["SearchType"]      = seaType;
                    TempData["ResponseMessage"] = rootObject.ResponseMessage;
                    TempData["PDFCopyURL"]      = rootObject.PDFCopyURL;
                    TempData["FirstName"]       = rootObject.ResponseObject[0].PersonInformation.FirstName;
                    TempData["Title"]           = rootObject.ResponseObject[0].PersonInformation.Title;
                    TempData["Surname"]         = rootObject.ResponseObject[0].PersonInformation.Surname;
                    TempData["Fullname"]        = rootObject.ResponseObject[0].PersonInformation.Fullname;
                    TempData["IDNumber"]        = rootObject.ResponseObject[0].PersonInformation.IDNumber;
                    TempData["DateOfBirth"]     = rootObject.ResponseObject[0].PersonInformation.DateOfBirth;
                    TempData["MaritalStatus"]   = rootObject.ResponseObject[0].PersonInformation.MaritalStatus;
                    TempData["Gender"]          = rootObject.ResponseObject[0].PersonInformation.Gender;
                    TempData["Age"]             = rootObject.ResponseObject[0].PersonInformation.Age;
                    TempData["Quality"]         = rootObject.ResponseObject[0].PersonInformation.Quality;
                    TempData.Keep();
                    return(View());
                }
            }
            catch (Exception e)
            {
                TempData["msg"] = "An error occured, please check the entered values.";
            }

            return(View());
        }
Example #45
0
        // If you need to do some testing on Inara's API, please set the `isDeveloped` boolean header property to true.
        public List <InaraResponse> SendEventBatch(List <InaraAPIEvent> events, InaraConfiguration inaraConfiguration)
        {
            // We always want to return a list from this method (even if it's an empty list) rather than a null value.
            List <InaraResponse> inaraResponses = new List <InaraResponse>();

            if (events is null)
            {
                return(inaraResponses);
            }

            try
            {
                if (inaraConfiguration is null)
                {
                    inaraConfiguration = InaraConfiguration.FromFile();
                }
                List <InaraAPIEvent> indexedEvents = IndexAndFilterAPIEvents(events, inaraConfiguration);
                if (indexedEvents.Count > 0)
                {
                    var           client       = new RestClient("https://inara.cz/inapi/v1/");
                    var           request      = new RestRequest(Method.POST);
                    InaraSendJson inaraRequest = new InaraSendJson()
                    {
                        header = new Dictionary <string, object>()
                        {
                            { "appName", "EDDI" },
                            { "appVersion", Constants.EDDI_VERSION.ToString() },
                            { "isBeingDeveloped", eddiIsBeta },
                            { "commanderName", inaraConfiguration.commanderName },
                            { "commanderFrontierID", inaraConfiguration.commanderFrontierID },
                            { "APIkey", !string.IsNullOrEmpty(inaraConfiguration.apiKey) ? inaraConfiguration.apiKey : readonlyAPIkey }
                        },
                        events = indexedEvents
                    };
                    request.RequestFormat = DataFormat.Json;
                    request.AddJsonBody(inaraRequest); // uses JsonSerializer

                    Logging.Debug("Sending to Inara: " + client.BuildUri(request).AbsoluteUri);
                    var clientResponse = client.Execute <InaraResponses>(request);
                    if (clientResponse.IsSuccessful)
                    {
                        InaraResponses response = clientResponse.Data;
                        if (validateResponse(response.header, indexedEvents, true))
                        {
                            foreach (InaraResponse inaraResponse in response.events)
                            {
                                if (validateResponse(inaraResponse, indexedEvents))
                                {
                                    inaraResponses.Add(inaraResponse);
                                }
                            }
                        }
                    }
                    else
                    {
                        // Inara may return null as it undergoes a nightly maintenance cycle where the servers go offline temporarily.
                        Logging.Warn("Unable to connect to the Inara server.", clientResponse.ErrorMessage);
                        ReEnqueueAPIEvents(events);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error("Sending data to the Inara server failed.", ex);
                ReEnqueueAPIEvents(events);
            }
            return(inaraResponses);
        }
Example #46
0
        private void booking_Click(object sender, EventArgs e)
        {
            var client  = new RestClient("http://localhost/web_sister/REST_API/api/tiket");
            var request = new RestRequest(Method.GET);

            request.AddParameter("tujuan", comboTujuan.SelectedItem);
            var          result  = client.Execute(request);
            var          content = result.Content;
            JObject      obj     = JObject.Parse(content);
            DialogResult tombol  =
                MessageBox.Show("Tiket Yang Anda Pilih\n Tujuan = " + (string)obj.SelectToken("data[0].tujuan") +
                                "\nHarga = " + (string)obj.SelectToken("data[0].harga") + "\n Lanjutkan Booking ?", "KONFIRMASI BOOKING",
                                MessageBoxButtons.OKCancel);

            if (tombol == DialogResult.OK)
            {
                try {
                    var clientT  = new RestClient("http://localhost/web_sister/REST_API/api/transaksi");
                    var requestT = new RestRequest(Method.POST);
                    requestT.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                    requestT.AddParameter("undefined", "idCustomer=" + idCust.Text +
                                          "&idTiket=" + (string)obj.SelectToken("data[0].idTiket") +
                                          "&status=0", ParameterType.RequestBody);
                    IRestResponse response = clientT.Execute(requestT);
                    MessageBox.Show("Data Berhasil Terinput, Silahkan Melakukan Pembayaran Untuk Memvalidasi Pemesanan Anda\n"
                                    + "harap catat ID Tiket Anda yang muncul di bawah Untuk Validasi !");
                    var req2 = new RestRequest(Method.GET);
                    req2.AddParameter("idCustomer", idCust.Text);
                    var     execute = clientT.Execute(req2);
                    var     hasil   = execute.Content;
                    JObject objek   = JObject.Parse(hasil);
                    idTrans.Text = (string)objek.SelectToken("data[0].idTransaksi");
                }
                catch (Exception eror) { MessageBox.Show(eror.ToString()); }
            }
            else
            {//jika transaksi dibatalkan beri pilihan, pilih tiket lain atau tidak
                DialogResult batal = MessageBox.Show("Transaksi Dibatalkan !", "BATALKAN", MessageBoxButtons.OK);
                if (batal == DialogResult.OK)
                {
                    DialogResult pesanlagi = MessageBox.Show("PESAN TIKET TUJUAN LAIN ?", "KONFIRMASI LAGI", MessageBoxButtons.YesNo);
                    if (pesanlagi == DialogResult.Yes)
                    {
                        //messagebox ini bakal nutup
                        //ulang dari awal
                    }
                    else //data customer dihapus
                    {
                        string id = idCust.Text;
                        try {
                            //MessageBox.Show(id);/*
                            var clientC  = new RestClient("http://localhost/web_sister/REST_API/api/pelanggan");
                            var requestC = new RestRequest(id, Method.DELETE, DataFormat.Json);
                            //= resp => { resp.ContentType = "application/json"; };
                            //requestC.AddHeader("content-length", "13");
                            //requestC.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                            requestC.AddParameter("undefined", "idCustomer=" + id.ToString(), ParameterType.RequestBody);
                            var     ex    = clientC.Delete(requestC);
                            var     ec    = ex.Content;
                            JObject ja    = JObject.Parse(ec);
                            string  pesan = (string)ja.SelectToken("status");
                            MessageBox.Show("DATA CUSTOMER TELAH DIHAPUS DARI DATABASE\nStatus penghapusan =" + pesan);
                            resettext();
                        }
                        catch (Exception eror)
                        {
                            MessageBox.Show(eror.ToString());
                        }
                    }
                }
            }
        }
Example #47
0
        private async Task <string> GetResponseContent(string endpoint, string requestBody)
        {
            Logger.Verbose("Making request to " + endpoint + " endpoint...");

            var restClient  = new RestClient(ApiClient.ApiUrl);
            var restRequest = new RestRequest(endpoint, Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            restRequest.AddParameter("application/json", requestBody, ParameterType.RequestBody);

            if (IsAuthenticatedRequest)
            {
                if (string.IsNullOrEmpty(ApiClient.ApiKey))
                {
                    throw new MissingFieldException("API key not provided for authenticated request.");
                }

                if (string.IsNullOrEmpty(ApiClient.PrivateKeyPem))
                {
                    throw new MissingFieldException("Private key not provided");
                }

                var signature = AsymmetricCryptoUtil.CreateSignature(requestBody, ApiClient.PrivateKeyPem);
                restRequest.AddHeader("Authorization", "token " + ApiClient.ApiKey + ":" + signature);
            }

            IRestResponse restResponse = new RestResponse();

            if (InterruptHandleSet)
            {
                // Perform the request asynchronously, but block on the interrupt handle.
                var responseReceived = false;
                var asyncHandle      = restClient.ExecuteAsync(restRequest, response =>
                {
                    responseReceived = true;
                    restResponse     = response;
                    InterruptHandle.Set();
                });

                InterruptHandle.WaitOne();

                if (!responseReceived)
                {
                    asyncHandle.Abort();
                    throw new RequestException("Network error. Request was interrupted.");
                }
            }
            else
            {
                var cancellationTokenSource = new CancellationTokenSource();
                restResponse = await restClient.ExecuteTaskAsync(restRequest, cancellationTokenSource.Token);
            }

            if (restResponse.StatusCode == 0)
            {
                throw new RequestException("Network error. Could not connect to server.");
            }

            if (restResponse.StatusCode != HttpStatusCode.OK)
            {
                ErrorResponse errorResponse;
                try
                {
                    errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(restResponse.Content);
                }
                catch (Exception)
                {
                    throw new NetworkErrorException("Unknown error whilst contacting server");
                }

                switch (restResponse.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                    throw new BadRequestException(errorResponse.Error);

                case HttpStatusCode.Unauthorized:
                    throw new UnauthorizedException(errorResponse.Error);

                case HttpStatusCode.NotFound:
                    throw new NotFoundException(errorResponse.Error);

                case HttpStatusCode.Conflict:
                    throw new NotFoundException(errorResponse.Error);

                default:
                    throw new RequestException(errorResponse.Error);
                }
            }

            Logger.Verbose("Received response: " + restResponse.Content);

            return(restResponse.Content);
        }
Example #48
0
 public CheckAvailability(string urls)
 {
     restClient  = new NetworkInitializer().GetNetworkConfig(urls);
     restRequest = new RestRequest(Method.POST);
 }
Example #49
0
        public IRestResponse Get(string jsonString)
        {
            var request = new RestRequest(Method.GET);

            return(client.Execute(request));
        }
Example #50
0
        private void _worker_DoWork(object sender, DoWorkEventArgs e)
        {
            var since = ReadLastPull();

            SaveLastPull(since);
            while (true)
            {
                Thread.Sleep(4000);
                var request = new RestRequest($"/sms/pushes/{since.ToString("s", CultureInfo.InvariantCulture)}",
                                              Method.GET, DataFormat.Json);
                var response = RestClient.Execute <IEnumerable <Push> >(request);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    since = DateTime.UtcNow;
                    SaveLastPull(since);
                    continue;
                }

                if (!response.Data.Any())
                {
                    since = DateTime.UtcNow;
                    SaveLastPull(since);
                    continue;
                }

                since = response.Data.Max(d => d.DateCreated).ToUniversalTime() + TimeSpan.FromSeconds(1);
                SaveLastPull(since);

                foreach (var push in response.Data)
                {
                    switch (push.Name)
                    {
                    case "message-created":
                    {
                        var messageItem = JsonConvert.DeserializeObject <MessageItem>(push.Body);

                        var messageEventPayload = new MessageEventPayload
                        {
                            EventType   = MessageEventPayload.MessageEventType.Created,
                            MessageItem = messageItem
                        };

                        MessageEvent?.Invoke(this, messageEventPayload);
                        break;
                    }

                    case "message-deleted":
                    {
                        var messageItem = JsonConvert.DeserializeObject <MessageItem>(push.Body);

                        var messageEventPayload = new MessageEventPayload
                        {
                            EventType   = MessageEventPayload.MessageEventType.Deleted,
                            MessageItem = messageItem
                        };

                        MessageEvent?.Invoke(this, messageEventPayload);
                        break;
                    }

                    case "conversation-created":
                    {
                        var conversation = JsonConvert.DeserializeObject <Conversation>(push.Body);

                        var conversationEventPayload = new ConversationEventPayload
                        {
                            EventType        = ConversationEventPayload.ConversationEventType.Created,
                            ConversationItem = conversation
                        };

                        ConversationEvent?.Invoke(this, conversationEventPayload);
                        break;
                    }

                    case "conversation-updated":
                    {
                        var conversation = JsonConvert.DeserializeObject <Conversation>(push.Body);

                        var conversationEventPayload = new ConversationEventPayload
                        {
                            EventType        = ConversationEventPayload.ConversationEventType.Updated,
                            ConversationItem = conversation
                        };

                        ConversationEvent?.Invoke(this, conversationEventPayload);
                        break;
                    }

                    case "contact-created":
                    {
                        var contact = JsonConvert.DeserializeObject <Contact>(push.Body);
                        var payload = new ContactUpdatedPayload
                        {
                            Contact    = contact,
                            UpdateType = ContactUpdatedPayload.UpdateTypes.Created
                        };
                        ContactUpdatedEvent?.Invoke(this, payload);
                        break;
                    }

                    case "contact-updated":
                    {
                        var contact = JsonConvert.DeserializeObject <Contact>(push.Body);
                        var payload = new ContactUpdatedPayload
                        {
                            Contact    = contact,
                            UpdateType = ContactUpdatedPayload.UpdateTypes.Updated
                        };
                        ContactUpdatedEvent?.Invoke(this, payload);
                        break;
                    }
                    }
                }
            }
        }
Example #51
0
        /// <summary>
        /// if error  throw ex
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="ActionStep">action step</param>
        /// <returns></returns>
        private static ResponseModel RequestURL_GET(string URL, string ActionStep)
        {
            int action = 3;

            try
            {
                if (action == 1)
                {
                    var client = new RestClient(URL);
                    client.Timeout = -1;
                    var           request  = new RestRequest(Method.GET);
                    IRestResponse response = client.Execute(request);

                    if (response.StatusCode == HttpStatusCode.OK ||
                        response.StatusCode == HttpStatusCode.Created ||
                        response.StatusCode == HttpStatusCode.Accepted)
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(response.Content);
                        var responseData = new ResponseModel()
                        {
                            XmlDoc     = xmlDoc,
                            StatusCode = response.StatusCode,
                        };
                        return(responseData);
                    }
                    else
                    {
                        var responseData = new ResponseModel()
                        {
                            XmlDoc     = null,
                            StatusCode = response.StatusCode,
                        };

                        return(responseData);
                    }
                }
                else if (action == 2)
                {
                    HttpRequest httpRequest = new HttpRequest();
                    IResopnse   response    = httpRequest.Get(URL);

                    if (response.StatusCode == HttpStatusCode.OK ||
                        response.StatusCode == HttpStatusCode.Created ||
                        response.StatusCode == HttpStatusCode.Accepted)
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(response.Result);
                        var responseData = new ResponseModel()
                        {
                            XmlDoc     = xmlDoc,
                            StatusCode = response.StatusCode,
                        };
                        return(responseData);
                    }
                    else
                    {
                        var responseData = new ResponseModel()
                        {
                            XmlDoc     = null,
                            StatusCode = response.StatusCode,
                        };

                        return(responseData);
                    }
                }
                else
                {
                    try
                    {
                        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
                        httpWebRequest.Method          = "GET";
                        httpWebRequest.Timeout         = -1;
                        httpWebRequest.KeepAlive       = true;
                        httpWebRequest.ProtocolVersion = HttpVersion.Version10;
                        httpWebRequest.ServicePoint.ConnectionLimit = 1;
                        using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
                        {
                            if (response.StatusCode == HttpStatusCode.OK ||
                                response.StatusCode == HttpStatusCode.Created ||
                                response.StatusCode == HttpStatusCode.Accepted)
                            {
                                using (Stream s = response.GetResponseStream())
                                {
                                    using (StreamReader sr = new StreamReader(s, System.Text.Encoding.Default))
                                    {
                                        XmlDocument xmlDoc = new XmlDocument();
                                        xmlDoc.Load(sr);
                                        var responseData = new ResponseModel()
                                        {
                                            XmlDoc     = xmlDoc,
                                            StatusCode = response.StatusCode,
                                        };
                                        return(responseData);
                                    }
                                }
                            }
                            else
                            {
                                var responseData = new ResponseModel()
                                {
                                    XmlDoc     = null,
                                    StatusCode = response.StatusCode,
                                };

                                return(responseData);
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        if (ex.Response != null)
                        {
                            HttpWebResponse response = (HttpWebResponse)ex.Response;
                            if (response != null)
                            {
                                using (var stream = response.GetResponseStream())
                                {
                                    using (var streamReader = new StreamReader(stream, Encoding.Default))
                                    {
                                        throw new Exception(string.Format("step:{3},StatusCode:{0}-{1},Result:{2}"
                                                                          , (int)response.StatusCode, response.StatusCode.ToString(), streamReader.ReadToEnd(), ActionStep));
                                    }
                                }
                            }
                        }


                        throw new Exception(string.Format("step:{0},message:{1}", ActionStep, ex.Message));
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("step:{0},message:{1}", ActionStep, ex.Message));
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(null);
        }
Example #52
0
        public virtual async Task <DeleteResponse> DeleteAsync(string resource = null)
        {
            var request = new RestRequest(BuildResourceString(resource), Method.DELETE);

            return(await _client.ExecuteRequestAsync <DeleteResponse>(request));
        }
Example #53
0
 public static Task<IRestResponse> GetResponseContentAsync(RestClient theClient, RestRequest theRequest)
 {
     var tcs = new TaskCompletionSource<IRestResponse>();
     theClient.ExecuteAsync(theRequest, response => {
         tcs.SetResult(response);
     });
     return tcs.Task;
 }