public static void MoveObjects(IRestClient restClient, long[] pFileIds, long pFromId, long pToId,
            TransactionResponse transaction = null)
        {
            if (pFileIds == null || pFileIds.Length == 0)
                return;

            var createRequest = new RestRequest("api/rest/object/move/{id}", Method.POST);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);

            for (var i = 0; i < pFileIds.Length; i++)
            {
                if (i == 0)
                    createRequest.AddUrlSegment("id", pFileIds[i].ToString("D"));
                else
                    createRequest.AddParameter("id", pFileIds[i].ToString("D"));
            }
            createRequest.AddParameter("target", pToId.ToString("D"));
            createRequest.AddParameter("parameters", createRequest.JsonSerializer.Serialize(new
            {
                parent = new[] {pFromId.ToString("D")},
                inheritAcl = true
            }));

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);
        }
        public static void CreateLinks(IRestClient restClient, long sourceFileId, long[] destFolderId,
                                      TransactionResponse transaction = null)
        {
            if (destFolderId == null || destFolderId.Length == 0)
                return;

            var createRequest = new RestRequest("api/rest/object/link/{id}", Method.POST);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);

            createRequest.AddUrlSegment("id", sourceFileId.ToString("D"));

            foreach (var value in destFolderId)
            {
                createRequest.AddParameter("target", value.ToString("D"));
            }
            createRequest.AddParameter("parameters", createRequest.JsonSerializer.Serialize(new {aclfromtarget = true}));

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse, "duplicate entry");

            //var createRequest = new RestRequest("/api/rest/parse/xml", Method.POST);
            //if (transaction != null)
            //    createRequest.AddParameter("transactionId", transaction.TransactionId);
            //createRequest.AddParameter("xml", AgorumFile.GenerateLinkObjectToFolderXml(sourceFileId, destFolderId));

            //var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);

            //ThrowIfNotSuccessful(tmpResponse, "duplicate");
        }
 public static void Logout(IRestClient restClient)
 {
     var request = new RestRequest("api/rest/session/logout", Method.POST);
     var responseData = restClient.Execute<RestResponseBaseExt>(request);
     //Dont throw Exception as it doesnt matter if Logout has worked
     //ThrowIfNotSuccessful(responseData);
 }
        public static void CreateFolder(IRestClient restClient, AgorumFolder folder,
                                        TransactionResponse transaction = null)
        {
            var createRequest = new RestRequest("api/rest/object", Method.POST);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);
            createRequest.AddParameter("handler", "object");

            createRequest.AddParameter("data", createRequest.JsonSerializer.Serialize(new Data
                {
                    classname = folder.Classname,
                    name = AgorumObject.RemoveIllegalChars(folder.Name),
                    target = folder.AnyFolderPathId != 0 ? folder.AnyFolderPathId.ToString() : GetAgorumAbsolutePath(folder.AnyFolderPath),
                    createtarget = folder.AnyFolderPathId == 0
                }));

            foreach (var property in folder.GetProperties())
            {
                createRequest.AddParameter("properties", property);
            }

            var tmpResponse = restClient.Execute<RestResponseBaseExt<AgorumFolder>>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);

            folder.FillFromObject(tmpResponse.Data.Data);
        }
Пример #5
0
 private static void CommitEdit(IRestClient restClient, string accessToken, string applicationId, string editId)
 {
     Console.WriteLine("Committing edit");
     var request = new RestRequest("/androidpublisher/v2/applications/{applicationId}/edits/{editId}:commit", Method.POST);
     request.AddUrlSegment("applicationId", applicationId);
     request.AddUrlSegment("editId", editId);
     request.AddQueryParameter("access_token", accessToken);
     var response = restClient.Execute<EditResponse>(request);
     CheckResponse(response);
 }
