예제 #1
1
 public void ConnectThroughProxy()
 {
     var client = new RestClient(@"https://api.test.nordnet.se/next/");
     IWebProxy proxy = WebRequest.DefaultWebProxy;
     proxy.Credentials = CredentialCache.DefaultCredentials;
     client.Proxy = proxy;
     client.AddDefaultHeader("Accept", "application/json");
     client.AddDefaultHeader("ContentType", "application/x-www-form-urlencoded");
     client.AddDefaultHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36");
     var restRequest = new RestRequest("login");
     IRestResponse response = client.Execute(restRequest);
     Console.Write(response.Content);
 }
예제 #2
0
        private RestSharp.RestClient CreateClient()
        {
            var client = new RestSharp.RestClient(BaseUrl);

            client.AddDefaultHeader("Authorization", $"Bearer {ApiKey}");
            client.AddDefaultHeader("Accept", "application / json");
            return(client);
        }
예제 #3
0
		public RestSharpRestEngine(string userAgent, int timeout)
		{
			_client = new RestSharp.RestClient(Endpoints.BaseApi)
			{
				PreAuthenticate = false
			};
			_client.AddDefaultHeader("accept", "*/*");
			_client.AddDefaultHeader("accept-encoding", "gzip,deflate");
            _client.UserAgent = userAgent;
			_client.ReadWriteTimeout = timeout;
		}
예제 #4
0
    UserInfo GetUser()
    {
        var client = new RestClient();
        client.BaseUrl = new Uri("http://localhost:60635");
        client.AddDefaultHeader("Content-Type", "application/json");
        client.AddDefaultHeader("Accept", "application/json");
        var request = new RestRequest();
        request.Resource = "api/Account/GetPlayer/player/ppowell";
        UserInfo user = client.Execute<UserInfo>(request).Data;

        return user;
    }
예제 #5
0
        public RecurlyClient(string sAPIKey)
        {
            mRESTClient = new RestClient();
            mRESTClient.BaseUrl = RECURLY_BASE_URL;
            mRESTClient.AddDefaultHeader("Accept", "application/xml");
            mRESTClient.AddDefaultHeader("Content-Type", "application/xml; charset=utf-8");
            mRESTClient.Authenticator = new HttpBasicAuthenticator(sAPIKey, string.Empty);

            mSerializer = new YAXRestSerializer();

            mRESTClient.AddHandler("application/xml", mSerializer);
            mRESTClient.AddHandler("text/xml", mSerializer);
        }
        public static RestClient ToRestClient(this string baseAddress)
        {
            if(string.IsNullOrEmpty(baseAddress))
                throw new Exception("Base Address for http client cannot be empty");

            var client = new RestClient(baseAddress);
            client.AddDefaultHeader("Accept", JsonMediaType);
            client.AddDefaultHeader("Accept", XmlMediaType);
            client.AddDefaultHeader("Accept", HtmlMediaType);
            client.AddDefaultHeader("AcceptEncoding", GZipEncodingType);
            client.AddDefaultHeader("AcceptEncoding", DeflateEncodingType);
            return client;
        }
예제 #7
0
        public static void SendGridMessage(SendGridMessage message)
        {
            var userName = ConfigurationManager.AppSettings["SendGrid:UserName"];
            var pwd = ConfigurationManager.AppSettings["SendGrid:Password"];
            var fromAddress = ConfigurationManager.AppSettings["SendGrid:SenderAddress"];
            var fromName = ConfigurationManager.AppSettings["SendGrid:SenderName"];
            var recipients = ConfigurationManager.AppSettings["SendGrid:Recipients"].Split(';');

            var baseUri = new Uri(baseUriString);
            var client = new RestClient(baseUri);
            client.AddDefaultHeader("Accept", "application/json");

            string destinations = string.Empty;

            var requestApiUrl = $"api/mail.send.json";

            var request = new RestRequest(requestApiUrl, Method.POST);
            request.AddParameter("api_user", userName);
            request.AddParameter("api_key", pwd);
            foreach (var recipient in recipients)
                request.AddParameter("to[]", recipient);
            request.AddParameter("subject", message.Subject);
            request.AddParameter("text", message.Text);
            request.AddParameter("from", fromAddress);
            request.AddParameter("fromname", fromName);

            var responseBGuest = client.Execute(request);
            if (responseBGuest.ErrorException != null)
            {
                var exception = responseBGuest.ErrorException;
                System.Console.WriteLine($"Bad response {exception}");
            }
        }
