Exemple #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestApiAsyncClient" /> class.
 /// </summary>
 /// <param name="endpoint">The endpoint.</param>
 /// <param name="acceptGZip">if set to <c>true</c> [accept g zip].</param>
 /// <param name="timeout">The timeout.</param>
 public RestApiAsyncClient(ApiEndpoint endpoint, bool acceptGZip = false, int?timeout = null) : base(endpoint, acceptGZip, timeout)
 {
     _client = new HttpClient()
     {
         Timeout = new TimeSpan(0, 0, timeout ?? 30)
     };
 }
Exemple #2
0
        internal Uri ToAbsoluteURI(string relativePath, IEnumerable <RequestParam> requestParameters)
        {
            if (ApiEndpoint.HasPath())
            {
                throw new InvalidOperationException("apiEndpoint should not contain a path");
            }
            if (ApiEndpoint.HasUserInfoOrQueryOrFragment())
            {
                throw new InvalidOperationException("apiEndpoint should not contain user info, query or fragment");
            }

            string absolutePath = relativePath.StartsWith("/", StringComparison.Ordinal)
                ? relativePath
                : "/" + relativePath;

            UriBuilder uriBuilder = new UriBuilder
            {
                Scheme = ApiEndpoint.Scheme,
                Host   = ApiEndpoint.Host,
                Port   = ApiEndpoint.Port,
                Path   = absolutePath,
            };

            if (requestParameters != null)
            {
                foreach (RequestParam nvp in requestParameters)
                {
                    uriBuilder.AddParameter(nvp.Name, nvp.Value);
                }
            }

            return(uriBuilder.Uri);
        }
Exemple #3
0
        private string ConstructNewRequestObject(Indent indent, ApiEndpoint apiEndpoint, string endpointPath)
        {
            var builder = new StringBuilder();

            builder.AppendLine();
            indent.Increment();

            builder.AppendLine($"{indent}new {apiEndpoint.ToCSharpRequestBodyClassName(endpointPath)!}");
            builder.AppendLine($"{indent}{{ ");
            indent.Increment();

            var typeNameForDto = apiEndpoint.ToCSharpRequestBodyClassName(endpointPath);

            foreach (var field in apiEndpoint.RequestBody !.Fields)
            {
                if (field.Type.IsCSharpReferenceType())
                {
                    builder.AppendLine($"{indent}{field.ToCSharpPropertyName(typeNameForDto)} = {field.ToCSharpVariableInstanceOrDefaultValue(_codeGenerationContext)},");
                }
                else
                {
                    builder.AppendLine($"{indent}{field.ToCSharpPropertyName(typeNameForDto)} = {field.ToCSharpVariableName()},");
                }
            }

            indent.Decrement();
            builder.Append($"{indent}}}");

            indent.Decrement();
            return(builder.ToString());
        }
        private ApiEndpoint GetEndpoint(ConnectorRequest request)
        {
            // Resolve the endpoint entity
            EndpointAddressResult address;

            try
            {
                address = _endpointResolver.ResolveEndpoint(request.ApiPath, false);
            }
            catch (EndpointNotFoundException)
            {
                return(null);    // can't find it, so return null
            }

            // Check the API
            Api apiEntity = _entityRepository.Get <Api>(address.ApiId);

            if (apiEntity == null)
            {
                return(null);
            }

            // Get the endpoint
            ApiEndpoint endpointEntity = _entityRepository.Get <ApiEndpoint>(address.EndpointId);

            return(endpointEntity);
        }
Exemple #5
0
 public TagService(IHttpClientFactory httpClientFactory, ApiEndpoint apiEndpoint)
 {
     _httpClient = httpClientFactory.CreateClient();
     tagsUrl     = apiEndpoint.TagsEndpointUrl;
     _httpClient.DefaultRequestHeaders.Authorization =
         new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, jwtToken);
 }
Exemple #6
0
        private void ServieHookappTimer(Object o)
        {
            var serverStats = ApiEndpoint.GetServerStats();

            _serviceHookappStats.Add(serverStats);
            File.WriteAllText(Const.SERVICE_HOOKAPP_HISTORY, JsonConvert.SerializeObject(_serviceHookappStats, Formatting.Indented));
        }
