Beispiel #1
0
        public async Task <ProjectSettingsResult> UpsertProjectColors([FromBody] ProjectSettingsRequest request)
        {
            if (string.IsNullOrEmpty(request?.projectUid))
            {
                ServiceExceptionHandler.ThrowServiceException(HttpStatusCode.BadRequest, 68);
            }
            LogCustomerDetails("UpsertProjectSettings", request?.projectUid);
            Logger.LogDebug($"UpsertProjectSettings: {JsonConvert.SerializeObject(request)}");

            request.ProjectSettingsType = ProjectSettingsType.Colors;

            var projectSettingsRequest = _requestFactory.Create <ProjectSettingsRequestHelper>(r => r
                                                                                               .CustomerUid(CustomerUid))
                                         .CreateProjectSettingsRequest(request.projectUid, request.Settings, request.ProjectSettingsType);

            projectSettingsRequest.Validate();

            var result = (await WithServiceExceptionTryExecuteAsync(() =>
                                                                    RequestExecutorContainerFactory
                                                                    .Build <UpsertProjectSettingsExecutor>(LoggerFactory, ConfigStore, ServiceExceptionHandler,
                                                                                                           CustomerUid, UserId, headers: customHeaders,
                                                                                                           productivity3dV2ProxyCompaction: Productivity3dV2ProxyCompaction,
                                                                                                           projectRepo: ProjectRepo, cwsProjectClient: CwsProjectClient)
                                                                    .ProcessAsync(projectSettingsRequest)
                                                                    )) as ProjectSettingsResult;

            await NotifyChanges(UserId, request.projectUid);

            Logger.LogResult(this.ToString(), JsonConvert.SerializeObject(request), result);
            return(result);
        }
Beispiel #2
0
        public async Task <Node> Node()
        {
            var requestFactory = _requestFactory.Create("/");
            var response       = await requestFactory.Get <Node>().ConfigureAwait(false);

            return(response);
        }
        public void WhenUrlIsNull_ThrowsException()
        {
            // Arrange

            // Act
            Action act = () => _sut.Create(null, 0, new Dictionary <string, string>());

            // Assert
            act.Should().Throw <ArgumentException>();
        }
Beispiel #4
0
        public async Task <IApi> Create(ApiData data)
        {
            var response = await _requestFactory.Post <Api>(data).ConfigureAwait(false);

            var requestFactory = _requestFactory.Create("/{id}", new Dictionary <string, string> {
                { "id", response.Id }
            });

            response.Configure(requestFactory);
            return(response);
        }
Beispiel #5
0
        public async Task <IPlugin> Create(PluginData data)
        {
            var response = await _requestFactory.Post <Plugin>(data).ConfigureAwait(false);

            var requestFactory = _requestFactory.Create("/{plugin_id}", new Dictionary <string, string> {
                { "plugin_id", response.Id }
            });

            response.Configure(requestFactory);
            return(response);
        }
        private async Task <BitfinexApiResult <T> > ExecutePublicRequest <T>(Uri uri, string httpMethod)
        {
            var uriString = uri.ToString();
            var request   = RequestFactory.Create(uriString);

            request.ContentType = "application/json";
            request.Accept      = "application/json";
            request.Method      = httpMethod;

            return(await GetResponse <T>(request));
        }
Beispiel #7
0
        /// <summary>
        /// Sets activated state for imported files.
        /// </summary>
        protected async Task <IEnumerable <Guid> > SetFileActivatedState(string projectUid, Dictionary <Guid, bool> fileUids)
        {
            Logger.LogDebug($"SetFileActivatedState: projectUid={projectUid}, {fileUids.Keys.Count} files with changed state");

            var deactivatedFileList = await ImportedFileRequestDatabaseHelper.GetImportedFileProjectSettings(projectUid, UserId, ProjectRepo).ConfigureAwait(false) ?? new List <ActivatedFileDescriptor>();

            Logger.LogDebug($"SetFileActivatedState: originally {deactivatedFileList.Count} deactivated files");

            var missingUids = new List <Guid>();

            foreach (var key in fileUids.Keys)
            {
                //fileUids contains only uids of files whose state has changed.
                //In the project settings we store only deactivated files.
                //Therefore if the value is true remove from the list else add to the list
                if (fileUids[key])
                {
                    var item = deactivatedFileList.SingleOrDefault(d => d.ImportedFileUid == key.ToString());
                    if (item != null)
                    {
                        deactivatedFileList.Remove(item);
                    }
                    else
                    {
                        missingUids.Add(key);
                        Logger.LogInformation($"SetFileActivatedState: ImportFile '{key}' not found in project settings.");
                    }
                }
                else
                {
                    deactivatedFileList.Add(new ActivatedFileDescriptor {
                        ImportedFileUid = key.ToString(), IsActivated = false
                    });
                }
            }

            Logger.LogDebug($"SetFileActivatedState: now {deactivatedFileList.Count} deactivated files, {missingUids.Count} missingUids");

            var projectSettingsRequest =
                _requestFactory.Create <ProjectSettingsRequestHelper>(r => r
                                                                      .CustomerUid(CustomerUid))
                .CreateProjectSettingsRequest(projectUid, JsonConvert.SerializeObject(deactivatedFileList), ProjectSettingsType.ImportedFiles);

            projectSettingsRequest.Validate();

            _ = await WithServiceExceptionTryExecuteAsync(() =>
                                                          RequestExecutorContainerFactory
                                                          .Build <UpsertProjectSettingsExecutor>(LoggerFactory, ConfigStore, ServiceExceptionHandler,
                                                                                                 CustomerUid, UserId, headers : customHeaders,
                                                                                                 productivity3dV2ProxyCompaction : Productivity3dV2ProxyCompaction,
                                                                                                 projectRepo : ProjectRepo, cwsProjectClient : CwsProjectClient)
                                                          .ProcessAsync(projectSettingsRequest)
                                                          ) as ProjectSettingsResult;

            var changedUids = fileUids.Keys.Except(missingUids);

            Logger.LogDebug($"SetFileActivatedState: {changedUids.Count()} changedUids");

            return(changedUids);
        }