예제 #8
0
        public Task<Model.Public.User> FindPrivate(int userId, string username, string apiKey)
        {
            restClient.AddDefaultHeader("Authorization", "ApiKey " + username + ":" + apiKey);
            IRestRequest request = new RestRequest(PRIVATE_API_URI + USER_API_RESOURCE + "/{userId}/", Method.GET);
            request.AddUrlSegment("userId", userId.ToString());
            var taskCompletionSource = new TaskCompletionSource<Model.Public.User>();

            restClient.ExecuteAsync<Model.Public.User>(request, (response) =>
                {
                    if (response.ResponseStatus == ResponseStatus.Error)
                    {
                        taskCompletionSource.TrySetException(new ApiRequestException("Error de conexión realizando petición a la API en el método Find()"));
                    }

                    if (response.ResponseStatus == ResponseStatus.Completed &&
                        response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var item = response.Data;
                        taskCompletionSource.TrySetResult(item);
                    }
                    else if (response.ResponseStatus == ResponseStatus.Completed &&
                            (response.StatusCode == System.Net.HttpStatusCode.NotFound ||
                             response.StatusCode == System.Net.HttpStatusCode.BadRequest ||
                             response.StatusCode == System.Net.HttpStatusCode.InternalServerError))
                    {
                        taskCompletionSource.TrySetException(
                            new ApiRequestException("Error realizando petición a la API en el método Find(): " + response.StatusCode + " " + response.StatusDescription));
                    }
                });

            return taskCompletionSource.Task;
        }
예제 #9
0
        internal static OperationResult <string> SendRequest(string serviceUrl, RestRequest restRequest, string token, bool resend = false)
        {
            var result = new OperationResult <string>();
            var client = new RestSharp.RestClient(serviceUrl);

            client.AddDefaultHeader("Authorization", $"bearer {token}");
            var response = client.Execute(restRequest);

            if (response.StatusCode != System.Net.HttpStatusCode.OK && !resend)
            {
                client   = new RestSharp.RestClient(serviceUrl);
                response = client.Execute(restRequest);
            }

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                result.SetSucces(response.Content);
            }
            else
            {
                result.SetError(response);
            }

            return(result);
        }
예제 #10
0
        public static void Start()
        {
            var configuration = new ConfigurationBuilder()
                                //order does matters
                                .AddJsonFile("appsettings.json")
                                .AddEnvironmentVariables()
                                .Build();

            IServiceCollection services = new ServiceCollection();

            services.AddLogging((builder) =>
            {
                builder.AddConfiguration(configuration);
                builder.AddConsole((cnf) => { cnf.IncludeScopes = true; });
            });

            services.AddTransient <RestSharp.RestClient>(c =>
            {
                var client           = new RestSharp.RestClient(configuration.GetValue <string>("ApiUrl"));
                client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(
                    configuration.GetValue <string>("ApiUsername"),
                    configuration.GetValue <string>("ApiPassword"));
                client.AddDefaultHeader("X-Company", configuration.GetValue <string>("ApiCompanyAlias"));
                return(client);
            });
            services.AddTransient <IRestClientService, RestClientService>();
            Container = services.BuildServiceProvider();


            /* Start services */
            var data = Container.GetService <IRestClientService>().GetObjectsFilter("KarelEXT");


            var data2 = Container.GetService <IRestClientService>().GetObjects(0, 500);
        }
        /// <summary>
        /// Gets the user's accounts list with it's permissions.
        /// </summary>
        /// <example>
        /// Get list
        /// <code>
        /// var balance = api.Assets();
        /// </code>
        /// </example>
        /// <returns>List of user accounts with permissions of each one.</returns>
        public IList <ProductInformation> Assets()
        {
            var header = Headers.Operation(application, user.AccessToken);

            var client = new RestSharp.RestClient(UrlFormatter.GetEndpointUrl(application, BestBankEndpoint.Assets));

            RestRequest request = new RestRequest(Method.POST);

            client.AddDefaultHeader("Authorization", header);

            var response = client.Execute(request);

            try
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return(JsonConvert.DeserializeObject <IList <ProductInformation> >(response.Content));
                }

                throw new BestBankAPIException(response);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #12
0
		public TwitchRestClient(IConfig config)
		{
			_config = config;
			_restClient = new RestClient(_TWITCH_API_URL);
			_restClient.AddHandler("application/json", new JsonDeserializer());
			_restClient.AddDefaultHeader("Accept", "application/vnd.twitchtv.v3+json");
		}