Пример #6
0
 private static string CreateEdit(IRestClient restClient, string applicationId, string accessToken)
 {
     Console.WriteLine("Creating edit");
     var request = new RestRequest("/androidpublisher/v2/applications/{applicationId}/edits", Method.POST);
     request.AddUrlSegment("applicationId", applicationId);
     request.AddQueryParameter("access_token", accessToken);
     var response = restClient.Execute<EditResponse>(request);
     CheckResponse(response);
     return response.Data.Id;
 }
        public static void Login(IRestClient restClient, string pUsername, string pPassword)
        {
            var request = new RestRequest("api/rest/session/login", Method.POST);
            request.AddParameter("username", pUsername);
            request.AddParameter("password", pPassword);

            // execute the request
            var responseData = restClient.Execute<LoginResponse>(request);
            ThrowIfNotSuccessful(responseData);
        }
        public static void CommitTransaction(IRestClient restClient, TransactionResponse transaction, bool abortTransaction = false)
        {
            var request = new RestRequest("api/rest/session/transaction/{id}", Method.DELETE);
            //request.AddParameter("id", transaction.TransactionId);
            request.AddUrlSegment("id", transaction.TransactionId);
            request.AddParameter("rollback", abortTransaction); //If true, Transaction gets aborted

            // execute the request
            var responseData = restClient.Execute<RestResponseBaseExt>(request);
            ThrowIfNotSuccessful(responseData);
        }
        public static TransactionResponse CreateTransaction(IRestClient restClient)
        {
            var request = new RestRequest("api/rest/session/transaction ", Method.POST);
            request.AddParameter("timeout", 300); //5 Minuten Timeout

            // execute the request
            var responseData = restClient.Execute<TransactionResponse>(request);
            ThrowIfNotSuccessful(responseData);

            return responseData.Data;
        }
        public static void DeleteObject(IRestClient restClient, long id, TransactionResponse transaction = null)
        {
            var createRequest = new RestRequest("api/rest/object/{id}", Method.DELETE);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);
            createRequest.AddParameter("handler", "object");
            createRequest.AddUrlSegment("id", id.ToString("D"));

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);
        }
        public static void UpdateAndRenameObject(IRestClient restClient, AgorumObject agObject, TransactionResponse transaction = null)
        {
            //Angabe von Id nicht nötig, da XML ObjectZuweisungen in XML-Anweisung hat und nicht zu einem bestimmten Object hochgeladen wird.
            var createRequest = new RestRequest("/api/rest/parse/xml", Method.POST);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);
            createRequest.AddParameter("xml", agObject.GenerateUpdateObjectXml());

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);
        }
Пример #12
0
 public string AddUserToJiraGroup(JiraDeveloper newdeveloper, string role, IRestClient client)
 {
     var requestBody = string.Format("group/user?groupname={0}", role);
     var request = new RestRequest(requestBody, Method.POST);
     request.RequestFormat = DataFormat.Json;
     request.AddBody(new
     {
         name = newdeveloper.name
     });
     var resp = client.Execute(request);
     return AnalyzeResponse(resp);
 }
        public static void DeleteLink(IRestClient restClient, long fileId, long parentId,
                                       TransactionResponse transaction = null)
        {
            var createRequest = new RestRequest("api/rest/object/{id}", Method.DELETE);
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);
            createRequest.AddUrlSegment("id", fileId.ToString("D"));
            createRequest.AddParameter("parameters", createRequest.JsonSerializer.Serialize(new { parent = parentId.ToString("D") }));

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);
        }
Пример #14
0
			public async Task GetAccessTokenAsync(IRestClient client, string authCode)
			{
				var request = new RestRequest("oauth/token", HttpMethod.Post)
					.AddJsonBody(new 
						{
							code = authCode,
							client_id = ClientId,
							client_secret = ClientSecret,
							redirect_uri = RedirectUri.AbsoluteUri,
							grant_type = "authorization_code"
						});

				var response = await client.Execute<OAuthToken>(request);
				token = response.Data;
			}
        public static void RenameObject(IRestClient restClient, AgorumFile agObject, TransactionResponse transaction = null)
        {
            var createRequest = new RestRequest("/api/rest/object/{id}", Method.PUT);
            createRequest.AddUrlSegment("id", agObject.Id.ToString("D"));
            if (transaction != null)
                createRequest.AddParameter("transactionId", transaction.TransactionId);
            createRequest.AddParameter("updatehandler", "object");

            createRequest.AddParameter("data", createRequest.JsonSerializer.Serialize(new
            {
                name = agObject.Name
            }));

            var tmpResponse = restClient.Execute<RestResponseBaseExt>(createRequest);
            ThrowIfNotSuccessful(tmpResponse);
        }