Exemple #7
0
        private async Task <bool> ExecuteAsync()
        {
            string joinCharacter = ApiEndpoint.Contains("?") ? "&" : "?";
            string apiUrl        = ApiEndpoint + joinCharacter + "access_token=" + Uri.EscapeDataString(AccessToken);

            Log.LogMessage(MessageImportance.Low, "Posting job to {0}", ApiEndpoint);
            Log.LogMessage(MessageImportance.Low, "Event json is ", EventDataPath);

            using (HttpClient client = new HttpClient())
            {
                int retryCount = 15;
                while (true)
                {
                    HttpResponseMessage response;

                    using (Stream stream = File.OpenRead(EventDataPath))
                    {
                        HttpContent contentStream = new StreamContent(stream);
                        contentStream.Headers.Add("Content-Type", "application/json");
                        response = await client.PostAsync(apiUrl, contentStream);
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        JObject responseObject;
                        using (Stream stream = await response.Content.ReadAsStreamAsync())
                            using (StreamReader streamReader = new StreamReader(stream))
                                using (JsonReader jsonReader = new JsonTextReader(streamReader))
                                {
                                    responseObject = JObject.Load(jsonReader);
                                }

                        JobId = (string)responseObject["Name"];
                        if (String.IsNullOrEmpty(JobId))
                        {
                            Log.LogError("Publish to '{0}' did not return a job ID", ApiEndpoint);
                            return(false);
                        }

                        Log.LogMessage(MessageImportance.High, "Started Helix job: CorrelationId = {0}", JobId);
                        return(true);
                    }

                    if (retryCount-- <= 0)
                    {
                        Log.LogError(
                            "Unable to publish to '{0}' after 15 retries. Received status code: {1} {2}",
                            ApiEndpoint,
                            response.StatusCode,
                            response.ReasonPhrase);
                        return(false);
                    }

                    Log.LogWarning("Failed to publish to '{0}', {1} retries remaining", ApiEndpoint, retryCount);
                }
            }
        }
        public static string GenerateId(ApiEndpoint endpoint, string input)
        {
            string id = "";

            if (endpoint.EndpointName.ToLower() == "apod")
            {
            }

            return(id);
        }
Exemple #9
0
        public ApiEndpoint SaveEndPoint(ApiEndpoint apiEndpoint)
        {
            ApiEndpoint retVal = null;

            if (apiEndpoint != null)
            {
                retVal = _model.ApiEndpoints.Add(apiEndpoint);
                _model.SaveChanges();
            }
            return(retVal);
        }
Exemple #10
0
        public async Task <T> ExecuteDataAsync <T>(ApiEndpoint <T> endpoint)
        {
            var response = await ExecuteAsync(endpoint);

            if (response.Successful)
            {
                return(await response.GetDataAsync());
            }

            throw new InvalidOperationException("Operation was not successfull");
        }
        public static string?ToCSharpRequestBodyClassName(this ApiEndpoint subject, string endpointPath)
        {
            if (subject.RequestBody == null ||
                subject.RequestBody.Kind != ApiFieldType.Object.ObjectKind.REQUEST_BODY)
            {
                return(null);
            }

            return(CSharpIdentifier.ForClassOrNamespace(endpointPath)
                   + subject.Method.ToHttpMethod().ToLowerInvariant().ToUppercaseFirst()
                   + "Request");
        }
        /// <summary>
        /// To the aws credentials.
        /// </summary>
        /// <param name="apiEndpoint">The API endpoint.</param>
        /// <returns>AWSCredentials.</returns>
        protected static AWSCredentials ToAWSCredentials(ApiEndpoint apiEndpoint)
        {
            if (apiEndpoint != null)
            {
                var accessKey       = apiEndpoint.Token;
                var accessSecretKey = apiEndpoint.SecondaryToken;

                return(new Amazon.Runtime.BasicAWSCredentials(accessKey, accessSecretKey));
            }

            return(null);
        }
Exemple #13
0
        public Task <ApiResponse <T> > ExecuteAsync <T>(ApiEndpoint <T> endpoint)
        {
            return(InternalExecuteAsync(endpoint, (ex) => new ApiResponse <T>(ex), async(response) =>
            {
                var result = new ApiResponse <T>(response);
                if (result.Successful)
                {
                    await result.GetDataAsync();
                }

                return result;
            }));
        }