예제 #13
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<TwitchClientFactory>().As<ITwitchClientFactory>().SingleInstance();
            builder.Register<Func<string, Method, IRestRequest>>(c => (uri, method) =>
                                                                      {
                                                                          var request = new RestRequest(uri, method);
                                                                          //Add any client or auth tokens here
                                                                          //request.AddHeader("Client-ID", "");
                                                                          //request.AddHeader("Authorization", string.Format("OAuth {0}", "oauth-token"));
                                                                          return request;
                                                                      }).AsSelf().SingleInstance();
            builder.Register(c =>
                             {
                                 var restClient = new RestClient("https://api.twitch.tv/kraken");
                                 restClient.AddHandler("application/json", new DynamicJsonDeserializer());
                                 restClient.AddDefaultHeader("Accept", "application/vnd.twitchtv.v2+json");
                                 return restClient;
                             }).As<IRestClient>().SingleInstance();
            builder.Register(c =>
                             {
                                 var restClient = c.Resolve<IRestClient>();
                                 var requestFactory = c.Resolve<Func<string, Method, IRestRequest>>();
                                 return c.Resolve<ITwitchClientFactory>().CreateStaticReadonlyClient(restClient, requestFactory);
                             }).InstancePerHttpRequest();

        }
예제 #14
0
        public RestSharpEngine(DiscordConfig config, string baseUrl, ILogger logger)
        {
            _config = config;
            _logger = logger;

            _rateLimitLock = new AsyncLock();
            _client        = new RestSharpClient(baseUrl)
            {
                PreAuthenticate  = false,
                ReadWriteTimeout = DiscordConfig.RestTimeout,
                UserAgent        = config.UserAgent
            };
            _client.Proxy = null;
            _client.RemoveDefaultParameter("Accept");
            _client.AddDefaultHeader("accept", "*/*");
            _client.AddDefaultHeader("accept-encoding", "gzip,deflate");
        }
예제 #15
0
        public RestSharpEngine(DiscordConfig config, string baseUrl, Logger logger)
		{
			_config = config;
            Logger = logger;

            _rateLimitLock = new AsyncLock();
            _client = new RestSharpClient(baseUrl)
			{
				PreAuthenticate = false,
				ReadWriteTimeout = _config.RestTimeout,
				UserAgent = config.UserAgent
            };
			_client.Proxy = null;
            _client.RemoveDefaultParameter("Accept");
            _client.AddDefaultHeader("accept", "*/*");
			_client.AddDefaultHeader("accept-encoding", "gzip,deflate");
        }
예제 #16
0
 public void SetToken(string token)
 {
     _client.RemoveDefaultParameter("authorization");
     if (token != null)
     {
         _client.AddDefaultHeader("authorization", token);
     }
 }
예제 #17
0
 public void Setup()
 {
     _restClient = new RestClient(_twitchApiUrl);
     _restClient.AddHandler("application/json", new DynamicJsonDeserializer());
     _restClient.AddDefaultHeader("Accept", _twitchAcceptHeader);
     Func<string, Method, IRestRequest> requestFunc = (url, method) => new RestRequest(url, method);
     _twitchClient = new TwitchReadOnlyClient(_restClient, requestFunc);
 }
예제 #18
0
        public SharpRestEngine(DiscordAPIClientConfig config)
		{
			_config = config;
			_client = new RestSharp.RestClient(Endpoints.BaseApi)
			{
				PreAuthenticate = false,
				ReadWriteTimeout = _config.APITimeout,
				UserAgent = _config.UserAgent
			};
			if (_config.ProxyUrl != null)
				_client.Proxy = new WebProxy(_config.ProxyUrl, true, new string[0], _config.ProxyCredentials);
			else
				_client.Proxy = null;
            _client.RemoveDefaultParameter("Accept");
            _client.AddDefaultHeader("accept", "*/*");
			_client.AddDefaultHeader("accept-encoding", "gzip,deflate");
        }
