public HttpServer Start(Uri apiBaseUrl = null)
        {
            var count = 0;

            CallContext.LogicalSetData(nameof(HttpServer), _builders);
            _builders = new List <Action <IAppBuilder> >();
            while (true)
            {
                try
                {
                    ApiBaseUrl = apiBaseUrl ?? new Uri($"http://localhost:{Random.Next(1000, 9999)}/");
                    var url = ApiBaseUrl.ToString().Replace("localhost", "*");
                    _server = WebApp.Start <HttpServer>(url);
                    break;
                }
                catch
                {
                    if (count++ == 2)
                    {
                        throw;
                    }
                }
            }

            return(this);
        }
Exemplo n.º 2
0
        internal string GetApiRootUrl()
        {
            ApiBaseUrl = ApiBaseUrl.Replace("http:", "https:");
            var result = this.ApiBaseUrl.TrimEnd('/') + "/" + EnumDescriptionAttributeHelper.GetDescription(this.ApiVersion);

            return(result.Trim('/'));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates a new context using the supplied settings.
        /// </summary>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public ApiContext(string apiBaseUrl, string apiKey)
        {
            ApiBaseUrl = apiBaseUrl ?? throw new ArgumentNullException(nameof(apiBaseUrl));
            ApiKey     = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
            if (string.IsNullOrWhiteSpace(ApiBaseUrl))
            {
                throw new ArgumentException("Cannot be blank.", nameof(apiBaseUrl));
            }
            if (string.IsNullOrWhiteSpace(ApiKey))
            {
                throw new ArgumentException("Cannot be blank.", nameof(apiKey));
            }

            if (!ApiBaseUrl.EndsWith("/"))
            {
                ApiBaseUrl += "/";
            }

            Customers     = new CustomerApiEndpoint(this);
            Contacts      = new ContactApiEndpoint(this);
            Agents        = new AgentApiEndpoint(this);
            Alerts        = new AlertApiEndpoint(this);
            Invoices      = new InvoiceApiEndpoint(this);
            ProductRates  = new RateApiEndpoint(this, "products");
            ExpenseRates  = new RateApiEndpoint(this, "expenses");
            Contracts     = new ContractApiEndpoint(this);
            KnowledgeBase = new KnowledgeBaseApiEndpoint(this);
            Tickets       = new TicketApiEndpoint(this);
            CustomValues  = new CustomValueApiEndpoint(this);
        }
Exemplo n.º 4
0
        public async Task <JsonResult> SaveApiBaseUrl(ApiBaseUrl model)
        {
            using (ApiManaRepository rep = new ApiManaRepository())
            {
                var res = await rep.AddOrUpdateApiBaseUrlAsync(model);

                return(Json(new { isOk = res }));
            }
        }
Exemplo n.º 5
0
        public static void AddCarRentApi(this IServiceCollection serviceCollection, string username, string password)
        {
            string baseUrl = "http://tss.ir/rentapi";
            var    url     = new ApiBaseUrl {
                BaseUrl = baseUrl
            };

            serviceCollection.AddMemoryCache();
            serviceCollection.AddTransient <IBaseUrl>(c => url);
            serviceCollection.AddTransient <IApiClient, ApiClient>();
            serviceCollection.AddTransient <TokenConfiguration>(tc => new TokenConfiguration(username, password));
            serviceCollection.AddTransient <ITokenProvider, TokenProvider>();
            serviceCollection.AddTransient <ICarRentApi, CarRentApi>();
        }
Exemplo n.º 6
0
        public void UserExists_ForAdminUser_OverHttp_ReturnsHttpForbidden()
        {
            var httpApiUrl   = "http" + ApiBaseUrl.TrimStart("https".ToCharArray());
            var restClient   = new RestClient(httpApiUrl);
            var objectToPost = new UserExistsReq {
                EmailId = TestHelper.Constants.DatabaseStaticEntities.AdminUserEmail
            };
            RestRequest request = CreateRequestDelayed(ServiceUrl, UserExitsActionUrl, objectToPost);

            IRestResponse response    = restClient.Post(request);
            string        jsonContent = response.Content;
            var           apiResponse = JsonConvert.DeserializeObject <ApiResponseDto <object> >(jsonContent);

            Assert.AreEqual(response.StatusCode, HttpStatusCode.Forbidden);
            Assert.IsNotNull(apiResponse.Error);
            Assert.IsNull(apiResponse.Result);
        }
Exemplo n.º 7
0
        public async Task <bool> AddOrUpdateApiBaseUrlAsync(ApiBaseUrl para)
        {
            var isAdd = false;
            var model = await context.ApiBaseUrls.Where(p => p.Id == para.Id).FirstOrDefaultAsync();

            if (model == null)
            {
                isAdd = true;
                model = new ApiBaseUrl();
            }
            model.BaseName = para.BaseName;
            model.BaseUrl  = para.BaseUrl;
            model.Remark   = para.Remark;
            if (isAdd)
            {
                context.ApiBaseUrls.Add(model);
            }
            return(await context.SaveChangesAsync() == 1);
        }
Exemplo n.º 8
0
        public async Task githubMarkdown(ScriptScopeContext scope, string markdownPath)
        {
            var file         = Context.ProtectedMethods.ResolveFile(nameof(githubMarkdown), scope, markdownPath);
            var htmlFilePath = file.VirtualPath.LastLeftPart('.') + ".html";
            var cacheKey     = nameof(GitHubMarkdownScripts) + ">" + htmlFilePath;

            var htmlFile = Context.VirtualFiles.GetFile(htmlFilePath);

            if (htmlFile != null && htmlFile.LastModified >= file.LastModified)
            {
                if (UseMemoryCache)
                {
                    byte[] bytes;
                    if (!Context.Cache.TryGetValue(cacheKey, out object oBytes))
                    {
                        using (var stream = htmlFile.OpenRead())
                        {
                            var ms = MemoryStreamFactory.GetStream();
                            using (ms)
                            {
                                await stream.CopyToAsync(ms);

                                ms.Position             = 0;
                                bytes                   = ms.ToArray();
                                Context.Cache[cacheKey] = bytes;
                            }
                        }
                    }
                    else
                    {
                        bytes = (byte[])oBytes;
                    }

                    scope.OutputStream.Write(bytes, 0, bytes.Length);
                }
                else
                {
                    using (var htmlReader = htmlFile.OpenRead())
                    {
                        await htmlReader.CopyToAsync(scope.OutputStream);
                    }
                }
            }
            else
            {
                var ms = MemoryStreamFactory.GetStream();
                using (ms)
                {
                    using (var stream = file.OpenRead())
                    {
                        await stream.CopyToAsync(ms);
                    }

                    ms.Position = 0;
                    var bytes = ms.ToArray();

                    var htmlBytes = RepositoryContext == null
                        ? await ApiBaseUrl.CombineWith("markdown", "raw")
                                    .PostBytesToUrlAsync(bytes, contentType: MimeTypes.PlainText,
                                                         requestFilter: x => x.UserAgent = "#Script")
                        : await ApiBaseUrl.CombineWith("markdown")
                                    .PostBytesToUrlAsync(
                        new Dictionary <string, string> {
                        { "text", bytes.FromUtf8Bytes() }, { "mode", Mode }, { "context", RepositoryContext }
                    }.ToJson().ToUtf8Bytes(),
                        contentType: MimeTypes.Json, requestFilter: x => x.UserAgent = "#Script");


                    var headerBytes = "<div class=\"gfm\">".ToUtf8Bytes();
                    var footerBytes = "</div>".ToUtf8Bytes();

                    var wrappedBytes = new byte[headerBytes.Length + htmlBytes.Length + footerBytes.Length];
                    System.Buffer.BlockCopy(headerBytes, 0, wrappedBytes, 0, headerBytes.Length);
                    System.Buffer.BlockCopy(htmlBytes, 0, wrappedBytes, headerBytes.Length, htmlBytes.Length);
                    System.Buffer.BlockCopy(footerBytes, 0, wrappedBytes, headerBytes.Length + htmlBytes.Length,
                                            footerBytes.Length);

                    if (Context.VirtualFiles is IVirtualFiles vfs)
                    {
                        var fs = vfs.GetFileSystemVirtualFiles();
                        fs.DeleteFile(htmlFilePath);
                        fs.WriteFile(htmlFilePath, wrappedBytes);
                    }

                    if (UseMemoryCache)
                    {
                        Context.Cache[cacheKey] = wrappedBytes;
                    }

                    await scope.OutputStream.WriteAsync(wrappedBytes, 0, wrappedBytes.Length);
                }
            }
        }
 public WeatherForecastClientService(HttpClient httpClient, ApiBaseUrl apiBaseUrl)
 {
     this.httpClient             = httpClient;
     this.httpClient.BaseAddress = apiBaseUrl.Uri;
 }