Пример #16
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var uri = client.BuildUri(request);
            var path = uri.AbsolutePath;

            if( path.EndsWith("/time") && path.Length <= 8 )
            {
                request.AddHeader("CB-VERSION", CoinbaseConstants.ApiVersionDate);
                return;
            }
            string timestamp = null;
            if( useTimeApi )
            {
                var timeReq = new RestRequest("/time", Method.GET)
                    {
                        JsonSerializer = new JsonNetSerializer(jsonSettings)
                    };

                var timeResp = client.Execute<CoinbaseResponse<Time>>(timeReq);
                timestamp = timeResp.Data.Data.Epoch.ToString();
            }
            else
            {
                timestamp = GetCurrentUnixTimestampSeconds().ToString(CultureInfo.InvariantCulture);
            }

            var method = request.Method.ToString().ToUpper(CultureInfo.InvariantCulture);

            var body = string.Empty;

            var param = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            if (param != null && param?.Value?.ToString() != "null" && !string.IsNullOrWhiteSpace(param?.Value?.ToString()))
                body = param.Value.ToString();

            var hmacSig = GenerateSignature(timestamp, method, path, body, this.apiSecret);

            request.AddHeader("CB-ACCESS-KEY", this.apiKey)
                .AddHeader("CB-ACCESS-SIGN", hmacSig)
                .AddHeader("CB-ACCESS-TIMESTAMP", timestamp)
                .AddHeader("CB-VERSION", CoinbaseConstants.ApiVersionDate);
        }
Пример #17
0
 public RetCode CreateObject(RootObject rootObject, IRestClient rClient, string requestResource, out IRestResponse rResponse)
 {
     RestRequest rRequest = new RestRequest();
     rRequest.DateFormat = "yyyy-MM-ddTHH:mm:ss.sss";
     rRequest.Resource = requestResource;
     rRequest.Method = Method.POST;
     rRequest.RequestFormat = DataFormat.Json;
     if (requestResource != "login") Authorize(rootObject);
     rRequest.AddBody(rootObject);
     rResponse = rClient.Execute(rRequest);
     if (rResponse.StatusCode == System.Net.HttpStatusCode.OK)
     {
         if (requestResource != "login") Callbacker.callback(eAction.Message, "Creation Successful.");
         return RetCode.successful;
     }
     else
     {
         Callbacker.callback(eAction.RestError, rResponse.StatusCode, rResponse.ErrorMessage, rResponse.Content);
         return RetCode.unsuccessful;
     }
 }
Пример #18
0
        public void SetUp()
        {
            restRequest = Substitute.For<IRestRequest>();
            restResponse = Substitute.For<IRestResponse>();

            restClient = Substitute.For<IRestClient>();
            restClient.Execute(restRequest).Returns(restResponse);

            factory = Substitute.For<IRequestFactory>();
            factory.NewClient().Returns(restClient);
            factory.NewRequest().Returns(restRequest);

            var configuration = Substitute.For<IClientConfiguration>();

            configuration.ClientId.Returns("client_id");
            configuration.ClientSecret.Returns("client_secret");
            configuration.RedirectUri.Returns("http://redirect-uri.net");
            configuration.Scope.Returns("scope");

            descendant = new OAuth2ClientDescendant(factory, configuration);
        }
Пример #19
0
        public void SetUp()
        {
            restRequest = Substitute.For<IRestRequest>();
            restResponse = Substitute.For<IRestResponse>();

            restResponse.StatusCode.Returns(HttpStatusCode.OK);
            restResponse.RawBytes.Returns(_encoding.GetBytes("response"));

            restClient = Substitute.For<IRestClient>();
            restClient.Execute(restRequest).Returns(Task.FromResult(restResponse));

            factory = Substitute.For<IRequestFactory>();
            factory.CreateClient().Returns(restClient);
            factory.CreateRequest(null).ReturnsForAnyArgs(restRequest);

            var configuration = Substitute.For<IClientConfiguration>();

            configuration.ClientId.Returns("client_id");
            configuration.ClientSecret.Returns("client_secret");
            configuration.RedirectUri.Returns("http://redirect-uri.net");
            configuration.Scope.Returns("scope");

            descendant = new OAuth2ClientDescendant(factory, configuration);
        }
