/// <summary> /// Initializes a new instance of the <see cref="ApiVersionApiExplorer"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="options">The generation options</param> public ApiVersionApiExplorer(HttpConfiguration configuration, ApiExplorerUrlOptions options) { _configuration = configuration; _options = options; _apiDescriptions = new Lazy <Collection <ApiDescription> >(InitializeApiDescriptions); _apiExplorer = new ApiExplorer(configuration); }
public override async Task <bool> Execute(Message message, TelegramBotClient botClient) { var endCommand = false; switch (_typeRequest) { case TypeRequest.Start: _typeRequest = TypeRequest.Resource; await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, "Insert <b>resource</b> (eg nodes)"); break; case TypeRequest.Resource: var ret = ApiExplorer.Usage(PveHelper.GetClassApiRoot(), message.Text.Trim(), true, null, true); await botClient.SendDocumentAsyncFromText(message.Chat.Id, ret, "Usage.txt"); endCommand = true; break; default: break; } return(await Task.FromResult(endCommand)); }
public static void Init(TestContext testContext) { var t = typeof(CompaniesController); var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.EnsureInitialized(); var apiExplorer = new ApiExplorer(config); var settings = new JsonSerializerSettings(); var versions = new Dictionary <string, Info> { { "v1", new Info() { version = "v1", title = "Test API" } } }; var options = new SwaggerGeneratorOptions(operationFilters: new IOperationFilter[] { // default filters used by Swashbuckle new HandleFromUriParams(), new ApplySwaggerOperationAttributes(), new ApplySwaggerResponseAttributes(), new ApplySwaggerOperationFilterAttributes(), // our custom filters new AddAsObjectAnnotationOperationFilter(), new HandleGridViewDataSetReturnType() }); var generator = new SwaggerGenerator(apiExplorer, settings, versions, options); document = generator.GetSwagger("http://localhost:61453/", "v1"); }
static void Main(string[] args) { var authClient = new OAuthClient("*****@*****.**", "password"); var apiContext = new ApiContext(authClient.GetSecureToken()) { AppName = "Application name", }; var api = new ApiExplorer(apiContext); // get template for new contact var template = api.Contacts.Default(); // cast to insert model var contact = (ContactCreate)template; // fill new contact contact.CompanyName = "New Company"; // insert var addedContact = api.Contacts.Create(contact); // delete bool isDeleted = api.Contacts.Delete(addedContact.Id); List <ValidationMessage> errors; bool isValid = ApiValidator.ValidateObject(contact, out errors); if (isValid) { var result = api.Contacts.Create(new ContactCreate()); } }
public string[] GetSuggestions(string text, int index) { if (text.StartsWith("ls /") || text.StartsWith("create /") || text.StartsWith("delete /") || text.StartsWith("get /") || text.StartsWith("set /") || text.StartsWith("usage /")) { var resource = text.Substring(text.IndexOf("/")).Trim(); var ret = ApiExplorer.ListValues(Client, ClassApiRoot, resource); if (!string.IsNullOrWhiteSpace(ret.Error)) { //try previous slash var pos = resource.LastIndexOf('/'); ret = ApiExplorer.ListValues(Client, ClassApiRoot, resource.Substring(0, pos)); return(ret.Values.Where(a => a.Value.StartsWith(resource.Substring(pos + 1))) .Select(a => a.Value) .ToArray()); } else { return(ret.Values.Select(a => a.Value).ToArray()); } } else { return(null); } }
public static ICollection <AbilityRequirement> ScanApiEndpointsForRequirements(this HttpConfiguration config) { var explorer = new ApiExplorer(config); var endpoints = new List <AbilityRequirement>(); foreach (var description in explorer.ApiDescriptions) { var action = description.ActionDescriptor; var endpoint = new AbilityRequirement { HttpMethod = description.HttpMethod.Method, Controller = description.ActionDescriptor.ControllerDescriptor.ControllerName, Action = description.ActionDescriptor.ActionName, EndpointPath = $"/{description.RelativePath}" }; var pipeline = action.GetFilterPipeline(); foreach (var filter in pipeline.OfType <CustomAttribute>()) { endpoint.Policies.Add(filter.AbilityType.Name); } endpoints.Add(endpoint); } return(endpoints); }
public override async Task<bool> Execute(Message message, TelegramBotClient botClient) { var endCommand = false; switch (_typeRequest) { case TypeRequest.Start: _typeRequest = TypeRequest.Resource; await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, Base.DEFAULT_MSG); break; case TypeRequest.Resource: var ret = ApiExplorer.Usage(PveHelper.GetClassApiRoot(PveHelper.GetClient()), message.Text.Trim(), ApiExplorer.OutputType.Html, true, null, true); await botClient.SendDocumentAsyncFromText(message.Chat.Id, ret, "Usage.html"); endCommand = true; break; default: break; } return await Task.FromResult(endCommand); }
public void Setup() { // Get ApiExplorer for TestApp var httpConfiguration = new HttpConfiguration(); TestApp.WebApiConfig.Register(httpConfiguration); _apiExplorer = new ApiExplorer(httpConfiguration); }
public void Setup() { // Get dummy ApiExplorer var config = new HttpConfiguration(); Dummy.WebApiConfig.Register(config); _apiExplorer = new ApiExplorer(config); config.EnsureInitialized(); }
private string HelpContent() { var sb = new StringBuilder(); var apiExExplorer = new ApiExplorer(ControllerContext.Configuration); foreach (var api in apiExExplorer.ApiDescriptions) { sb.AppendFormat("<li><a href='{0}'>/{1}</a> - {2} - {3}", ToLink(api.RelativePath), api.RelativePath.ToLower(), api.HttpMethod, api.Documentation); // if (api.ParameterDescriptions.Count > 0) // { // sb.AppendFormat("<ul>"); // foreach (var parameter in api.ParameterDescriptions) // { // sb.AppendFormat("<li>{0}: {1} ({2})</li>", parameter.Name, parameter.Documentation, parameter.Source); // } // sb.AppendFormat("</ul></li>"); // } } var content = string.Format(@" <!DOCTYPE html> <html> <head> <title>httpapi - Request Response Service</title> <style> body {{font-family: monospace;font-size:14px;line-height:1.5em;}} a:visited {{color: blue}} ul {{list-style: none}} </style> </head> <body> <a href='http://github.com/chandmk/httpapi'><img style='position: absolute; top: 0; right: 0; border: 0;' src='https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png' alt='Fork me on GitHub'></a> <h1>httpapi - Request Response Service</h1> <section> <h3>ENDPOINTS</h3> <ul> {0} </ul> </section> <section> <h3>DESCRIPTION</h3> <ul><li> Inspiration for this service is from httpbin.org.</li> <li>This service provides api for http scenarios. </li> <li>All endpoints, where it makes sense by default return JSON-encoded content.</li> <li>You can also request for xml/json by adding respective extension.</li> <li> <a href='/get.xml' > /get.xml </a> returns xml content. </li><li> <a href='/get.json' > /get.json </a> returns json content.</li></ul> </section> </body> </html>", sb); return(content); }
public void Setup() { // Get ApiExplorer for TestApp var httpConfiguration = new HttpConfiguration(); TestApp.WebApiConfig.Register(httpConfiguration); _apiExplorer = new ApiExplorer(httpConfiguration); var xmlCommentsDoc = new XPathDocument(String.Format(@"{0}\XmlComments.xml", AppDomain.CurrentDomain.BaseDirectory)); _filter = new ApplyActionXmlComments(xmlCommentsDoc); }
public void Setup() { // Basic config _config = new SwaggerSpecConfig() .ResolveBasePath(() => "http://tempuri.org"); // Get ApiExplorer for TestApp var httpConfiguration = new HttpConfiguration(); WebApiConfig.Register(httpConfiguration); _apiExplorer = new ApiExplorer(httpConfiguration); }
static void Main(string[] args) { //var authCredentials = new AuthorizationCodeAuth("client_id", "client_secret", "code", "http://localhost:3432"); //var url = AuthorizationCodeAuth.GetClientAuthenticationUrl("client_id", "http://localhost:3432"); // choose authorization flow var clientCred = new ClientCredentialAuth("client_id", "client_secret"); // initialise context with configuration var apiContext = new ApiContext(clientCred) { AppName = "Application name" }; // initialise api explorer var api = new ApiExplorer(apiContext); // get template for new contact var template = api.Contacts.Default(); // cast to insert model var contact = (ContactCreate)template; // fill new contact contact.CompanyName = "New Company"; // insert var addedContact = api.Contacts.Create(contact); // delete bool isDeleted = api.Contacts.Delete(addedContact.Id); // get all var allContacts = api.Contacts.Contacts(new ApiFilter().WithPaging(1, int.MaxValue)); // prepare custom filter for querying var contactFilter = new ContactFilter(); contactFilter.DateLastChange.IsEqualOrGreatherThan(new DateTime(2016, 1, 1)); // query data using custom filter var contacts = api.Contacts.ContactsExpand( new ApiFilter(contactFilter, FilterType.And).AddOrderDesc("Id").WithPaging(1, 5)); List <ValidationMessage> errors; bool isValid = ApiValidator.ValidateObject(contact, out errors); if (isValid) { var result = api.Contacts.Create(new ContactCreate()); } }
public void Setup() { // Get dummy ApiExplorer var config = new HttpConfiguration(); Dummy.WebApiConfig.Register(config); _apiExplorer = new ApiExplorer(config); config.EnsureInitialized(); var xmlCommentsDoc = new XPathDocument(String.Format(@"{0}\XmlComments.xml", AppDomain.CurrentDomain.BaseDirectory)); _filter = new ApplyActionXmlComments(xmlCommentsDoc); }
public override Task SetLastDownloadDateAsync(DateTime date) { if (string.IsNullOrWhiteSpace(Token)) { throw new InvalidOperationException("Fio bank token has not been set"); } var explorer = new ApiExplorer(Token); explorer.SetLastDownloadDateAsync(date); return(Task.FromResult(0)); }
private static void List(CommandLineApplication parent, PveClient client, ClassApi classApiRoot) { parent.Command("ls", cmd => { cmd.Description = "List child objects on <api_path>."; cmd.AddFullNameLogo(); var argResource = CreateResourceArgument(cmd); cmd.OnExecute(() => Console.Out.Write(ApiExplorer.List(client ?? cmd.ClientTryLogin(), classApiRoot ?? GetClassApiRoot(parent), argResource.Value))); }); }
public IntegrationTestBase() { if (Auth.AuthKey.IsNullOrEmpty()) { Assert.Ignore("Auth key is not presented"); } ApiExplorer = new ApiExplorer(new ApiContext(Auth.AuthKey) { AppName = "Idoklad.Sdk.Integration.Tests", AppVersion = SdkSettings.Version }); }
public override async Task <List <Transaction> > GetTransactionsAsync(Filter filter) { if (string.IsNullOrWhiteSpace(Token)) { throw new InvalidOperationException("Fio bank token has not been set"); } var explorer = new ApiExplorer(Token); var statement = await explorer.PeriodsAsync(FioFilter.LastDays(filter.Days)); nextPossibleSyncTime = DateTime.Now.AddSeconds(syncTimeOutinSec); return(GetTransactions(statement)); }
public void RegisterMappingsMiddleware_RegistersComponents() { // Arrange ContainerBuilder containerBuilder = new ContainerBuilder(); IConfigurationRoot config = new ConfigurationBuilder().Build(); ApiExplorer apiExplorer = new ApiExplorer(new HttpConfiguration()); // Act MappingsContainerBuilderExtensions.RegisterMappingsActuator(containerBuilder, config, apiExplorer); var container = containerBuilder.Build(); // Assert Assert.True(container.IsRegistered <IMappingsOptions>(), "Mappings options are registered"); Assert.True(container.IsRegistered <MappingsEndpoint>(), "Mappings endpoint is registered"); Assert.True(container.IsRegistered <MappingsEndpointOwinMiddleware>(), "Mappings endpoint middleware is registered"); }
public static List <ApiEndPoint> Get(HttpConfiguration config) { var apiDescriptions = new ApiExplorer(config).ApiDescriptions; var controllers = apiDescriptions .GroupBy(x => x.ActionDescriptor.ControllerDescriptor.ControllerName) .Select(x => x.First().ActionDescriptor.ControllerDescriptor.ControllerName) .ToList(); var apiEndPoints = new List <ApiEndPoint>(); foreach (var controller in controllers) { apiEndPoints.Add(getApiEndPoint(controller, config)); } return(apiEndPoints); }
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))); }
public void RegisterMappingsMiddleware_ThrowsOnNulls() { // Arrange ContainerBuilder containerNull = null; ContainerBuilder containerBuilder = new ContainerBuilder(); IConfigurationRoot configNull = null; IConfigurationRoot config = new ConfigurationBuilder().Build(); ApiExplorer apiExplorerNull = null; ApiExplorer apiExplorer = new ApiExplorer(new HttpConfiguration()); // Act var ex = Assert.Throws <ArgumentNullException>(() => MappingsContainerBuilderExtensions.RegisterMappingsActuator(containerNull, config, apiExplorer)); var ex2 = Assert.Throws <ArgumentNullException>(() => MappingsContainerBuilderExtensions.RegisterMappingsActuator(containerBuilder, configNull, apiExplorer)); var ex3 = Assert.Throws <ArgumentNullException>(() => MappingsContainerBuilderExtensions.RegisterMappingsActuator(containerBuilder, config, apiExplorerNull)); // Assert Assert.Equal("container", ex.ParamName); Assert.Equal("config", ex2.ParamName); Assert.Equal("apiExplorer", ex3.ParamName); }
static void Main(string[] args) { ApiExplorer explorer = new ApiExplorer("YOUR_TOKEN_MUST_BE_PRESENT_HERE"); // get new transactions from last check AccountStatement newTransactions = explorer.Last(); // change last check date explorer.SetLastDownloadDate(DateTime.UtcNow.AddMonths(-1)); // get account statement AccountStatement statement = explorer.Periods(TransactionFilter.LastMonth()); // browse transactions foreach (var transaction in statement.TransactionList.Transactions) { Console.WriteLine(transaction + " - " + transaction.Amount.Value); } // get data in specific format string data = explorer.Periods(TransactionFilter.LastDays(10), Format.Html); }
private static void Usage(CommandLineApplication parent, ClassApi classApiRoot) { parent.Command("usage", cmd => { cmd.Description = "Usage resource"; cmd.AddFullNameLogo(); var argResource = CreateResourceArgument(cmd); var optVerbose = cmd.VerboseOption(); var optCommand = cmd.OptionEnum <MethodType>("--command|-c", "API command"); var optResturns = cmd.Option("--returns|-r", "Including schema for returned data.", CommandOptionType.NoValue); cmd.OnExecute(() => { Console.Out.Write(ApiExplorer.Usage(classApiRoot ?? GetClassApiRoot(parent), argResource.Value, optResturns.HasValue(), optCommand.Value(), optVerbose.HasValue())); }); }); }
private static void Execute(CommandLineApplication parent, MethodType methodType, string description, PveClient client, ClassApi classApiRoot) { parent.Command(methodType.ToString().ToLower(), cmd => { cmd.Description = description; cmd.AddFullNameLogo(); var optVerbose = cmd.VerboseOption(); var argResource = CreateResourceArgument(cmd); var argParameters = cmd.Argument("parameters", "Parameter for resource format key:value (Multiple)." + " If value have space or special charapter using quote 'key:value'", true); var optOutput = cmd.OptionEnum <ApiExplorer.OutputType>("--output|-o", "Type output (default: unicode)"); var optWait = cmd.WaitOption(); cmd.OnExecute(() => { client = client ?? parent.ClientTryLogin(); classApiRoot = classApiRoot ?? GetClassApiRoot(client); var ret = ApiExplorer.Execute(client, classApiRoot, argResource.Value, methodType, ApiExplorer.CreateParameterResource(argParameters.Values), optWait.HasValue(), optOutput.GetEnumValue <ApiExplorer.OutputType>(), optVerbose.HasValue()); parent.Out.Write(ret.ResultText); return(ret.ResultCode); }); }); }
static ApiEndPoint getApiEndPoint(string controller, HttpConfiguration config) { string ctrl = controller; var apis = new ApiExplorer(config) .ApiDescriptions .Where(x => x.ActionDescriptor.ControllerDescriptor.ControllerName == ctrl).ToList(); List <ApiEndPointDetail> apiEndPointDetails = null; if (apis.ToList().Count > 0) { apiEndPointDetails = new List <ApiEndPointDetail>(); foreach (var api in apis) { apiEndPointDetails.Add(getApiEndPointDetail(api)); } } else { controller = string.Format("The {0} api does not exist.", controller); } return(new ApiEndPoint(controller, apiEndPointDetails)); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object" /> class. /// </summary> public VersionedApiExplorer(HttpConfiguration configuration) { this._configuration = configuration; this._defaultApiExplorer = new ApiExplorer(this._configuration); this._apiDescriptions = new Lazy <Collection <ApiDescription> >(() => this._defaultApiExplorer.ApiDescriptions); }
private async Task <bool> ExecuteOrChoose(Message message, TelegramBotClient botClient) { var endCommand = false; var cmdArgs = ParserExtensions.Parse(new Parser(), _messageText).Tokens.Select(a => a.Value).ToList(); if (cmdArgs.Count == 0) { //request resource _typeRequest = TypeRequest.Resource; await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, DEFAULT_MSG); } else { var resource = cmdArgs[0]; if (!resource.StartsWith("/")) { resource = "/" + resource; } var requestArgs = StringHelper.GetArgumentTags(resource); var parameters = cmdArgs.Skip(1).ToArray(); var parametersArgs = parameters.SelectMany(a => StringHelper.GetArgumentTags(a)).ToList(); if (requestArgs.Count() > 0) { //fix request resource = resource.Substring(0, resource.IndexOf(StringHelper.CreateArgumentTag(requestArgs[0])) - 1); var pveClient = PveHelper.GetClient(); var(Values, Error) = ApiExplorer.ListValues(pveClient, PveHelper.GetClassApiRoot(pveClient), resource); if (!string.IsNullOrWhiteSpace(Error)) { //return error await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, Error); endCommand = true; } else { _typeRequest = TypeRequest.ArgResource; await botClient.ChooseInlineKeyboard(message.Chat.Id, $"Choose {requestArgs[0]}", Values.Select(a => ("", a.Value, a.Value))); } } else if (parametersArgs.Count() > 0) { //request parameter value _typeRequest = TypeRequest.ArgParameter; await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, $"Insert value for parmater <b>{parametersArgs[0]}</b>"); } else if (requestArgs.Count() == 0) { var pveClient = PveHelper.GetClient(); //execute request var(ResultCode, ResultText) = ApiExplorer.Execute(pveClient, PveHelper.GetClassApiRoot(pveClient), resource, MethodType, ApiExplorer.CreateParameterResource(parameters), false, ApiExplorer.OutputType.Html); if (ResultCode != 200) { await botClient.SendTextMessageAsync(message.Chat.Id, $"Error: {ResultText}"); } else { var filename = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(resource).Replace("/", ""); await botClient.SendDocumentAsyncFromText(message.Chat.Id, ResultText, $"{filename}.html"); } endCommand = true; } } if (endCommand) { _messageText = ""; } return(await Task.FromResult(endCommand)); }
public InvoiceImporter(ApiExplorer idokladClient, IInvoiceParser invoiceParser) { _idokladClient = idokladClient; _invoiceParser = invoiceParser; }
public VersionedApiExplorer(HttpConfiguration configuration) { this.configuration = configuration; this.apiDescription = new Lazy <Collection <ApiDescription> >(InitializeApiDescriptions); this.DefaultExplorer = new ApiExplorer(configuration); }