예제 #19
0
파일: Program.cs 프로젝트: remotex/Samples
        private static void Main(string[] args)
        {
            var apiBaseUrl = args[0];
            var username = args[1];
            var password = args[2];
            var client = new RestClient(apiBaseUrl)
                {
                    Authenticator = new HttpBasicAuthenticator(username, password)
                };
            client.AddDefaultHeader("Accept", "application/json");

            Console.WriteLine("API base: " + apiBaseUrl);

            Console.WriteLine();
            Console.WriteLine("This sample will put a series of commands to the commands endpoint.");
            Console.WriteLine("The commands will update a Remotex workorder status, update title and creata an usagequantity/artikle row");
            Console.WriteLine("Operations used in this sample: POST");
            Console.WriteLine();
            Console.WriteLine("Press any key to begin...");
            Console.ReadKey();

            // The case "cases/130610-0027", resource "resources/130225-0011" and workorder reference "workorders/130610-0027-1"
            // are just example href based on the command xml files.

            // Based on UpdateWorkOrderStatus.xml
            var workOrderStatus = Commands.UpsertWorkOrder("workorders/130610-0027-1")
                                                .Parameter("State", "NotStarted"); // NotStarted/Started/Finished

            // Based on UpdateWorkOrderTitle.xml
            var workOrderTitleAndDescription = Commands.UpsertWorkOrder("workorders/130610-0027-1")
                    .Parameter("Title", "New title")
                    .Parameter("Description", "Updated using commands sample");

            // Based on CreateUsageQuantity.xml
            var addUsageQuantity = Commands.CreateUsageQuantity("cases/130610-0027", "resources/130225-0011",
                                                                new Dictionary<string, string>
                                                                    {
                                                                       { "Activity", "System.Picklist.UsageQuantity.Activity.Felsökning" },
                                                                       { "Description", "Demo lägga till text"}
                                                                    });

            var batch = CommandBatch.Create(new[] { workOrderStatus, workOrderTitleAndDescription, addUsageQuantity });

            var request = new RestRequest("commands", Method.POST) {RequestFormat = DataFormat.Json}
                .AddBody(batch);

            var commandResponse = client.Execute<CommandBatch>(request);

            Console.WriteLine("Status for update: " + commandResponse.StatusCode);
            if (commandResponse.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Command successfull");
            }

            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
예제 #20
0
 public SmsTechWrapper(IRavenDocStore documentStore)
 {
     var smsTechUrl = ConfigurationManager.AppSettings["SMSTechUrl"];
     DocumentStore = documentStore;
     using (var session = DocumentStore.GetStore().OpenSession("Configuration"))
     {
         var smsTechConfiguration = session.Load<SmsTechConfiguration>("SmsTechConfig");
         if (smsTechConfiguration == null)
             throw new ArgumentException("Could not find sms tech configuration");
         TransmitSmsClient = new TransmitSms.TransmitSmsWrapper(smsTechConfiguration.ApiKey, smsTechConfiguration.ApiSecret, smsTechUrl);
         /* - ALL FOR CHECKING TRANSMIT SMS NUGET PACKAGE */
         var baseUrl = smsTechUrl;
         var authHeader = string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", smsTechConfiguration.ApiKey, smsTechConfiguration.ApiSecret))));
         RestClient = new RestClient(baseUrl);
         RestClient.AddDefaultHeader("Authorization", authHeader);
         RestClient.AddDefaultHeader("Accept", "application/json");
     }
 }
예제 #21
0
        public StackExchange()
        {
            client = new RestClient
            {
                BaseUrl = apiRepo
            };

            client.AddDefaultHeader("Accept", "application/vnd.github.beta+json");
        }
예제 #22
0
        /// <summary>
        /// Create an HeyWatchClient instance
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <example>
        /// HeyWatchClient HeyWatch = new HeyWatchClient("username", "passwd");
        /// </example>
        public HeyWatchClient(string Username, string Password)
        {
            Cli = new RestClient("https://heywatch.com");
            Cli.Authenticator = new HttpBasicAuthenticator(Username, Password);
            Cli.AddDefaultHeader("Accept", "application/json");
            Cli.UserAgent = "HeyWatch dotnet/1.0.0";

            Json = new JavaScriptSerializer();
        }
예제 #23
0
        /// <summary>
        /// Create an CoconutClient instance
        /// </summary>
        /// <param name="APIKey"></param>
        /// <example>
        /// CoconutClient Coconut = new CoconutClient("k-myapikey");
        /// </example>
        public CoconutAPI(string APIKey)
        {
            Cli = new RestClient("https://api.coconut.co");
            Cli.Authenticator = new HttpBasicAuthenticator(APIKey, "");
            Cli.AddDefaultHeader("Accept", "application/json");
            Cli.UserAgent = "Coconut/2.0.0 (dotnet)";

            Json = new JavaScriptSerializer();
        }
예제 #24
0
 public RecurlyInvoice VerifyToken(string token)
 {
     RestClient reqclient = new RestClient(_baseUrl);
     RestRequest request = new RestRequest("recurly_js/result/{token}",Method.GET);
     request.AddParameter("token",token,ParameterType.UrlSegment);
     //    reqclient.AddDefaultHeader("Accept", "application/xml");
     reqclient.AddDefaultHeader("Authorization", AuthorizationHeaderValue);
     var resp = reqclient.Execute<RecurlyInvoice>(request);
     return resp.Data;
 }
예제 #25
0
 public SharpRestEngine(DiscordAPIClientConfig config)
 {
     _config = config;
     _client = new RestSharp.RestClient(Endpoints.BaseApi)
     {
         PreAuthenticate  = false,
         ReadWriteTimeout = _config.APITimeout,
         UserAgent        = _config.UserAgent
     };
     if (_config.ProxyUrl != null)
     {
         _client.Proxy = new WebProxy(_config.ProxyUrl, true, new string[0], _config.ProxyCredentials);
     }
     else
     {
         _client.Proxy = null;
     }
     _client.RemoveDefaultParameter("Accept");
     _client.AddDefaultHeader("accept", "*/*");
     _client.AddDefaultHeader("accept-encoding", "gzip,deflate");
 }
예제 #26
0
        /// <summary>
        /// Sets up a new bot with the given authtoken.
        /// </summary>
        /// <param name="authToken">The authorization token for your bot</param>
        public TelegramBot(string authToken)
        {
            if (String.IsNullOrWhiteSpace(authToken))
            {
                throw new ArgumentNullException("authToken", "Your authtoken must be valid. Message @Botfather on Telegram to get one.");
            }

            AuthToken = authToken;
            PollingTimeout = 5;
            _client = new RestClient(ApiUrl);
            _client.AddDefaultHeader("Content-Type", "application/x-www-form-urlencoded ; charset=UTF-8");
            SimpleJson.CurrentJsonSerializerStrategy = new TelegramSerializationStrategy();
        }
        public SimpleBlobstoreClient(BlobstoreOptions options)
            : base(options)
        {
            this.client = new RestClient();

            if (false == String.IsNullOrWhiteSpace(options.User) &&
                false == String.IsNullOrWhiteSpace(options.Password))
            {
                string authInfo = String.Format("{0}:{1}", options.User, options.Password);
                string authHeader = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
                client.AddDefaultHeader("Authorization", authHeader);
            }
        }
예제 #28
0
        /// <summary>
        /// Sets up a new bot with the given authtoken.
        /// </summary>
        /// <param name="authenticationToken">The authorization token for your bot</param>
        public TeleSharp(string authenticationToken)
        {
            if (string.IsNullOrWhiteSpace(authenticationToken))
                throw new ArgumentNullException(nameof(authenticationToken));

            _authToken = authenticationToken;
            _botClient = new RestClient(Resources.TelegramAPIUrl + _authToken);
            _botClient.AddDefaultHeader(Resources.HttpContentType, Resources.TeleSharpHttpClientContentType);

            SimpleJson.CurrentJsonSerializerStrategy = new SnakeCaseSerializationStrategy();

            // Receive messages
            new Task(HandleMessages).Start();
        }
        public CompanyInfo GetCompanyInfo(string name)
        {
            var client = new RestClient("http://cvrapi.dk/api");
            client.AddDefaultHeader("User-Agent", "https://github.com/AndersRasmussen/SharePoint.CvrService");

            var request = new RestRequest(Method.GET);

            request.AddParameter("search", name);
            request.AddParameter("country", "dk");

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

            return response.Data;
        }
        public void Setup()
        {
            _restClient = new RestClient(_twitchApiUrl);
            _restClient.AddHandler("application/json", new DynamicJsonDeserializer());
            _restClient.AddDefaultHeader("Accept", _twitchAcceptHeader);

            Func<string, Method, IRestRequest> requestFunc = (url, method) => { 
                var restRequest = new RestRequest(url, method);
                restRequest.AddHeader("Client-ID", "fakeclientid");
                restRequest.AddHeader("Authorization", string.Format("OAuth {0}", "fakeauth"));
                return restRequest;
            };
            _twitchClient = new TwitchAuthenticatedClient(_restClient, requestFunc);
        }
        /// <summary>
        /// Starts a tranfer requeriment between one specific user's account to another account. The transfer is only complete after the user type the SMS code sent to him.
        /// </summary>
        /// <param name="accountId">Internal User's Banco Best Account ID</param>
        /// <param name="amount">Money amount</param>
        /// <param name="creditorIBAN">Account's IBAN of who is receiving the transfer</param>
        /// <param name="creditorName">Account's name of who is receiving the transfer</param>
        /// <param name="creditorMessage">A message for who is receiving the transfer</param>
        /// <param name="debitorMessage">A message for who is sending the transfer</param>
        /// <example>
        /// Make simple transfer:
        /// <code>
        /// var withdrawRequirement = api.Transfer("0-G4ECC", 10.5, "PT50006500010000000000154", "Creditor Name", "Creditor Message", "Debitor Message");
        /// </code>
        /// </example>
        /// <returns>Returns a requirement. The transfer is only confirmed after the user type the SMS code sent to him.</returns>
        public OperationRequirement Transfer(string accountId, double amount, string creditorIBAN, string creditorName, string creditorMessage, string debitorMessage, AccountType accountType = AccountType.BankAccount)
        {
            var tranferRequest = new TransferRequestModel
            {
                amount   = amount.ToString(),
                currency = Variables.UniqueCurrency,
                debtor   = new Debtor
                {
                    message = debitorMessage
                },
                creditor = new Creditor
                {
                    account = new Account
                    {
                        currency = Variables.UniqueCurrency,
                        value    = creditorIBAN,
                        _type    = Variables.UniqueAccountType
                    },
                    name    = creditorName,
                    message = creditorMessage,
                }
            };

            var         header  = Headers.Operation(application, user.AccessToken);
            var         client  = new RestSharp.RestClient(UrlFormatter.GetEndpointUrl(application, BestBankEndpoint.Transfer, accountType, accountId));
            RestRequest request = new RestRequest(Method.POST);

            client.AddDefaultHeader("Authorization", header);

            request.AddJsonBody(tranferRequest);

            var response = client.Execute(request);

            try
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responsePaymentCode = JsonConvert.DeserializeObject <PaymentCodeResponseModel>(response.Content);

                    return(new OperationRequirement(this, responsePaymentCode.payment_code, accountId, OperationType.Transfer));
                }

                throw new BestBankAPIException(response);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #32
0
      protected RestClient BuildRestClient()
      {
         if (string.IsNullOrEmpty(Configuration.JiraUrl))
            throw new IncompleteJiraConfiguration();

         var client = new RestClient(Configuration.JiraUrl);
         client.AddDefaultHeader("Content-Type", "Application/json");
         if (string.IsNullOrEmpty(Configuration.SessionCookies) == false)
         {
            client.CookieContainer = new CookieContainer();
            client.CookieContainer.SetCookies(client.BaseUrl, Configuration.SessionCookies);
         }

         return client;
      }
예제 #33
0
        /// <summary>
        /// 获取应用token。
        /// </summary>
        /// <returns>token。</returns>
        public string GetToken()
        {
            var client = new RestClient(Configuration.TokenUrl);
            client.AddDefaultHeader("Content-Type", "application/x-www-form-urlencoded");
            client.Authenticator = new HttpBasicAuthenticator(Configuration.AppKey, Configuration.AppSecret);
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception(response.Content);

            var token = JsonConvert.DeserializeObject<AccessToken>(response.Content).token;
            return token;
        }
예제 #34
0
        public void FetchNowPlayingIntegrationTest()
        {
            var kernel = new MoqMockingKernel();
            var client = new RestClient(IntegrationTestUrl.Current);

            client.AddDefaultHeader("Authorization", IntegrationTestUrl.Token);
            kernel.Bind<IBlobCache>().To<TestBlobCache>();

            var api = new PlayApi(client, kernel.Get<IBlobCache>());

            var result = api.NowPlaying()
                .Timeout(TimeSpan.FromSeconds(9.0), RxApp.TaskpoolScheduler)
                .First();

            this.Log().Info(result.ToString());
            result.id.Should().NotBeNullOrEmpty();
        }
예제 #35
0
        public void MakeAlbumSearchIntegrationTest()
        {
            var kernel = new MoqMockingKernel();
            var client = new RestClient(IntegrationTestUrl.Current);

            client.AddDefaultHeader("Authorization", IntegrationTestUrl.Token);
            kernel.Bind<IBlobCache>().To<TestBlobCache>();

            var api = new PlayApi(client, kernel.Get<IBlobCache>());

            var result = api.AllSongsOnAlbum("LCD Soundsystem", "Sound Of Silver")
                .Timeout(TimeSpan.FromSeconds(9.0), RxApp.TaskpoolScheduler)
                .First();

            this.Log().Info(String.Join(",", result.Select(x => x.name)));
            result.Count.Should().BeGreaterThan(2);
        }
예제 #36
0
        public void TestInit()
        {
            var restClient = new RestClient("http://api.themoviedb.org/3");
            restClient.AddDefaultHeader("Accept", "application/json");
            restClient.AddDefaultParameter("api_key", "cd684dd007b56d859be21f1a4902b2b6");
            //restClient.Proxy = new WebProxy("localhost", 8888);

            var serializer = new JsonSerializer
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                    NullValueHandling = NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Include
                };
            restClient.AddHandler("application/json", new NewtonsoftJsonDeserializer(serializer));

            _searchService = new TmdbDegreeRepository(restClient);
        }