Exemple #14
0
        private static HttpResponseMessage HttpGet(ApiEndpoint apiEndpoint, string encodedQuery)
        {
            var        url    = string.Concat(apiEndpoint.Endpoint, encodedQuery);
            HttpClient client = new HttpClient {
                BaseAddress = new Uri(url)
            };

            client.DefaultRequestHeaders.Add(X_QUERYKEY_HEADER, apiEndpoint.ApiKey);
            client.DefaultRequestHeaders.Add(CommonStrings.Accept, StandardHttpContentTypes.ApplicationJson);
            HttpResponseMessage response = client.GetAsync(url).Result;

            return(response);
        }
        /// <summary>
        /// Gets the request URI.
        /// </summary>
        /// <param name="apiEndpoint">The API endpoint.</param>
        /// <param name="realm">The realm.</param>
        /// <param name="version">The version.</param>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="resourceAction">The resource action.</param>
        /// <param name="key">The key.</param>
        /// <param name="queryString">The query string.</param>
        /// <returns></returns>
        protected internal virtual string GetRequestUri(ApiEndpoint apiEndpoint, string realm, string version, string resourceName, string resourceAction, string key, Dictionary <string, string> queryString = null)
        {
            var url = string.Format("{0}{1}/{2}", GetRequestEndpoint(Endpoint, realm, version), resourceName, resourceAction).TrimEnd('/') + "/";

            if (!string.IsNullOrWhiteSpace(key))
            {
                url += (key.ToUrlEncodedText() + "/");
            }
            if (queryString.HasItem())
            {
                url += ("?" + queryString.ToKeyValuePairString(encodeKeyValue: true));
            }

            return(url);
        }
        private static void AddObsoletes(string jsonFile, ApiEndpoint endpoint)
        {
            var directory    = Path.GetDirectoryName(jsonFile);
            var obsoleteFile = Path.Combine(directory, Path.GetFileNameWithoutExtension(jsonFile)) + ".obsolete.json";

            if (!File.Exists(obsoleteFile))
            {
                return;
            }

            var json             = File.ReadAllText(obsoleteFile);
            var endpointOverride = JsonConvert.DeserializeObject <Dictionary <string, ApiEndpoint> >(json).First();

            endpoint.ObsoleteQueryParameters = endpointOverride.Value?.Url?.Params ?? new Dictionary <string, ApiQueryParameters>();
            endpoint.RemovedMethods          = endpointOverride.Value?.RemovedMethods ?? new Dictionary <string, string>();
        }
Exemple #17
0
        private string GenerateMethodsForApiEndpoint(ApiEndpoint apiEndpoint, string baseEndpointPath)
        {
            var builder = new StringBuilder();

            builder.AppendLine(GenerateMethodForApiEndpoint(apiEndpoint, baseEndpointPath));

            var isResponseBatch = apiEndpoint.ResponseBody is ApiFieldType.Object objectResponse &&
                                  objectResponse.Kind == ApiFieldType.Object.ObjectKind.BATCH;

            if (isResponseBatch && apiEndpoint.ResponseBody != null)
            {
                builder.AppendLine();
                builder.AppendLine(GenerateEnumerableMethodForBatchApiEndpoint(apiEndpoint, baseEndpointPath));
            }

            return(builder.ToString());
        }
Exemple #18
0
        private static void LoadOverridesOnEndpoint(ApiEndpoint endpoint)
        {
            var method = endpoint.CsharpNames.MethodName;

            if (CodeConfiguration.ApiNameMapping.TryGetValue(endpoint.Name, out var mapsApiMethodName))
            {
                method = mapsApiMethodName;
            }

            var namespacePrefix = typeof(GlobalOverrides).Namespace + ".Endpoints.";
            var typeName        = namespacePrefix + method + "Overrides";
            var type            = GeneratorLocations.Assembly.GetType(typeName);

            if (type != null && Activator.CreateInstance(type) is IEndpointOverrides overrides)
            {
                endpoint.Overrides = overrides;
            }
        }
Exemple #19
0
        public void apiEndpoint_should_save_to_database()
        {
            ApiEndpoint apiEndpoint = new ApiEndpoint()
            {
                AccountId   = 1,
                ApiKey      = "Duiwoelskj3342ksd",
                ApiKeyType  = 2,
                Curl        = "testing",
                Endpoint    = "https://www.google.com",
                NRSQLSyntax = "Select * from Transaction",
                Title       = "Test Api Endpoint"
            };

            var result = _apiEndPointRepository.SaveEndPoint(apiEndpoint);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Id > 0);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RestApiClientBase" /> class.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="acceptGZip">if set to <c>true</c> [accept g zip].</param>
        /// <param name="timeout">The timeout.</param>
        public RestApiClientBase(ApiEndpoint endpoint, bool acceptGZip = false, int?timeout = null)
        {
            //Try detecting base client version and generated version.
            if (ClientGeneratedVersion != BaseClientVersion)
            {
                throw new NotSupportedException(string.Format("ClientGeneratedVersion [{0}] doesnot match BaseClientVersion [{1}].", ClientGeneratedVersion, BaseClientVersion));
            }

            Endpoint   = endpoint ?? new ApiEndpoint();
            AcceptGZip = acceptGZip;
            Timeout    = timeout;

            var actualType = GetType();

            var version = (actualType.Assembly.GetCustomAttribute <BeyovaComponentAttribute>()?.UnderlyingObject?.Version).SafeToString(actualType.Assembly.GetName().Version.ToString());

            UserAgent = string.Format("{0}/{1} BeyovaCommon/{2} .NET/{3}", actualType.Name, version, EnvironmentCore.CommonComponentInfo?.Version, Environment.Version.ToString());
        }
