protected async virtual Task <IResponse> BuildResponse(HttpResponseMessage responseMessage)
        {
            Ensure.ArgumentIsNotNull(responseMessage, "responseMessage");

            object responseBody = null;
            string contentType  = null;

            using (var content = responseMessage.Content)
            {
                if (content != null)
                {
                    contentType = GetContentMediaType(responseMessage.Content);

                    // We added support for downloading images and zip-files. Let's constrain this appropriately.
                    if (contentType != null && (contentType.StartsWith("image/") || contentType.Equals("application/zip", StringComparison.OrdinalIgnoreCase)))
                    {
                        responseBody = await responseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        responseBody = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }

            return(new Response(
                       responseMessage.StatusCode,
                       responseBody,
                       responseMessage.Headers.ToDictionary(h => h.Key, h => h.Value.First()),
                       contentType));
        }
Exemple #2
0
        public Task <IApiResponse <T> > Patch <T>(Uri uri, object body)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(body, "body");

            return(SendData <T>(uri, HttpVerb.Patch, body, null, null, CancellationToken.None));
        }
Exemple #3
0
        /// <summary>
        /// Creates a new connection instance used to make requests of the Sulekha Property API.
        /// </summary>
        /// <param name="baseAddress">The address to point this client to, such as https://api.tookanapp.com:8888.</param>
        /// <param name="credentialStore">Provides credentials to the client when making requests</param>
        /// <param name="httpClient">A raw <see cref="IHttpClient"/> used to make requests</param>
        /// <param name="serializer">Class used to serialize and deserialize JSON requests</param>
        /// <param name="jsonPipeline">Json Pipeline used to serialize and deserialize.</param>
        public Connection(
            Uri baseAddress,
            ICredentialStore credentialStore,
            IHttpClient httpClient,
            ISerializationService serializer,
            IJsonHttpPipeline jsonPipeline)
        {
            Ensure.ArgumentIsNotNull(baseAddress, nameof(baseAddress));
            Ensure.ArgumentIsNotNull(credentialStore, nameof(credentialStore));
            Ensure.ArgumentIsNotNull(httpClient, nameof(httpClient));
            Ensure.ArgumentIsNotNull(serializer, nameof(serializer));
            Ensure.ArgumentIsNotNull(jsonPipeline, nameof(jsonPipeline));

            if (!baseAddress.IsAbsoluteUri)
            {
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture, "The base address '{0}' must be an absolute URI",
                                        baseAddress), nameof(baseAddress));
            }

            BaseAddress    = baseAddress;
            _authenticator = new Authenticator(credentialStore);
            _httpClient    = httpClient;
            _jsonPipeline  = jsonPipeline;
        }
Exemple #4
0
        public Task <IApiResponse <T> > Post <T>(Uri uri, object body, string accepts, string contentType, Uri baseAddress)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(body, "body");

            return(SendData <T>(uri, HttpMethod.Post, body, accepts, contentType, CancellationToken.None, baseAddress: baseAddress));
        }