예제 #37
0
        public IRestResponse HacerPeticion(string ruta, string metodo, Dictionary <string, string> parametros, string metodoEnvio, Dictionary <string, string> headers = null, bool peticionBody = false)
        {
            var         client = new RestSharp.RestClient(ruta);
            RestRequest request;

            switch (metodoEnvio)
            {
            case "POST":
                request = new RestRequest(metodo, Method.POST);
                break;

            case "GET":
                request = new RestRequest(metodo, Method.GET);
                break;

            default:
                request = new RestRequest();
                break;
            }

            client.RemoteCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => {
                return(sslPolicyErrors == SslPolicyErrors.None);
            };
            if (headers != null && headers.Count > 0)
            {
                foreach (var item in headers)
                {
                    client.AddDefaultHeader(item.Key, item.Value);
                }
            }

            if (peticionBody)
            {
                request.AddJsonBody(parametros);
            }
            else
            {
                foreach (var p in parametros)
                {
                    request.AddParameter(p.Key, p.Value);
                }
            }

            return(client.Execute(request));
        }
예제 #38
0
        /// <summary>
        /// 获取公有应用token。
        /// </summary>
        /// <param name="code">可在请求中获取。</param>
        /// <returns>token.</returns>
        public string GetToken(string code)
        {
            var client = new RestClient(Configuration.TokenUrl);
            client.AddDefaultHeader("Content-Type", "application/x-www-form-urlencoded");
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "authorization_code");
            request.AddParameter("code", code);
            request.AddParameter("client_id", Configuration.AppKey);
            request.AddParameter("redirect_uri", Configuration.AppRedirectUrl);
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var token = JsonConvert.DeserializeObject<AccessToken>(response.Content).token;
                return token;
            }

            return null;
        }
        public DigitalOceanClient(string token) {
            var client = new RestClient(DigitalOceanApiUrl) {
                UserAgent = "digitalocean-api-dotnet"
            };
            client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", token));

            _connection = new Connection(client);

            Actions = new ActionsClient(_connection);
            DomainRecords = new DomainRecordsClient(_connection);
            Domains = new DomainsClient(_connection);
            DropletActions = new DropletActionsClient(_connection);
            Droplets = new DropletsClient(_connection);
            ImageActions = new ImageActionsClient(_connection);
            Images = new ImagesClient(_connection);
            Keys = new KeysClient(_connection);
            Regions = new RegionsClient(_connection);
            Sizes = new SizesClient(_connection);
        }