Beispiel #8
0
        private void AcceptNewMessage()
        {
            string message  = Console.ReadLine();
            var    strategy = _requestFactory.Create(_client, message);

            _ = Task.Run(async() => await HandleMessage(strategy, message));
            AcceptNewMessage();
        }
Beispiel #9
0
        public Task Delete(ClusterNode node)
        {
            var requestFactory = _requestFactory.Create(new Dictionary <string, string> {
                { "name", node.Name }
            });

            return(requestFactory.Delete());
        }
        public bool Sync()
        {
            if (string.IsNullOrWhiteSpace(_panelUrl) || string.IsNullOrWhiteSpace(_secret))
            {
                throw new ArgumentNullException();
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var syncUrl   = _urlProvider.GetUrl(Verb.Sync);
            var challenge = _requestFactory.Create(_urlProvider.GetUrl(Verb.Challenge), 360000, null).Execute();
            var signature = _signatureService.CreateSignature(challenge, syncUrl, null);

            return(_requestFactory
                   .Create(syncUrl, 10800000,
                           new Dictionary <string, string>
            {
                { "X-MC-MAC", signature.SignatureHash }, { "X-MC-Nonce", challenge }
            })
                   .Execute(_streamProcessor) &&
                   !_log.HasLoggedErrors);
        }
        /// <summary>
        /// Creates a new instance of the specified TRequest request, configures and invokes it and returns its response.
        /// </summary>
        /// <typeparam name="TRequest">The request interface to invoke.</typeparam>
        /// <typeparam name="TResponse">The type of the request response result.</typeparam>
        /// <param name="configure">Action that configures a type instance that implements TRequest.</param>
        /// <param name="token">Cancellation token.</param>
        /// <returns>Returns the result of the request invocation.</returns>
        private async Task <TResponse> InvokeRequestAsync <TRequest, TResponse>(Action <TRequest> configure,
                                                                                CancellationToken token)
            where TRequest : IRequest <TResponse>
        {
            EnsureIsConnected();

            var request = requestFactory.Create <TRequest>(ServerInfo);

            configure(request);

            var result = await request.InvokeAsync(httpClient, token);

            return(result);
        }
        public void Execute(int groupId, string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name), "name cannot be null when added to database");
            }

            var group = _uow.RequestGroups.Include(c => c.Requests).Single(c => c.Id == groupId);

            var domainObject = _factory.Create(groupId, name);

            group.Requests.Add(_dataFactory.Create(domainObject));

            _uow.RequestGroups.Update(group);
            _uow.SaveChanges();
        }
Beispiel #13
0
        public async Task <bool> SendValidCodeByEmail(string emailAddresss, string body, string subject)
        {
            m_paramsDict.Add("emailBody", body);
            m_paramsDict.Add("toAddress", emailAddresss);
            m_paramsDict.Add("subject", subject);
            m_paramsDict.Add("timestamp", DateTimeHelper.DateTimeToUnixTimestamp(DateTime.Now).ToString());

            var request = m_requestFactory.Create("/api/DirectEmail/SingleSendMailByBody", Method.Get, false);

            foreach (var item in m_paramsDict)
            {
                request.AddParameter("mailParams." + item.Key.ToLower(), item.Value);
            }

            request.AddParameter("mailParams." + "sign", JeuciAccessTokenHelper.GetSignStr(m_paramsDict));

            var result = await request.Execute <DirectEmailMessage>();

            return(result.StatusCode == HttpStatusCode.OK && result.Data.Code == ResultCode.Success);
        }