Exemple #5
0
        /// <summary>
        /// Initializes a new API client.
        /// </summary>
        /// <param name="apiConnection">The client's connection</param>
        protected ApiClient(IApiConnection apiConnection)
        {
            Ensure.ArgumentIsNotNull(apiConnection, "apiConnection");

            ApiConnection = apiConnection;
            Connection    = apiConnection.Connection;
        }
        public static TValue SafeGet <TKey, TValue>(this IReadOnlyDictionary <TKey, TValue> dictionary, TKey key)
        {
            Ensure.ArgumentIsNotNull(dictionary, "dictionary");
            TValue value;

            return(dictionary.TryGetValue(key, out value) ? value : default(TValue));
        }
        public static Task <IApiResponse <T> > GetRedirect <T>(this IConnection connection, Uri uri)
        {
            Ensure.ArgumentIsNotNull(connection, "connection");
            Ensure.ArgumentIsNotNull(uri, "uri");

            return(connection.Get <T>(uri, null, null, false));
        }
        /// <summary>
        /// Deletes the API object at the specified URI.
        /// </summary>
        /// <param name="uri">URI of the API resource to delete</param>
        /// <param name="data">Object that describes the API resource; this will be serialized and used as the request's body</param>
        /// <returns>A <see cref="Task"/> for the request's execution.</returns>
        public Task Delete(Uri uri, object data)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(data, "data");

            return(Connection.Delete(uri, data));
        }
        /// <summary>
        /// Creates a new API resource in the list at the specified URI.
        /// </summary>
        /// <typeparam name="T">The API resource's type.</typeparam>
        /// <param name="uri">URI of the API resource to get</param>
        /// <param name="data">Object that describes the new API resource; this will be serialized and used as the request's body</param>
        /// <returns>The created API resource.</returns>
        /// <exception cref="ApiException">Thrown when an API error occurs.</exception>
        public Task <T> Post <T>(Uri uri, object data)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(data, "data");

            return(Post <T>(uri, data, null, null));
        }
Exemple #10
0
        /// <summary>
        /// Gets the API resource at the specified URI.
        /// </summary>
        /// <typeparam name="T">Type of the API resource to get.</typeparam>
        /// <param name="connection">The connection to use</param>
        /// <param name="uri">URI of the API resource to get</param>
        /// <param name="cancellationToken">A token used to cancel the GetResponse request</param>
        /// <returns>The API resource.</returns>
        /// <exception cref="ApiException">Thrown when an API error occurs.</exception>
        public static Task <IApiResponse <T> > GetResponse <T>(this IConnection connection, Uri uri, CancellationToken cancellationToken)
        {
            Ensure.ArgumentIsNotNull(connection, "connection");
            Ensure.ArgumentIsNotNull(uri, "uri");

            return(connection.Get <T>(uri, null, null, cancellationToken));
        }
Exemple #11
0
        public static ApiInfo ParseResponseHeaders(IDictionary <string, string> responseHeaders)
        {
            Ensure.ArgumentIsNotNull(responseHeaders, "responseHeaders");
            var    oauthScopes         = new List <string>();
            var    acceptedOauthScopes = new List <string>();
            string etag = null;

            if (responseHeaders.ContainsKey("X-Accepted-OAuth-Scopes"))
            {
                acceptedOauthScopes.AddRange(responseHeaders["X-Accepted-OAuth-Scopes"]
                                             .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                             .Select(x => x.Trim()));
            }

            if (responseHeaders.ContainsKey("X-OAuth-Scopes"))
            {
                oauthScopes.AddRange(responseHeaders["X-OAuth-Scopes"]
                                     .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                     .Select(x => x.Trim()));
            }

            if (responseHeaders.ContainsKey("ETag"))
            {
                etag = responseHeaders["ETag"];
            }

            return(new ApiInfo(oauthScopes, acceptedOauthScopes, etag, new RateLimit(responseHeaders)));
        }
Exemple #12
0
        public Task <IApiResponse <T> > Post <T>(Uri uri, object body, string accepts, string contentType, TimeSpan timeout)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(body, "body");

            return(SendData <T>(uri, HttpMethod.Post, body, accepts, contentType, timeout, CancellationToken.None));
        }
Exemple #13
0
        /// <summary>
        /// Gets all API resources in the list at the specified URI.
        /// </summary>
        /// <typeparam name="T">Type of the API resource in the list.</typeparam>
        /// <param name="connection">The connection to use</param>
        /// <param name="uri">URI of the API resource to get</param>
        /// <returns><see cref="IReadOnlyList{T}"/> of the The API resources in the list.</returns>
        /// <exception cref="ApiException">Thrown when an API error occurs.</exception>
        public static Task <IReadOnlyList <T> > GetAll <T>(this IApiConnection connection, Uri uri)
        {
            Ensure.ArgumentIsNotNull(connection, "connection");
            Ensure.ArgumentIsNotNull(uri, "uri");

            return(connection.GetAll <T>(uri, null));
        }