예제 #40
0
        public void SearchAsync(string hashTag, int numberTweets, Action<Error,List<Tweet>> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException ("callback");
            }

            var client = new RestClient (_host);

            var queryRequest = new RestRequest (_requestURL, Method.GET); // old api search.json
            queryRequest.AddParameter ("q", hashTag);
            //queryRequest.AddParameter("rpp", userCount); //old twitter Api 1.0
            queryRequest.AddParameter ("count", numberTweets);
            //queryRequest.AddParameter ("include_entities", true);

            client.AddDefaultHeader ("Authorization", "Bearer " + _authorizationService.BearerToken );

            client.AddHandler ("application/json", new JsonDeserializer ());
            //var responseTweets = client.Execute<TwitterSearchResponse>(queryRequest);

            client.ExecuteAsync<TwitterSearchResponse> (queryRequest, response =>
                                                        {
                var listTweets = new List<Tweet> ();
                Error error = null;
                try
                {
                    if (response.ResponseStatus != ResponseStatus.Completed)
                    {
                        error = new Error (response.ResponseStatus);
                    }
                    listTweets = ParseTweet (response.Data.statuses);
                }
                catch (Exception ex)
                {
                    error = new Error ("Tweets loading error", ex);
                }

                callback (error, listTweets);

            });
        }