Пример #20
0
        private UTorrentResponse ProcessRequest(IRestRequest request, IRestClient client)
        {
            _logger.Debug("Url: {0}", client.BuildUri(request));
            var clientResponse = client.Execute(request);

            if (clientResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                // Token has expired. If the settings were incorrect or the API is disabled we'd have gotten an error 400 during GetAuthToken
                _logger.Debug("uTorrent authentication token error.");

                _authToken = GetAuthToken(client);

                request.Parameters.First(v => v.Name == "token").Value = _authToken;
                clientResponse = client.Execute(request);
            }
            else if (clientResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new DownloadClientAuthenticationException("Failed to authenticate");
            }

            var uTorrentResult = clientResponse.Read<UTorrentResponse>(client);

            return uTorrentResult;
        }
        /// <summary>
        ///     The check order status.
        /// </summary>
        /// <param name="orderList">
        ///     The order list.
        /// </param>
        /// <param name="webClient">
        ///     The web client.
        /// </param>
        /// <param name="token">
        ///     The token.
        /// </param>
        private void CheckOrderStatus(List<string> orderList, IRestClient webClient, string token)
        {
            foreach (var id in orderList)
            {
                if (this.okToWork)
                {
                    var request = new RestRequest("/raster-catalog/api/gbd/orders/v1/status/" + id, Method.GET);
                    request.AddHeader("Authorization", "Bearer " + token);

                    var result = webClient.Execute<GbdOrder>(request);
                    var keepRunning = true;
                    var numTries = 0;
                    while (keepRunning)
                    {
                        if (result.Data.salesOrderNumber == null && numTries <= 5)
                        {
                            numTries++;
                            result = webClient.Execute<GbdOrder>(request);
                        }
                        else
                        {
                            keepRunning = false;
                        }
                    }

                    // Callback to the main UI thread to update the data table
                    this.Invoke(new UpdateStatusCallback(this.UpdateRecordStatus), result.Data);
                }
            }
        }
Пример #22
0
 public static IRestResponse Patch(this IRestClient client, IRestRequest request)
 => client.Execute(request, Method.PATCH);
Пример #23
0
 public static IRestResponse Delete(this IRestClient client, IRestRequest request)
 => client.Execute(request, Method.DELETE);
Пример #24
0
 public static Task <TResponse> Get <TResponse>(this IRestClient restClient, string resource)
 {
     return(restClient.Execute <TResponse>(resource, RestSharp.Method.GET));
 }
Пример #25
0
        Connect(HttpContext httpContext, string nodeKey)
        {
            var errors = new Dictionary <string, object>();

            // Ok, we aren't already connected. Let's go try talking to the backend and set ourselves up.
            var request = new RestRequest("unauth/node", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            var generatedPassword = PasswordUtils.GeneratePassword(24, 0);
            var body = new UnauthNodeAddRequest {
                InstallId = _identityProvider.GetGuid().ToString()
            };

            var ownIp = await _ipResolver.Resolve();

            body.Ip = ownIp.ToString();

            body.Port = httpContext.Connection.LocalPort;

            body.Protocol = "http"; // TODO: When HTTPs support lands, use -> httpContext.Request.Protocol.ToLower() which returns things like http/1.1 (needs further parsing);

            body.NodeKey     = nodeKey;
            body.AccessToken = _defaultCloudUserName + ":" + generatedPassword;

            // This is data about *THIS* specific system being contributed to the cloud/CRM.
            body.SystemData = _apm.GetAllDetails();
            body.Version    = AppConfig.version;

            // Ok, we got the user created. Everything is ready, let's send off the request.
            var serializedBody = JsonConvert.SerializeObject(body);

            _logger.LogDebug($"We will be sending: {serializedBody}");

            request.AddParameter("application/json; charset=utf-8", serializedBody, ParameterType.RequestBody);

            // We have to ensure this user actually exists before sending off the request.
            // First, we need to remove any cached representation.
            AuthUtils.ClearUserFromCacheIfExists(_cache, _defaultCloudUserName);

            // Check if the cloud connect user exists already.
            var user = await _db.SingleAsync <User>(x => x.AuthKey == _defaultCloudUserName) ?? new User();

            user.AuthKey        = _defaultCloudUserName;
            user.PasswordSetter = generatedPassword;
            user.EmailAddress   = _defaultCloudUserName + $"@spectero.com";
            user.FullName       = "Spectero Cloud Management User";
            user.Roles          = new List <User.Role> {
                User.Role.SuperAdmin
            };
            user.Source        = User.SourceTypes.SpecteroCloud;
            user.CloudSyncDate = DateTime.Now;
            user.CertKey       = PasswordUtils.GeneratePassword(48, 6);

            var userCertBytes = _cryptoService.IssueUserChain(user.AuthKey, new[] { KeyPurposeID.IdKPClientAuth }, user.CertKey);

            user.Cert = Convert.ToBase64String(userCertBytes);

            // Checks if user existed already, or is being newly created.
            if (user.Id != 0L)
            {
                await _db.UpdateAsync(user);
            }
            else
            {
                user.CreatedDate = DateTime.Now;
                await _db.InsertAsync(user);
            }

            var response = _restClient.Execute(request);


            if (response.ErrorException != null)
            {
                _logger.LogError(response.ErrorException, "CC: Connect attempt to the Spectero Cloud failed!");

                errors.Add(Core.Constants.Errors.FAILED_TO_CONNECT_TO_SPECTERO_CLOUD, response.ErrorMessage);

                await DeleteCloudUserIfExists();

                return(false, errors, HttpStatusCode.ServiceUnavailable, null);
            }

            CloudAPIResponse <Node> parsedResponse = null;

            try
            {
                // Parse after error checking.
                parsedResponse = JsonConvert.DeserializeObject <CloudAPIResponse <Node> >(response.Content);
            }
            catch (JsonException e)

            {
                // The Cloud Backend fed us bogus stuff, let's bail.
                _logger.LogError(e, "CC: Connect attempt to the Spectero Cloud failed!");
                _logger.LogDebug("Cloud API said: " + response.Content);

                errors.Add(Core.Constants.Errors.FAILED_TO_CONNECT_TO_SPECTERO_CLOUD, e.Message);

                await DeleteCloudUserIfExists();

                return(false, errors, HttpStatusCode.ServiceUnavailable, parsedResponse);
            }


            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:

                await ConfigUtils.CreateOrUpdateConfig(_db, ConfigKeys.CloudConnectStatus, true.ToString());

                await ConfigUtils.CreateOrUpdateConfig(_db, ConfigKeys.CloudConnectIdentifier, parsedResponse?.result.id.ToString());

                await ConfigUtils.CreateOrUpdateConfig(_db, ConfigKeys.CloudConnectNodeKey, nodeKey);

                break;

            default:
                // Likely a 400 or a 409, just show the response as is.
                errors.Add(Core.Constants.Errors.FAILED_TO_CONNECT_TO_SPECTERO_CLOUD, "");
                errors.Add(Core.Constants.Errors.RESPONSE_CODE, response.StatusCode);
                errors.Add(Core.Constants.Errors.NODE_PERSIST_FAILED, parsedResponse?.errors);

                _logger.LogDebug("Cloud API said: " + response.Content);

                await DeleteCloudUserIfExists();

                return(false, errors, HttpStatusCode.ServiceUnavailable, parsedResponse);
            }

            return(true, errors, HttpStatusCode.OK, parsedResponse);
        }