Exemple #21
0
 public PaymentsService(string apiLogin, string apiKey, string merchantID, string language, bool testMode)
 {
     _apiLogin   = apiLogin ?? throw new ArgumentNullException(nameof(apiLogin));
     _apiKey     = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
     _language   = language;
     _testMode   = testMode;
     _endpoint   = ApiEndpoint.Payments(testMode);
     _merchantID = merchantID;
     _headers    = new
     {
         Accept       = "application/json",
         Content_Type = "application/json"
     };
     _merchant = new Merchant
     {
         ApiKey   = _apiKey,
         ApiLogin = _apiLogin
     };
 }
        public async Task <dynamic> Call(ApiEndpoint endpoint, dynamic body, List <int> expectedStatusCodes)
        {
            string url = this.Config.Protocol + "://" + this.Config.Host + ":" + this.Config.Port + endpoint.Path;

            string data = "{}";

            if (body != null)
            {
                data = JsonConvert.SerializeObject(body);
            }

            client.DefaultRequestHeaders.Clear();
            foreach (var header in this.Authentication.PrepareHeaders(this.Config.ApiKey, endpoint.Method, endpoint.Path, data))
            {
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }


            HttpResponseMessage response = null;

            switch (endpoint.Method)
            {
            case Api.METHOD.GET:
                response = await client.GetAsync(url);

                break;

            case Api.METHOD.POST:
                response = await client.PostAsync(url, new StringContent(data, Encoding.UTF8, "application/json"));

                break;

            case Api.METHOD.DELETE:
                response = await client.DeleteAsync(url);

                break;
            }

            string responseBody = await HandleResponseAsync(response, expectedStatusCodes);

            return(JsonConvert.DeserializeObject("{'statusCode': " + (int)response.StatusCode + "," + " 'body': " + responseBody + "}"));
        }
Exemple #23
0
        public HttpResponseMessage Endpoints()
        {
            IList <ApiEndpoint> apiEndpoints = new List <ApiEndpoint>();

            ApiExplorer apiExplorer = new ApiExplorer(ControllerContext.Configuration);

            foreach (var endpoint in apiExplorer.ApiDescriptions)
            {
                ApiEndpoint apiEndpoint = apiEndpoints.FirstOrDefault(a => a.RouteTemplate.Equals(endpoint.Route.RouteTemplate));
                if (apiEndpoint == null)
                {
                    apiEndpoint = new ApiEndpoint(endpoint.Route.RouteTemplate);
                    apiEndpoints.Add(apiEndpoint);
                }

                apiEndpoint.AddMethod(endpoint.HttpMethod.Method);
            }

            return(Request.CreateResponse(HttpStatusCode.OK, apiEndpoints.OrderBy(a => a.RouteTemplate)));
        }