예제 #41
0
        /// <summary>
        /// This method is the first step of the authorizaton flow. It will return the Banco Best user login url where the user will allow the application to connect to his own account.
        /// </summary>
        /// <example>
        /// <code>
        /// AuthorizationFlow.GetBankLoginUrl(myApplication,"http://www.myapplication.com/returnLogin");
        /// </code>
        /// </example>
        /// <param name="application">Application representation</param>
        /// <param name="redirectUrl">URL where the user will be redirected after succesful login to the application.</param>
        /// <param name="state">Custom application variable that will be returned with the 'redirectUrl' as param.</param>
        /// <param name="response_type">Response Type Code</param>
        /// <param name="scope">Scope</param>
        /// <returns>Login URL at the Banco Best website where the application must redirect the user.</returns>
        public static Uri GetBankLoginUrl(Application application, string redirectUrl, string state = "none", int response_type = 200, string scope = "none")
        {
            var header = Headers.Login(application, redirectUrl, response_type, scope, state);

            var client = new RestSharp.RestClient(UrlFormatter.GetEndpointUrl(application, BestBankEndpoint.Initiate));

            RestRequest request = new RestRequest(Method.POST);

            client.AddDefaultHeader("Authorization", header);

            var response = client.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var loginUrl = JsonConvert.DeserializeObject <LoginResponseModel>(response.Content).LoginUrl;

                return(new Uri(loginUrl));
            }

            throw new BestBankAPIException(response);
        }