Пример #26
0
        public ActivitySummary GetDayActivitySummary(DateTime activityDate)
        {
            //RestClient client = new RestClient(baseApiUrl);

            string apiCall = GetActivityApiExtentionURL(activityDate);

            RestRequest request = new RestRequest(apiCall);

            request.RootElement = "summary";

            var response = restClient.Execute <Fitbit.Models.ActivitySummary>(request);

            HandleResponse(response);

            //Console.WriteLine(response.ToString());
            //Console.WriteLine(response.Content);
            //Console.WriteLine(response.Data.steps);

            return(response.Data);
        }
Пример #27
0
 /// <summary>
 /// Executes this instance.
 /// </summary>
 private void Execute()
 {
     restResponse = restClient.Execute <V, E, C>(restRequest);
 }
 public static IRestResponse Delete(this IRestClient client, IRestRequest request)
 {
     request.Method = Method.DELETE;
     return(client.Execute(request));
 }
 public static IRestResponse Patch(this IRestClient client, IRestRequest request)
 {
     request.Method = Method.PATCH;
     return(client.Execute(request));
 }
 public static IRestResponse Options(this IRestClient client, IRestRequest request)
 {
     request.Method = Method.OPTIONS;
     return(client.Execute(request));
 }
Пример #31
0
        public RetCode UpdateObject(RootObject rootObject, IRestClient rClient, string requestResource, string requestResourceId, out IRestResponse rResponse)
        {
            RestRequest rRequest = new RestRequest();
            rRequest.DateFormat = "yyyy-MM-ddTHH:mm:ss.sss";
            rRequest.Resource = requestResource;
            rRequest.Method = Method.PUT;
            rRequest.AddUrlSegment("id", requestResourceId);
            rRequest.RequestFormat = DataFormat.Json;
            Authorize(rootObject);
            rRequest.AddBody(rootObject);
            rResponse = rClient.Execute(rRequest);

            if (rResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Callbacker.callback(eAction.State,"Update Successful");
                return RetCode.successful;
            }
            else
            {
                Callbacker.callback(eAction.RestError, rResponse.StatusCode, rResponse.ErrorMessage, rResponse.Content);
                return RetCode.unsuccessful;
            }
        }
Пример #32
0
        public StripeCustomer CreateCustomer(string customerToken, string donorDescription = null)
        {
            var request = new RestRequest("customers", Method.POST);

            request.AddParameter("description", string.Format(StripeCustomerDescription, string.IsNullOrWhiteSpace(donorDescription) ? "pending" : donorDescription));
            if (!string.IsNullOrWhiteSpace(customerToken))
            {
                request.AddParameter("source", customerToken);
            }

            var response = _stripeRestClient.Execute <StripeCustomer>(request);

            CheckStripeResponse("Customer creation failed", response);

            return(response.Data);
        }