Exemple #14
0
        void GenerateReports(ReportResult reportResult, string reportTypes)
        {
            Ensure.ArgumentIsNotNull(reportResult, "reportResult");

            if (BuildEnvironment.IsTeamCityBuild)
            {
                TeamCityReportGenerator.RenderReport(reportResult, this);
            }

            if (String.IsNullOrEmpty(reportTypes))
            {
                return;
            }

            Log(Level.Info, "Generating reports");
            foreach (string reportType in reportTypes.Split(';'))
            {
                string reportFileName = null;
                Log(Level.Verbose, "Report type: {0}", reportType);
                switch (reportType.ToLower())
                {
                case "text":
                    reportFileName = TextReport.RenderToText(reportResult, ReportDirectory, ReportFileNameFormat);
                    break;

                case "xml":
                    reportFileName = XmlReport.RenderToXml(reportResult, ReportDirectory, ReportFileNameFormat);
                    break;

                case "html":
                    reportFileName = HtmlReport.RenderToHtml(reportResult, ReportDirectory, ReportFileNameFormat);
                    break;

                case "dox":
                    reportFileName = DoxReport.RenderToDox(reportResult, ReportDirectory, ReportFileNameFormat);
                    break;

                case "transform":
                    if (Transform == null)
                    {
                        throw new BuildException(String.Format("No transform specified for report type '{0}'", reportType));
                    }

                    reportFileName = HtmlReport.RenderToHtml(reportResult,
                                                             ReportDirectory,
                                                             Transform.FullName,
                                                             TransformReportFileNameFormat);
                    break;

                default:
                    Log(Level.Error, "Unknown report type {0}", reportType);
                    break;
                }

                if (reportFileName != null)
                {
                    Log(Level.Info, "Created report at {0}", reportFileName);
                }
            }
        }
        public static Task <IResponse> Send(this IHttpClient httpClient, IRequest request)
        {
            Ensure.ArgumentIsNotNull(httpClient, "httpClient");
            Ensure.ArgumentIsNotNull(request, "request");

            return(httpClient.Send(request, CancellationToken.None));
        }
        private PageProperty CreateProperty(PageNode pageNode, PagePropertyTemplate propertyTemplate, string text = null, bool commit = true)
        {
            Ensure.ArgumentIsNotNull(pageNode, "pageNode");
            Ensure.ArgumentIsNotNull(propertyTemplate, "propertyTemplate");

            var propertyDbSet = _unitOfWork.Context.GetDbSet <PageProperty>();

            var property = propertyDbSet.Create();

            property.PropertyTemplate = propertyTemplate;
            property.ParentPageNode   = pageNode;
            property.Text             = text;
            property.Order            = pageNode.Properties == null || !pageNode.Properties.Any()
                            ? CmsConstants.FirstOrderNumber
                            : pageNode.Properties.Count();

            propertyDbSet.Add(property);

            if (commit)
            {
                _unitOfWork.Commit();
            }

            return(property);
        }
        public PageProperty Create(PageNode pageNode, PagePropertyTemplate propertyTemplate, string text = null, bool commit = true)
        {
            Ensure.ArgumentIsNotNull(pageNode, "pageNode");
            Ensure.ArgumentIsNotNull(propertyTemplate, "propertyTemplate");

            return(CreateProperty(pageNode, propertyTemplate, text, commit));
        }
Exemple #18
0
        public Response(IDictionary <string, string> headers)
        {
            Ensure.ArgumentIsNotNull(headers, "headers");

            Headers = new ReadOnlyDictionary <string, string>(headers);
            ApiInfo = ApiInfoParser.ParseResponseHeaders(headers);
        }
        public NAntRunListener(Task task)
        {
            Ensure.ArgumentIsNotNull(task, "task");
            _task = task;

            UpdateNAntProperties(_task.Properties, 0, 0, 0, 0, 0, 0);
        }