Exemple #24
0
        private string GenerateMethodDocumentationForEndpoint(ApiEndpoint apiEndpoint)
        {
            var indent  = new Indent();
            var builder = new StringBuilder();

            // Documentation for method
            if (!string.IsNullOrEmpty(apiEndpoint.Documentation))
            {
                builder.Append(
                    indent.Wrap(
                        apiEndpoint.Documentation.ToCSharpDocumentationComment()));
            }

            // Remarks (required permissions)
            if (apiEndpoint.Rights != null && apiEndpoint.Rights.Count > 0)
            {
                builder.AppendLine($"{indent}/// <remarks>");
                builder.AppendLine($"{indent}/// Required permissions:");
                builder.AppendLine($"{indent}/// <list type=\"bullet\">");
                foreach (var apiRight in apiEndpoint.Rights)
                {
                    builder.AppendLine($"{indent}/// <item>");
                    builder.AppendLine($"{indent}/// <term>{apiRight.Title}</term>");
                    if (!string.IsNullOrEmpty(apiRight.Description))
                    {
                        builder.AppendLine($"{indent}/// <description>{apiRight.Description}</description>");
                    }
                    builder.AppendLine($"{indent}/// </item>");
                }
                builder.AppendLine($"{indent}/// </list>");
                builder.AppendLine($"{indent}/// </remarks>");
            }

            // Attributes
            if (apiEndpoint.Deprecation != null)
            {
                builder.AppendLine(apiEndpoint.Deprecation.ToCSharpDeprecation());
            }

            return(builder.ToString());
        }
        } = 60;                                                  // Default to every minute

        /// <summary>
        /// Go over the values in the configuration and validate them and also fix any issues
        /// such as leading characters etc,
        /// </summary>
        /// <returns></returns>
        public Boolean Parse()
        {
            if ((SignalREndpoint ?? String.Empty).Trim() == String.Empty)
            {
                throw new Exception("No SignalR Endpoint defined for Application Monitor");
            }
            else
            {
                // Clean endpoint string
                if (!SignalREndpoint.StartsWith('/'))
                {
                    SignalREndpoint = $"/{SignalREndpoint}".Trim();
                }
            }

            if ((ApiEndpoint ?? String.Empty).Trim() == String.Empty)
            {
                throw new Exception("No API Endpoint defined for Application Monitor");
            }
            {
                // Clean endpoint string
                if (!ApiEndpoint.StartsWith('/'))
                {
                    ApiEndpoint = $"/{ApiEndpoint}".Trim();
                }
            }

            if ((SaveLocation ?? String.Empty).Trim() == String.Empty)
            {
                throw new Exception("No save location defined for Application Monitor");
            }

            if (BackgroundTaskInterval < 60)
            {
                throw new Exception("Application Monitor Background Task Interval is too short at less than 60 seconds");
            }

            return(true);
        }
Exemple #26
0
        public async Task StatusAsync([Summary("Name of service")] string service, [Summary("How many hours to go back for comparison stats")]  int hours = 0)
        {
            _log.Info($"{Context.User.Username} executed !stats command with parameter {service}");

            var builder = new EmbedBuilder()
            {
                Color = Const.DISCORD_EMBED_COLOR,
            };

            switch (service)
            {
            case "hookapp":
                ServerStats stats    = _stats.Where(o => string.IsNullOrEmpty(o.error)).LastOrDefault();
                ServerStats compared = null;

                if (stats == null)
                {
                    _log.Info($"Ho history of stats available. Forcefully getting one from server.");
                    stats = ApiEndpoint.GetServerStats();
                }

                var historyList = _stats.Where(o => string.IsNullOrEmpty(o.error)).Take(_stats.Count() - 1).ToList();
                if (hours.Equals(0))
                {
                    compared = historyList.LastOrDefault();
                }
                else
                {
                    _log.Info($"Getting history stats from {hours} hours ago");
                    var queryDay = DateTime.Now.Subtract(TimeSpan.FromHours(hours));
                    compared = historyList.OrderBy(o => Math.Abs((o.date.Subtract(queryDay).Ticks))).FirstOrDefault();
                }

                _log.Info($"Replying with server status for service {service}");
                await Context.Channel.SendMessageAsync("", false, DiscordMessageFormatter.GetServiceHookappMessage(stats, compared).Build());

                break;
            }
        }
        public async Task Get()
        {
            const string expectedOutput  = "Request handled by next request delegate";
            var          requestDelegate = new RequestDelegate((innerHttpContext) =>
            {
                innerHttpContext.Response.WriteAsync(expectedOutput);
                return(Task.CompletedTask);
            });

            // Arrange
            DefaultHttpContext defaultContext = new DefaultHttpContext();

            defaultContext.Response.Body = new MemoryStream();
            defaultContext.Request.Path  = "/";

            var infoHandler = new Mock <IInfoCollector>();

            RegisterServiceWithInstance <IInfoCollector>(infoHandler.Object);

            // Act
            var middlewareInstance = new ApiEndpoint(
                next: requestDelegate,
                serviceScopeFactory: _serviceScopeFactory.Object);

            await middlewareInstance.InvokeAsync(defaultContext);

            infoHandler.Verify(x => x.AggregateData());

            //defaultContext.Response.Body.Seek(0, SeekOrigin.Begin);
            //var body = new StreamReader(defaultContext.Response.Body).ReadToEnd();
            //var jsonData = JsonDocument.Parse(body);
            //var items = jsonData.RootElement.EnumerateObject();

            // Assert
            //Assert.True(items.Count() > 0, "No data in JSON response");
        }