Пример #33
0
        public int GetCompanyIDFromCAN(string clientAccountNumber)
        {
            var clientDetailsServicesUrl = ConfigurationManager.AppSettings["ClientDetailsServices.Rest.BaseUrl"];
            _restClient = new RestClient(clientDetailsServicesUrl);

            var request = new RestRequest("Client?can={CAN}", Method.GET)
                              {
                                  RequestFormat = DataFormat.Xml
                              };

            request.AddUrlSegment("CAN", clientAccountNumber);

            var resp = _restClient.Execute<CompanyDetailsResponse>(request).Data;

            return resp.Id;
        }
Пример #34
0
        /// <summary>
        /// 创建标签
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="tagName"></param>
        /// <returns>Tag Id</returns>
        public int CreateTag(string accessToken, string tagName)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Access Token为空");
            }
            if (string.IsNullOrEmpty(tagName))
            {
                throw new ArgumentException("标签名为空");
            }

            IRestRequest request = new RestRequest("cgi-bin/tags/create", Method.POST);

            request.AddQueryParameter("access_token", accessToken);
            request.AddJsonBody(new Tag()
            {
                tag = new TagDetail()
                {
                    name = tagName
                }
            });

            IRestResponse response = _restClient.Execute(request);

            if (response.Content.Contains("errcode"))
            {
                var err = JsonConvert.DeserializeObject <Error>(response.Content);
                throw new WeixinInterfaceException(err.errmsg);
            }

            Tag tag = JsonConvert.DeserializeObject <Tag>(response.Content);

            return(tag.tag.id);
        }
 public static IRestResponse Head(this IRestClient client, IRestRequest request)
 {
     request.Method = Method.HEAD;
     return(client.Execute(request));
 }
Пример #36
0
 public AuthenticationKeys(IRestClient client)
 {
     ActualRestRequest = new RestRequest();
     client.Execute <ScreenboardSummaries>(Arg.Do <RestRequest>(x => ActualRestRequest = x));
 }
Пример #37
0
        public T GetUser <T>(string user) where T : new()
        {
            var request = _requestFactory("users/{user}", Method.GET);

            request.AddUrlSegment("user", user);
            var response = _restClient.Execute <T>(request);

            return(response.Data);
        }
Пример #38
0
 public static IRestResponse <T> Get <T>(this IRestClient client, IRestRequest request) where T : new()
 => client.Execute <T>(request, Method.GET);
Пример #39
0
 public static bool IsConnected(IRestClient restClient)
 {
     var request = new RestRequest("/api/rest/session/isConnected", Method.GET);
     var responseData = restClient.Execute<IsConnectedResponse>(request);
     return responseData.Data != null && responseData.Data.Success && responseData.Data.Connected;
 }
Пример #40
0
 public static IRestResponse <T> Head <T>(this IRestClient client, IRestRequest request) where T : new()
 => client.Execute <T>(request, Method.HEAD);
Пример #41
0
 public static IRestResponse Options(this IRestClient client, IRestRequest request)
 => client.Execute(request, Method.OPTIONS);
 public static IRestResponse <T> Delete <T>(this IRestClient client, IRestRequest request) where T : new()
 {
     request.Method = Method.DELETE;
     return(client.Execute <T>(request));
 }
Пример #43
0
        private String GetAuthToken(IRestClient client)
        {
            var request = new RestRequest();
            request.RequestFormat = DataFormat.Json;
            request.Resource = "/gui/token.html";

            _logger.Debug("Url: {0}", client.BuildUri(request));
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new DownloadClientAuthenticationException("Failed to authenticate");
            }

            response.ValidateResponse(client);

            var xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(response.Content);

            var authToken = xmlDoc.FirstChild.FirstChild.InnerText;

            _logger.Debug("uTorrent AuthToken={0}", authToken);

            return authToken;
        }
 public static IRestResponse <T> Patch <T>(this IRestClient client, IRestRequest request) where T : new()
 {
     request.Method = Method.PATCH;
     return(client.Execute <T>(request));
 }