Exemple #20
0
        /// <summary>
        /// Gets the API resource at the specified URI.
        /// </summary>
        /// <typeparam name="T">Type of the API resource to get.</typeparam>
        /// <param name="uri">URI of the API resource to get</param>
        /// <param name="parameters">Parameters to add to the API request</param>
        /// <returns>The API resource.</returns>
        /// <exception cref="ApiException">Thrown when an API error occurs.</exception>
        public async Task <T> Get <T>(Uri uri, IDictionary <string, string> parameters)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");

            var response = await Connection.Get <T>(uri, parameters, null).ConfigureAwait(false);

            return(response.Body);
        }
Exemple #21
0
        public async Task Apply(IRequest request)
        {
            Ensure.ArgumentIsNotNull(request, "request");

            var credentials = await CredentialStore.GetCredentials().ConfigureAwait(false) ?? Credentials.Anonymous;

            authenticators[credentials.AuthenticationType].Authenticate(request, credentials);
        }
Exemple #22
0
        public ApiResponse(IResponse response, T bodyAsObject, ResponseInfo responseInfo = null)
        {
            Ensure.ArgumentIsNotNull(response, "response");

            HttpResponse = response;
            Body         = bodyAsObject;
            ResponseInfo = responseInfo;
        }
        public TeamCityMessageProvider(TeamCityLogWriter writer, Task taskToUseForLogging)
        {
            Ensure.ArgumentIsNotNull(writer, "writer");
            Ensure.ArgumentIsNotNull(taskToUseForLogging, "taskToUseForLogging");

            _writer = writer;
            _writer.TaskToUseForLogging = taskToUseForLogging;
        }
Exemple #24
0
        /// <summary>
        /// Performs an asynchronous HTTP POST request.
        /// </summary>
        /// <param name="uri">URI endpoint to send request to</param>
        /// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
        public async Task <HttpStatusCode> Post(Uri uri)
        {
            Ensure.ArgumentIsNotNull(uri, nameof(uri));

            var response = await SendData <object>(uri, HttpMethod.Post, null, null, null, CancellationToken.None);

            return(response.HttpResponse.StatusCode);
        }
Exemple #25
0
        public RateLimit(IDictionary <string, string> responseHeaders)
        {
            Ensure.ArgumentIsNotNull(responseHeaders, "responseHeaders");

            Limit     = (int)GetHeaderValueAsInt32Safe(responseHeaders, "X-RateLimit-Limit");
            Remaining = (int)GetHeaderValueAsInt32Safe(responseHeaders, "X-RateLimit-Remaining");
            Reset     = GetHeaderValueAsInt32Safe(responseHeaders, "X-RateLimit-Reset").FromUnixTime();
        }
Exemple #26
0
        /// <summary>
        /// Performs an asynchronous HTTP POST request.
        /// Attempts to map the response body to an object of type <typeparamref name="T"/>
        /// </summary>
        /// <typeparam name="T">The type to map the response to</typeparam>
        /// <param name="uri">URI endpoint to send request to</param>
        /// <param name="body">The object to serialize as the body of the request</param>
        /// <param name="accepts">Specifies accepted response media types.</param>
        /// <param name="contentType">Specifies the media type of the request body</param>
        /// <param name="twoFactorAuthenticationCode">Two Factor Authentication Code</param>
        /// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
        public Task <IApiResponse <T> > Post <T>(Uri uri, object body, string accepts, string contentType, string twoFactorAuthenticationCode)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(body, "body");
            Ensure.ArgumentIsNotNullOrEmptyString(twoFactorAuthenticationCode, "twoFactorAuthenticationCode");

            return(SendData <T>(uri, HttpMethod.Post, body, accepts, contentType, CancellationToken.None, twoFactorAuthenticationCode));
        }