예제 #42
0
        /// <summary>
        /// This is the second step of the authorization flow. Get the User object containing his access token.
        /// See <see cref="AuthorizationFlow.GetBankLoginUrl(Application, string, string, int, string)"/> to start the first step.
        /// </summary>
        /// <param name="application">Application representation</param>
        /// <param name="temporaryCode">
        /// Parameters returned after the user return to the application.
        /// See <see cref="AuthorizationFlow.GetBankLoginUrl(Application, string, string, int, string)"/> if you have no temporary code.
        /// </param>
        /// <param name="grand_type">Grand type</param>
        /// <returns>User object containing his access token and ready to start to make operations.</returns>
        /// See <see cref="AuthorizationFlow.GetBankLoginUrl(Application, string, string, int, string)"/> to make the first step.
        public static User GetUserAccessToken(Application application, string temporaryCode, string grand_type = "none")
        {
            var header = Headers.AccessToken(application, temporaryCode, grand_type);

            var client = new RestSharp.RestClient(UrlFormatter.GetEndpointUrl(application, BestBankEndpoint.Token));

            RestRequest request = new RestRequest(Method.POST);

            client.AddDefaultHeader("Authorization", header);

            var response = client.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseTokenObj = JsonConvert.DeserializeObject <RequestTokenResponseModel>(response.Content);

                return(new User(responseTokenObj.access_token));
            }

            throw new BestBankAPIException(response);
        }
        /// <summary>
        /// Confirm and complete the transfer or the payment.
        /// </summary>
        /// <param name="smsCode">SMS Code sent to the user. In Sandbox, the only value is '1234'.</param>
        /// <returns>
        /// Confirms is the tranfer or payment was completed.
        /// </returns>
        /// <exception cref="BestBankAPIException"></exception>
        public bool Confirm(string smsCode)
        {
            if (this.isConfirmed)
            {
                return(true);
            }

            var confirmRequest = new ConfirmPaymentRequestModel
            {
                payment_code = paymentCode,
                sms_code     = smsCode
            };

            var         header  = Headers.Operation(api.Application, api.User.AccessToken);
            var         client  = new RestSharp.RestClient(UrlFormatter.GetEndpointUrl(api.Application, BestBankEndpoint.ConfirmPayment));
            RestRequest request = new RestRequest(Method.POST);

            client.AddDefaultHeader("Authorization", header);

            request.AddJsonBody(confirmRequest);

            var response = client.Execute(request);

            try
            {
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    return(true);
                }

                throw new BestBankAPIException(response);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #44
0
 public static void AddBillyAuthentication(this RestSharp.RestClient client, string key)
 {
     client.AddDefaultHeader("X-Access-Token", key);
 }
        private void SignIn()
        {
            RestRequest request = new RestRequest("Sitefinity/Authenticate", Method.GET);

            IRestResponse response = _restClient.Execute(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:

                var    formData = String.Format("wrap_name={0}&wrap_password={1}", _username, _password);
                var    bytes    = Encoding.UTF8.GetBytes(formData);
                string strResponse;
                WebHeaderCollection headers;
                var responseCode = Request(_restClient.BaseUrl + "Sitefinity/Authenticate/SWT", out strResponse, out headers, bytes, "POST", "application/x-www-form-urlencoded");

                if (responseCode == HttpStatusCode.OK)
                {
                    // we expect WRAP formatted response which is the same as query string
                    var nameValueColl  = HttpUtility.ParseQueryString(strResponse);
                    var bootstrapToken = nameValueColl["wrap_access_token"];
                    expiresOn = DateTime.Now + TimeSpan.FromSeconds(int.Parse(nameValueColl["wrap_access_token_expires_in"]));
                    _restClient.AddDefaultHeader("Authorization", String.Format("WRAP access_token=\"{0}\"", bootstrapToken));
                }
                if (responseCode == HttpStatusCode.Unauthorized)
                {
                    // This means wrong credentials were submitted

                    throw new Exception("Wrong credential");
                }

                /*
                 * request = new RestRequest("Sitefinity/Authenticate/SWT?realm={realm}&redirect_uri={redirectUri}&deflate=true", Method.POST);
                 *
                 * request.AddUrlSegment("realm", _baseUrl);
                 * request.AddUrlSegment("redirectUri", "/Sitefinity");
                 *
                 * request.AddParameter("wrap_name", _username, ParameterType.GetOrPost);
                 * request.AddParameter("wrap_password", _password, ParameterType.GetOrPost);
                 * request.AddParameter("sf_persistent", "true", ParameterType.GetOrPost);
                 *
                 * response = _restClient.Execute(request);
                 *
                 *
                 * switch (response.StatusCode)
                 * {
                 *  case HttpStatusCode.OK:
                 *      if (response.ResponseUri.AbsolutePath == "/Sitefinity/SignOut/selflogout")
                 *      {
                 *          SelfLogout();
                 *      }
                 *      break;
                 *  case HttpStatusCode.Unauthorized:
                 *      throw new SitefinityException("Invalid username or password");
                 *  default:
                 *      break;
                 * }*/
                break;

            case HttpStatusCode.Redirect:
                throw new NotImplementedException("External STS not supported");

            default:
                throw new Exception("Unable get Sitefinity/Authenticate Page");
            }
        }