Пример #45
0
 public RetCode DeleteObject(IRestClient rClient, string requestResource, string requestResourceId, out IRestResponse rResponse)
 {
     RestRequest rRequest = new RestRequest();
     rRequest.Resource = requestResource;// "task/{id}";
     rRequest.DateFormat = "yyyy-MM-ddTHH:mm:sssssZ";
     rRequest.AddUrlSegment("id", requestResourceId);
     rRequest.Method = Method.DELETE;
     rRequest.AddBody(Authorize(new RootObject()));
     rResponse = rClient.Execute(rRequest);
     if (rResponse.StatusCode == System.Net.HttpStatusCode.OK)
     {
         Callbacker.callback(eAction.State,"Delete Successful");
         return RetCode.successful;
     }
     else
     {
         Callbacker.callback(eAction.RestError, rResponse.StatusCode, rResponse.ErrorMessage, rResponse.Content);
         return RetCode.unsuccessful;
     }
 }
 public static IRestResponse <T> Options <T>(this IRestClient client, IRestRequest request) where T : new()
 {
     request.Method = Method.OPTIONS;
     return(client.Execute <T>(request));
 }
Пример #47
0
        public RetCode ReadObject(IRestClient rClient, string requestResource, string requestResourceId, out IRestResponse rResponse)
        {
            RestRequest rRequest = new RestRequest();
            rRequest.Resource = requestResource;// "task/{id}";
            rRequest.DateFormat = "yyyy-MM-ddTHH:mm:ss.sss";
            //rRequest.DateFormat = "yyyy-MM-ddTHH:mm:sssssZ";
            if (requestResource.Contains("{id}")) rRequest.AddUrlSegment("id", requestResourceId);
            rRequest.Method = Method.GET;
            rResponse = rClient.Execute(rRequest);
            if (rResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Callbacker.callback(eAction.State,"Online");
                return RetCode.successful;
            }
            else
            {
                Callbacker.callback(eAction.RestError,rResponse.StatusCode,rResponse.ErrorMessage,rResponse.Content);
                return RetCode.unsuccessful;
            }

        }
Пример #48
0
 public static IRestResponse Put(this IRestClient client, IRestRequest request) => client.Execute(request, Method.PUT);
        /// <summary>
        /// 发送一次性订阅消息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <param name="templateId"></param>
        /// <param name="scene"></param>
        /// <param name="title"></param>
        /// <param name="value"></param>
        /// <param name="color"></param>
        /// <param name="url"></param>
        /// <param name="miniProgram"></param>
        /// <returns></returns>
        public string SendDisposableMessage(string accessToken, string openId, string templateId, int scene, string title, string value, string color = null, string url = null, MiniProgram miniProgram = null)
        {
            #region 参数验证
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Access Token为空");
            }
            if (string.IsNullOrEmpty(openId))
            {
                throw new ArgumentException("接受者OpenId为空");
            }
            if (string.IsNullOrWhiteSpace(templateId))
            {
                throw new ArgumentException("模板Id为空");
            }
            if (miniProgram != null && string.IsNullOrEmpty(miniProgram.AppId))
            {
                throw new ArgumentException("小程序AppId为空");
            }
            if (miniProgram != null && string.IsNullOrEmpty(miniProgram.PagePath))
            {
                throw new ArgumentException("小程序跳转页面为空");
            }
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("Value为空");
            }
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException("Title为空");
            }
            #endregion

            IRestRequest request = new RestRequest("cgi-bin/message/template/subscribe", Method.POST);
            request.AddQueryParameter("access_token", accessToken);
            request.AddJsonBody(new
            {
                touser      = openId,
                template_id = templateId,
                url         = url,
                miniProgram = miniProgram == null ? null : miniProgram,
                scene       = scene,
                title       = title,
                data        = new
                {
                    content = new
                    {
                        value = value,
                        color = color
                    }
                }
            });

            IRestResponse response = _restClient.Execute(request);

            Error err = JsonConvert.DeserializeObject <Error>(response.Content);
            if (err.errcode != 0)
            {
                throw new WeixinInterfaceException(err.errmsg);
            }

            return(err.errmsg);
        }
Пример #50
0
 public static IRestResponse Head(this IRestClient client, IRestRequest request) => client.Execute(request, Method.HEAD);
 public static IRestResponse <T> Head <T>(this IRestClient client, IRestRequest request) where T : new()
 {
     request.Method = Method.HEAD;
     return(client.Execute <T>(request));
 }