Exemple #28
0
        private static void PatchRequestParameters(ApiEndpoint endpoint)
        {
            var newParams = ApiQueryParametersPatcher.Patch(endpoint.Name, endpoint.Url.Params, endpoint.Overrides);

            endpoint.Url.Params = newParams;
        }
        public async Task <IPlatformResponse <T> > Request <T>(ApiEndpoint endpoint, string relativePath, CancellationToken cancellationToken, IProgress <ISDKProgress> progress = null, HttpMethod method = null, string body = null, byte[] rawData = null, string contentType = "application/json", IDictionary <string, string> headers = null)
        {
            var monitor = _container.Resolve <IProgressMonitor>();

            if (progress != null)
            {
                monitor.Progress = progress;
                monitor.Start();
            }
            monitor.Report("Initializing Http Request", 0);

            var _method = HttpMethod.Get;

            if (method != null)
            {
                _method = method;
            }

            var platformResponse = new PlatformResponse <T>
            {
                Success = false
            };

            if (headers != null && headers.Count > 0)
            {
                if (headers.ContainsKey("Authorization"))
                {
                    var h = headers["Authorization"];
                    if (h.IndexOf(" ", StringComparison.Ordinal) > 0)
                    {
                        var type  = h.Substring(0, h.IndexOf(" ", StringComparison.Ordinal)).Trim();
                        var token = h.Substring(h.IndexOf(" ", StringComparison.Ordinal)).Trim();
                        AuthorizationType           = type;
                        Authorization.MojioApiToken = token;
                        headers.Remove("Authorization");
                    }
                }
            }

            HttpClient client;

            switch (endpoint)
            {
            case ApiEndpoint.Accounts:
                client = AccountsClient(contentType);
                break;

            case ApiEndpoint.Images:
                client = ImagesClient(contentType);
                break;

            case ApiEndpoint.Push:
                client = PushClient(contentType);
                break;

            default:
                client = ApiClient(contentType);
                break;
            }

            var request = new HttpRequestMessage(_method, relativePath);

            monitor.Report("Setting HttpContent Body", 0.1);

            if (!string.IsNullOrEmpty(body))
            {
                Debug.WriteLine($"Request Content:{body}");
                request.Content = new StringContent(body, Encoding.UTF8, contentType);
            }

            monitor.Report("Set HttpContent Body", 0.2);

            if (rawData != null)
            {
                monitor.Report("Creating MultiPart Form Content", 0.2);

                var requestContent = new MultipartFormDataContent(); //"Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture));

                var imageContent = new ByteArrayContent(rawData);
                var fileName     = "image.png";
                var type         = "image/png";

                if (headers != null && headers.Count > 0)
                {
                    type     = (from x in headers where x.Key == "Content-Type" select x.Value).FirstOrDefault();
                    fileName = (from x in headers where x.Key == "Filename" select x.Value).FirstOrDefault();
                    if (!string.IsNullOrEmpty(type))
                    {
                        headers.Remove("Content-Type");
                    }
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        headers.Remove("Filename");
                    }
                }

                imageContent.Headers.ContentDisposition          = ContentDispositionHeaderValue.Parse("form-data");
                imageContent.Headers.ContentDisposition.Name     = "\"file\"";
                imageContent.Headers.ContentDisposition.FileName = fileName;
                imageContent.Headers.ContentDisposition.Size     = rawData.Length;
                imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(type);

                requestContent.Add(imageContent);
                request.Content = requestContent;

                monitor.Report("Created MultiPart Form Content", 0.3);
            }
            monitor.Report("Adding Headers", 0.4);

            if (headers != null && headers.Count > 0)
            {
                foreach (var h in headers)
                {
                    request.Headers.Add(h.Key, h.Value);
                }
            }
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));

            if (DisableSessionAffinity)
            {
                request.Headers.Add("Arr-Disable-Session-Affinity", "True");
            }

            monitor.Report("Added Headers", 0.4);

            if (cancellationToken.IsCancellationRequested)
            {
                platformResponse.WasCancelled = true;
                monitor.Report("Operation Cancelled", 0.5);
                return(platformResponse);
            }
            monitor.Report("Sending Http Request", 0.6);
            var requestSw = new Stopwatch();

            requestSw.Start();
            Debug.WriteLine($"Pre-flight request URL: {request.RequestUri}");

            using (var sendResult = await client.SendAsync(request, cancellationToken))
            {
                platformResponse.RequestDurationMS = requestSw.ElapsedMilliseconds;
                monitor.Report("Received Response from Http Request", 0.7);
                requestSw.Stop();

                platformResponse.Url = sendResult.RequestMessage.RequestUri.ToString();
                Debug.WriteLine($"Post-flight request URL: {platformResponse.Url}");
                platformResponse.Timestamp      = DateTimeOffset.UtcNow;
                platformResponse.HttpStatusCode = sendResult.StatusCode;
                Debug.WriteLine($"Status Code: {platformResponse.HttpStatusCode}");

                try
                {
                    var cookie = (from h in sendResult.Headers where h.Key == "Set-Cookie" select h.Value.FirstOrDefault()).FirstOrDefault();
                    if (cookie != null)
                    {
                        platformResponse.ARRAffinityInstance = (from c in cookie.Split(';') where c.StartsWith("") select c.Split('=').LastOrDefault()).FirstOrDefault();
                    }
                }
                catch (Exception)
                {
                }

                if (sendResult.IsSuccessStatusCode)
                {
                    monitor.Report("Received Successful StatusCode", 0.8);
                    if (cancellationToken.IsCancellationRequested)
                    {
                        platformResponse.WasCancelled = true;
                        monitor.Report("Operation Cancelled", 0.9);
                        return(platformResponse);
                    }

                    monitor.Report("Reading data from Response", 0.9);
                    var json = await sendResult.Content.ReadAsStringAsync();

                    monitor.Report("Deserializing data", 0.95);
                    try
                    {
                        platformResponse.Response = _serializer.Deserialize <T>(json);
                        if (platformResponse.Response != null)
                        {
                            platformResponse.Success = true;
                        }
                    }
                    catch (Exception e)
                    {
                        _log.Error(e, "Invalid response from the server. Received:{0}, expected:{1}.  Will continue.", json, typeof(T));
                    }

                    if (typeof(T) == typeof(IAuthorization))
                    {
                        monitor.Report("Setting internal auth token", 0.99);
                        Authorization.MojioApiToken = (platformResponse.Response as IAuthorization).AccessToken;
                        _container.RegisterInstance(Authorization, "Session");
                    }
                }
                else
                {
                    monitor.Report("Received Unsuccessful StatusCode", 0.8);

                    platformResponse.Success      = false;
                    platformResponse.ErrorCode    = sendResult.StatusCode.ToString();
                    platformResponse.ErrorMessage = sendResult.ReasonPhrase;

                    monitor.Report("Reading data from Response", 0.9);
                    var content = await sendResult.Content.ReadAsStringAsync();

                    Debug.WriteLine(content);
                    Debug.WriteLine(_serializer.SerializeToString(request));

                    if (!string.IsNullOrEmpty(content))
                    {
                        try
                        {
                            monitor.Report("Deserializing data", 0.95);
                            dynamic result = _serializer.Deserialize(content);
                            if (result != null)
                            {
                                if (result.Message != null)
                                {
                                    platformResponse.ErrorMessage = platformResponse.ErrorMessage + ", " + result.Message;
                                }
                                else
                                {
                                    platformResponse.ErrorMessage = platformResponse.ErrorMessage + ", " + content;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            monitor.Report("Finished", 1);

            monitor.Stop();

            return(platformResponse);
        }
Exemple #30
0
        public SharePointFileManager(IConfiguration Configuration)
        {
            // create the HttpClient that is used for our direct REST calls.
            _CookieContainer   = new CookieContainer();
            _HttpClientHandler = new HttpClientHandler()
            {
                UseCookies = true, AllowAutoRedirect = false, CookieContainer = _CookieContainer
            };
            _Client = new HttpClient(_HttpClientHandler);

            _Client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

            // SharePoint configuration settings.

            string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"];
            string sharePointOdataUri       = Configuration["SHAREPOINT_ODATA_URI"];
            string sharePointWebname        = Configuration["SHAREPOINT_WEBNAME"];
            string sharePointNativeBaseURI  = Configuration["SHAREPOINT_NATIVE_BASE_URI"];

            // ADFS using fed auth

            string sharePointStsTokenUri            = Configuration["SHAREPOINT_STS_TOKEN_URI"];            // Full URI to the STS service we will use to get the initial token.
            string sharePointRelyingPartyIdentifier = Configuration["SHAREPOINT_RELYING_PARTY_IDENTIFIER"]; // use Fiddler to grab this from an interactive session.  Will normally start with urn:
            string sharePointUsername = Configuration["SHAREPOINT_USERNAME"];                               // Service account username.  Be sure to add this user to the SharePoint instance.
            string sharePointPassword = Configuration["SHAREPOINT_PASSWORD"];                               // Service account password

            // SharePoint Online
            string sharePointAadTenantId  = Configuration["SHAREPOINT_AAD_TENANTID"];
            string sharePointClientId     = Configuration["SHAREPOINT_CLIENT_ID"];
            string sharePointCertFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"];
            string sharePointCertPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"];

            // Basic Auth (SSG API Gateway)
            string ssgUsername = Configuration["SSG_USERNAME"];  // BASIC authentication username
            string ssgPassword = Configuration["SSG_PASSWORD"];  // BASIC authentication password

            // sometimes SharePoint could be using a different username / password.
            string sharePointSsgUsername = Configuration["SHAREPOINT_SSG_USERNAME"];
            string sharePointSsgPassword = Configuration["SHAREPOINT_SSG_PASSWORD"];

            if (string.IsNullOrEmpty(sharePointSsgUsername))
            {
                sharePointSsgUsername = ssgUsername;
            }

            if (string.IsNullOrEmpty(sharePointSsgPassword))
            {
                sharePointSsgPassword = ssgPassword;
            }

            OdataUri       = sharePointOdataUri;
            ServerAppIdUri = sharePointServerAppIdUri;
            NativeBaseUri  = sharePointNativeBaseURI;
            WebName        = sharePointWebname;

            // ensure the webname has a slash.
            if (!string.IsNullOrEmpty(WebName) && WebName[0] != '/')
            {
                WebName = "/" + WebName;
            }


            ApiEndpoint = sharePointOdataUri;
            // ensure there is a trailing slash.
            if (!ApiEndpoint.EndsWith("/"))
            {
                ApiEndpoint += "/";
            }
            ApiEndpoint += "_api/";


            // Scenario #1 - ADFS (2016) using FedAuth
            if (!string.IsNullOrEmpty(sharePointRelyingPartyIdentifier) &&
                !string.IsNullOrEmpty(sharePointUsername) &&
                !string.IsNullOrEmpty(sharePointPassword) &&
                !string.IsNullOrEmpty(sharePointStsTokenUri)
                )
            {
                Authorization = null;
                var samlST = Authentication.GetStsSamlToken(sharePointRelyingPartyIdentifier, sharePointUsername, sharePointPassword, sharePointStsTokenUri).GetAwaiter().GetResult();
                //FedAuthValue =
                Authentication.GetFedAuth(sharePointOdataUri, samlST, sharePointRelyingPartyIdentifier, _Client, _CookieContainer).GetAwaiter().GetResult();
            }
            // Scenario #2 - SharePoint Online (Cloud) using a Client Certificate
            else if (!string.IsNullOrEmpty(sharePointAadTenantId) &&
                     !string.IsNullOrEmpty(sharePointCertFileName) &&
                     !string.IsNullOrEmpty(sharePointCertPassword) &&
                     !string.IsNullOrEmpty(sharePointClientId)
                     )
            {
                // add authentication.
                var authenticationContext = new AuthenticationContext(
                    "https://login.windows.net/" + sharePointAadTenantId);

                // Create the Client cert.
                X509Certificate2           cert = new X509Certificate2(sharePointCertFileName, sharePointCertPassword);
                ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(sharePointClientId, cert);

                //ClientCredential clientCredential = new ClientCredential(clientId, clientKey);
                var task = authenticationContext.AcquireTokenAsync(sharePointServerAppIdUri, clientAssertionCertificate);
                task.Wait();
                authenticationResult = task.Result;
                Authorization        = authenticationResult.CreateAuthorizationHeader();
            }
            else
            // Scenario #3 - Using an API Gateway with Basic Authentication.  The API Gateway will handle other authentication and have different credentials, which may be NTLM
            {
                // authenticate using the SSG.
                string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(sharePointSsgUsername + ":" + sharePointSsgPassword));
                Authorization = "Basic " + credentials;
            }

            // Authorization header is used for Cloud or Basic API Gateway access
            if (!string.IsNullOrEmpty(Authorization))
            {
                _Client.DefaultRequestHeaders.Add("Authorization", Authorization);
            }

            // Add a Digest header.  Needed for certain API operations
            Digest = GetDigest(_Client).GetAwaiter().GetResult();
            if (Digest != null)
            {
                _Client.DefaultRequestHeaders.Add("X-RequestDigest", Digest);
            }

            // Standard headers for API access
            _Client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            _Client.DefaultRequestHeaders.Add("OData-Version", "4.0");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RestApiClient" /> class.
 /// </summary>
 /// <param name="endpoint">The endpoint.</param>
 /// <param name="acceptGZip">if set to <c>true</c> [accept g zip].</param>
 public RestApiClient(ApiEndpoint endpoint, bool acceptGZip = false)
     : this(endpoint?.ToString(), endpoint.Token, acceptGZip)
 {
 }