Exemple #27
0
        /// <summary>
        /// Creates or replaces the API resource at the specified URI.
        /// </summary>
        /// <typeparam name="T">The API resource's type.</typeparam>
        /// <param name="uri">URI of the API resource to create or replace</param>
        /// <param name="data">Object that describes the API resource; this will be serialized and used as the request's body</param>
        /// <param name="twoFactorAuthenticationCode">The two-factor authentication code in response to the current user's previous challenge</param>
        /// <param name="accepts">Accept header to use for the API request</param>
        /// <returns>The created API resource.</returns>
        /// <exception cref="ApiException">Thrown when an API error occurs.</exception>
        public async Task <T> Put <T>(Uri uri, object data, string twoFactorAuthenticationCode, string accepts)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(data, "data");

            var response = await Connection.Put <T>(uri, data, twoFactorAuthenticationCode, accepts).ConfigureAwait(false);

            return(response.Body);
        }
Exemple #28
0
        /// <summary>
        /// Updates the API resource at the specified URI.
        /// </summary>
        /// <typeparam name="T">The API resource's type.</typeparam>
        /// <param name="uri">URI of the API resource to update</param>
        /// /// <param name="data">Object that describes the API resource; this will be serialized and used as the request's body</param>
        /// <returns>The updated API resource.</returns>
        /// <exception cref="ApiException">Thrown when an API error occurs.</exception>
        public async Task <T> Patch <T>(Uri uri, object data)
        {
            Ensure.ArgumentIsNotNull(uri, "uri");
            Ensure.ArgumentIsNotNull(data, "data");

            var response = await Connection.Patch <T>(uri, data).ConfigureAwait(false);

            return(response.Body);
        }
Exemple #29
0
        public T GetModel <T>(HttpContextBase httpContextBase) where T : class, new()
        {
            var currentRouteData = httpContextBase.Request.RequestContext.RouteData;

            Ensure.ArgumentIsNotNull(currentRouteData, "currentRouteData");

            var routeDataValues = currentRouteData.Values.ToList();

            var cmsRouteDataValues = GetCmsRouteDataValues(routeDataValues);

            var controllerName = cmsRouteDataValues[0].Value.ToString();

            var sectionNode = _sectionNodeService.GetByUrlName(controllerName);

            if (sectionNode == null)
            {
                throw new ArgumentException(string.Format(Messages.SectionNodeNotFoundForUrlName, controllerName));
            }

            PageNode pageNode = null;

            for (var i = 0; i < cmsRouteDataValues.Count; i++)
            {
                if (i == 0)
                {
                    continue;          //skip the controller route data value
                }
                pageNode = i == 1
                            ? NodeHelper.GetActionPageNode(sectionNode.PageNodes, cmsRouteDataValues[i].Value.ToString())
                            : NodeHelper.GetActionPageNode(pageNode.PageNodes, cmsRouteDataValues[i].Value.ToString());

                if (pageNode == null)
                {
                    throw new ArgumentException(string.Format("The page with the url name : {0} was not found.", cmsRouteDataValues[i].Value));
                }
            }

            var modelName = pageNode.PageTemplate.ModelName;

            var modelType     = Assembly.GetCallingAssembly().GetModels().FirstOrDefault(x => x.Name == modelName);
            var modelInstance = (T)Activator.CreateInstance(modelType);

            var props           = modelType.GetMembers();
            var modelProperties = props.Where(x => x.GetCustomAttributes(typeof(CmsModelPropertyAttribute), false).Length > 0).OfType <PropertyInfo>().ToList();

            foreach (var property in pageNode.Properties)
            {
                var modelProperty = modelProperties.FirstOrDefault(x => x.Name == property.PropertyTemplate.PropertyName);
                if (modelProperty != null)
                {
                    modelProperty.SetValue(modelInstance, property.Text, BindingFlags.Public, null, null, null);
                }
            }

            return(modelInstance);
        }
Exemple #30
0
        internal static void FormatValue(StringBuilder builder)
        {
            Ensure.ArgumentIsNotNull(builder, "builder");

            builder.Replace("|", "||");
            builder.Replace("'", "|'");
            builder.Replace("\n", "|n");
            builder.Replace("\r", "|r");
            builder.Replace("]", "|]");
        }