Пример #52
0
        //General method to get country data.
        private static string GetCountryData(string data_type, string source = "jhu")
        {
            string data_list = null;
            var    data_set  = new SortedSet <string>();

            try
            {
                //Sends a GET request to the API
                var request = new RestRequest("v2/locations?source=" + source, Method.GET);

                //Fetches the response from the API
                var response = client.Execute(request);

                //Deserializes the response
                JObject output = (JObject)JsonConvert.DeserializeObject(response.Content);

                //Stores the 'locations' node
                var    locations = output["locations"];
                JArray loc_arr   = (JArray)locations;

                //Loop untill all countries and add them in HashSet to remove duplicates.
                for (int index = 0; index < loc_arr.Count; index++)
                {
                    string country_data = locations[index][data_type].ToString();
                    data_set.Add(country_data);
                }

                data_list = string.Join("\n", data_set);
            }
            catch (NullReferenceException ex)
            {
                data_list = "Data not available try changing source";
            }
            return(data_list);
        }
Пример #53
0
 public static Task <TResponse> Post <TResponse, TRequest>(this IRestClient restClient, string resource, TRequest body)
 {
     return(restClient.Execute <TResponse, TRequest>(resource, RestSharp.Method.POST, body));
 }
Пример #54
0
 private static void UploadApk(IRestClient restClient, string accessToken, string applicationId, string editId, string apkPath)
 {
     Console.WriteLine("Uploading apk");
     var request = new RestRequest("/upload/androidpublisher/v2/applications/{applicationId}/edits/{editId}/apks", Method.POST);
     request.Timeout = _10_MIN_IN_MILLIS;
     request.AddUrlSegment("applicationId", applicationId);
     request.AddUrlSegment("editId", editId);
     request.AddQueryParameter("access_token", accessToken);
     request.AddFile("file", apkPath);
     var response = restClient.Execute<EditResponse>(request);
     CheckResponse(response);
 }
Пример #55
0
 public static IRestResponse <T> Options <T>(this IRestClient client, IRestRequest request) where T : new()
 => client.Execute <T>(request, Method.OPTIONS);
 public static IRestResponse Post(this IRestClient client, IRestRequest request)
 {
     request.Method = Method.POST;
     return(client.Execute(request));
 }
Пример #57
0
        protected IRestResponse SendRequest(IRestClient client, IRestRequest request)
        {
            var response = client.Execute(request);

            log.Debug(String.Format(
                    "Executed request to {0} with method {1}, got the following status: {2} and the body is {3}",
                    response.ResponseUri, request.Method, response.StatusDescription, response.Content));

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                log.Error("Your login/password are unknown to server");
                throw new UnauthorizedException("Your login/password are unknown to server");
            }

            if (((int)response.StatusCode) == 422)
            {
                var errors = JsonConvert.DeserializeObject<ErrorsDAO>(response.Content).Errors;
                log.Error(String.Format("API returned following errors: {0}", JsonConvert.SerializeObject(errors)));
                throw new ApiErrorsException("API returned errors, see Errors property", errors);
            }
            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                var message = JsonConvert.DeserializeObject<IDictionary<string,string>>(response.Content)["message"];
                log.Error(String.Format("Bad request: {0}", message));
                throw new ApiErrorsException(message, null);
            }
            return response;
        }
Пример #58
0
 public static IRestResponse <T> Patch <T>(this IRestClient client, IRestRequest request) where T : new()
 => client.Execute <T>(request, Method.PATCH);
Пример #59
0
        protected String GetSessionId(IRestClient client, TransmissionSettings settings)
        {
            var request = new RestRequest();
            request.RequestFormat = DataFormat.Json;

            _logger.Debug("Url: {0} GetSessionId", client.BuildUri(request));
            var restResponse = client.Execute(request);

            if (restResponse.StatusCode == HttpStatusCode.MovedPermanently)
            {
                var uri = new Uri(restResponse.ResponseUri, (String)restResponse.GetHeaderValue("Location"));

                throw new DownloadClientException("Remote site redirected to " + uri);
            }

            // We expect the StatusCode = Conflict, coz that will provide us with a new session id.
            switch (restResponse.StatusCode)
            {
                case HttpStatusCode.Conflict:
                {
                    var sessionId = restResponse.Headers.SingleOrDefault(o => o.Name == "X-Transmission-Session-Id");

                    if (sessionId == null)
                    {
                        throw new DownloadClientException("Remote host did not return a Session Id.");
                    }

                    return (String)sessionId.Value;
                }
                case HttpStatusCode.Unauthorized:
                    throw new DownloadClientAuthenticationException("User authentication failed.");
            }

            restResponse.ValidateResponse(client);

            throw new DownloadClientException("Remote host did not return a Session Id.");
        }
Пример #60
0
 public static IRestResponse <T> Delete <T>(this IRestClient client, IRestRequest request) where T : new()
 => client.Execute <T>(request, Method.DELETE);