Beispiel #14
0
 public Task Delete(string id)
 {
     return(_requestFactory.Create("/{credential_id}", new Dictionary <string, string> {
         { "credential_id", id }
     }).Delete());
 }
        internal static WebRequest CreateRequest(RequestInfoBase info, IRequestFactory requestFactory)
        {
            WebRequest Request = requestFactory.Create(info.Uri.AbsoluteUri);

            Request.Method = info.Method.ToString();
            if ((info.Method == RequestMethod.POST || info.Method == RequestMethod.PUT))
            {
                Request.ContentType = info.RequestContentType.ToHeaderValue();
            }



            if (Request is HttpWebRequest)
            {
                var request = ((HttpWebRequest)Request);

                switch (info.ResponseContentType)
                {
                    case ContentType.JSON:
                        request.Accept = "text/plain, text/json, application/json";
                        break;
                    case ContentType.FORM:
                        request.Accept = "text/plain, text/json, application/json, text/xml, application/xml";
                        break;
                    case ContentType.XML:
                        request.Accept = "text/xml, application/xml";
                        break;
                    case ContentType.TEXT:
                        request.Accept = "text/plain";
                        break;
                }

                request.UserAgent = info.UserAgent;
                var headers = info.Headers;
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        request.Headers[header.Key] = header.Value.ToString();

                    }
                }
            }


            if ((info.Method == RequestMethod.POST || info.Method == RequestMethod.PUT))
            {
                if (string.IsNullOrEmpty(info.RequestBody))
                {
#if !WINDOWS_PHONE
                    Request.ContentLength = 0;
#endif
                }
                else
                {
                    // set request stream
                    var gate = new AutoResetEvent(false);
                    byte[] bodyValue = Encoding.UTF8.GetBytes(info.RequestBody);
                    Exception exception = null;
                    Request.BeginGetRequestStream(ac =>
                    {
                        try
                        {
                            using (
                                Stream requestStream =
                                    Request.EndGetRequestStream(ac))
                            {
                                requestStream.Write(bodyValue, 0, bodyValue.Length);
                                requestStream.Flush();
                            }
                        }
                        catch (Exception ex)
                        {
                            exception = ex;
                        }
                        finally
                        {
                            gate.Set();
                        }
                    }, null);

                    gate.WaitOne();
                    // #FIXME: logic to catch stalls conflicts with throttle
                    //if (!gate.WaitOne(10000))
                    //{
                    //    throw new Exception("timed out setting request body");
                    //}
                    if (exception != null)
                    {
                        throw exception;
                    }
                }

            }
            return Request;
        }
        /// <summary>
        /// Execute request
        /// </summary>
        /// <param name="request">The request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>The response</returns>
        public async Task <ApiResponse <TResponse> > Execute(ApiRequest <TRequest> request, CancellationToken cancellationToken)
        {
            Argument.NotNull(request, nameof(request));

            var client = _clientFactory.Create(request);

            var apiRequest = _requestFactory.Create(request);

            ApiDownloadFileResponse downloadFile = null;

            if (request.IsFileDownload == true)
            {
                client.ConfigureWebRequest(x => x.AllowReadStreamBuffering = false);

                downloadFile = new ApiDownloadFileResponse();

                apiRequest.AdvancedResponseWriter = (stream, httpResponse) => SetDownloadFile(downloadFile, stream, httpResponse);
            }

            _ = apiRequest.AddHeader(HttpRequestHeaderConstants.CacheControl, "no-cache");

            if (request.IsFileUpload == true)
            {
                client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = false);

                _ = apiRequest.AddFile(
                    request.UploadFile.ParameterName,
                    request.UploadFile.File.CopyTo,
                    request.UploadFile.FileName,
                    request.UploadFile.Size.Value,
                    request.UploadFile.ContentType);
            }
            else
            {
                client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = true);

                AddBody(request, apiRequest);
            }

            var apiResponse = await client
                              .ExecuteAsync <TResponse>(apiRequest, cancellationToken)
                              .ConfigureAwait(Await.Default);

            var response = new RestSharpApiResponse <TResponse>
            {
                RestRequest  = apiRequest,
                RestResponse = apiResponse,

                IsSuccessful   = apiResponse.IsSuccessful,
                ErrorException = apiResponse.ErrorException,
                StatusCode     = apiResponse.StatusCode,
                ResponseStatus = _converter.Convert(apiResponse.ResponseStatus)
                                 .ThrowIfNoValue()
                                 .Value,

                Content      = apiResponse.Content,
                DownloadFile = downloadFile,
            };

            if (apiResponse.IsSuccessful == true)
            {
                response.Model        = apiResponse.Data;
                response.ContentModel = apiResponse.Data;
            }

            if (apiResponse.Headers != null)
            {
                var headers = apiResponse.Headers
                              .Where(x => x.Type == ParameterType.HttpHeader)
                              .Where(x => x.Value is string)
                              .Select(x => new ResponseHeader
                {
                    Name  = x.Name,
                    Value = x.Value as string
                })
                              .ToList();

                response.Headers = new ResponseHeaders(headers)
                {
                    ContentLength = apiResponse.ContentLength,

                    ContentType = apiResponse.ContentType
                };

                SetContentDispositionHeader(response, apiResponse);
            }

            return(response);
        }
Beispiel #17
0
 public ICloudFilesResponse Submit(IAddToWebRequest requesttype, string authtoken)
 {
     return(commonSubmit(requesttype, () => _requestfactory.Create(requesttype.CreateUri()), authtoken));
 }
Beispiel #18
0
        protected IRestResponse PutBase(string body, object parameters)
        {
            var request = _requestFactory.Create(parameters, body);

            return(_clientFactory.Create().Execute(request, Method.PUT));
        }