Ejemplo n.º 1
0
 public IEnumerable <InvalidMember> Validate(ResourceSync entity, RESTableContext context)
 {
     context.Services.GetRequiredService <OperationsTestsFlags>().ValidatorWasCalled = true;
     if (entity.Id == 99)
     {
         yield return(this.Invalidate(p => p.Id, "Cannot be 99"));
     }
 }
Ejemplo n.º 2
0
 internal HttpRequest(ITraceable trace, HeaderRequestParameters parameters, Func <Stream, Task> writeBody)
 {
     Context   = trace.Context;
     URI       = parameters.URI;
     WriteBody = writeBody;
     Headers   = parameters.Headers;
     Method    = parameters.Method;
 }
Ejemplo n.º 3
0
        // METHOD URI
        public static void Main()
        {
            // Build services
            using var services = new ServiceCollection()
                                 .AddRESTable()
                                 .AddJsonProvider()
                                 .BuildServiceProvider();
            var configurator = services.GetRequiredService <RESTableConfigurator>();

            configurator.ConfigureRESTable();
            var rootClient = services.GetRequiredService <RootClient>();
            var context    = new RESTableContext(rootClient, services);

            // Welcome
            Console.WriteLine("App is running...");
            Console.WriteLine("Enter a request like so: <METHOD> <URI> [<BODY>], e.g. POST /person {'Name': 'Jane'}");

            // Handle input loop
            while (true)
            {
                // Handle input
                var input = Console.In.ReadLine()?.TrimStart();
                if (string.IsNullOrWhiteSpace(input))
                {
                    continue;
                }
                var args   = input.Split(new[] { ' ' }, 3);
                var method = (Method)Enum.Parse(typeof(Method), args[0], ignoreCase: true);
                var uri    = args[1];
                var body   = args.ElementAtOrDefault(2);

                // Make request
                var request = context.CreateRequest(method, uri, body);
                using var result           = request.GetResult().Result;
                using var serializedResult = result.Serialize().Result;

                // Write output
                Console.WriteLine($"=> {request.GetLogMessage().Result} {request.GetLogContent().Result}");
                Console.WriteLine($"<= {result.GetLogMessage().Result}");
                foreach (var(key, value) in result.Headers)
                {
                    Console.WriteLine($"{key}: {value}");
                }
                using var streamReader = new StreamReader(serializedResult.Body);
                var resultBody = streamReader.ReadToEnd();
                if (!string.IsNullOrWhiteSpace(resultBody))
                {
                    Console.WriteLine(resultBody);
                }
                Console.WriteLine("- - - - - - - - - - - - - - - - -");
            }
        }
Ejemplo n.º 4
0
        public RESTableFixture()
        {
            OperationsTestsFlags = new OperationsTestsFlags();
            ServiceProvider      = new ServiceCollection()
                                   .AddRESTable()
                                   .AddJsonProvider()
                                   .AddSingleton(OperationsTestsFlags)
                                   .BuildServiceProvider();
            Configurator = ServiceProvider
                           .GetRequiredService <RESTableConfigurator>();
            var client = ServiceProvider.GetRequiredService <RootClient>();

            Context = new RESTableContext(client, ServiceProvider);
            Configurator.ConfigureRESTable();
        }
Ejemplo n.º 5
0
        /// <inheritdoc />
        public bool TryAuthenticate(RESTableContext context, ref string uri, Headers headers, out Unauthorized error)
        {
            var accessRights = GetAccessRights(ref uri, headers);

            if (accessRights == null)
            {
                error = new Unauthorized();
                error.SetContext(context);
                if (headers?.Metadata == "full")
                {
                    error.Headers.Metadata = error.Metadata;
                }
                return(false);
            }
            context.Client.AccessRights = accessRights;
            error = null;
            return(true);
        }
Ejemplo n.º 6
0
        internal Terminal MakeTerminal(RESTableContext context, IEnumerable <Condition <T> > assignments = null)
        {
            var assignmentList = assignments?.ToList() ?? new List <Condition <T> >();

            var newTerminal = HasConstructorParameters
                ? InvokeParameterizedConstructor(assignmentList)
                : Constructor.Invoke(null) as Terminal;

            foreach (var assignment in assignmentList)
            {
                if (assignment.Operator != Operators.EQUALS)
                {
                    throw new BadConditionOperator(this, assignment.Operator);
                }
                if (!Members.TryGetValue(assignment.Key, out var property))
                {
                    if (newTerminal is IDictionary <string, object> dynTerminal)
                    {
                        dynTerminal[assignment.Key] = assignment.Value;
                    }
                    else
                    {
                        throw new UnknownProperty(Type, this, assignment.Key);
                    }
                }
                else
                {
                    property.SetValue(newTerminal, assignment.Value);
                }
            }
            if (newTerminal is T terminal and IValidator <T> validator)
            {
                var invalidMembers = validator.Validate(terminal, context).ToList();
                if (invalidMembers.Count > 0)
                {
                    var invalidEntity = new InvalidEntity(invalidMembers);
                    throw new InvalidInputEntity(invalidEntity);
                }
            }
            return(newTerminal);
        }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, RootClient rootClient)
        {
            app.UseMvcWithDefaultRoute();
            app.UseWebSockets();

            var rootContext       = new RESTableContext(rootClient, app.ApplicationServices);
            var personPostRequest = rootContext
                                    .CreateRequest <Person>(Method.POST)
                                    .WithBody(new object[]
            {
                new
                {
                    FirstName   = "Sarah",
                    LastName    = "Connor",
                    DateOfBirth = 19870304,
                    Interests   = new[] { "Survival" }
                },
                new
                {
                    FirstName   = "Jordan",
                    LastName    = "Belfort",
                    DateOfBirth = 19880119,
                    Interests   = new[] { "Money", "Drugs" }
                },
                new
                {
                    FirstName = "Darth",
                    LastName  = "Vader",
                    Interests = new[] { "Finding droids", "Darkness" }
                },
                new
                {
                    FirstName = "Luke",
                    LastName  = "Skywalker",
                    Interests = new[] { "Destiny", "Forces" }
                }
            });

            using var result = personPostRequest.GetResult().Result;
        }
Ejemplo n.º 8
0
        public async IAsyncEnumerable <TResource> Validate(IAsyncEnumerable <TResource> entities, RESTableContext context)
        {
            if (entities == null)
            {
                yield break;
            }
            if (Validator == null)
            {
                await foreach (var entity in entities.ConfigureAwait(false))
                {
                    yield return(entity);
                }
                yield break;
            }

            var index = -1L;

            await foreach (var entity in entities.ConfigureAwait(false))
            {
                index += 1;
                var invalidMembers = Validator(entity, context).ToList();
                if (invalidMembers.Count > 0)
                {
                    throw new InvalidInputEntity(new InvalidEntity(index, invalidMembers));
                }
                yield return(entity);
            }
        }
Ejemplo n.º 9
0
 public AwaitingWebSocket(IWebSocketInternal webSocket, Task waitTask)
 {
     WaitTask  = waitTask;
     WebSocket = webSocket;
     Context   = webSocket.Context;
 }
Ejemplo n.º 10
0
 internal static IAsyncEnumerable <T> Validate <T>(this IAsyncEnumerable <T> entities, IEntityResource <T> resource, RESTableContext context) where T : class
 {
     return(resource.Validate(entities, context));
 }
Ejemplo n.º 11
0
        /// <inheritdoc />
        public IUriComponents GetUriComponents(string uriString, RESTableContext context)
        {
            var uri   = new DefaultProtocolUriComponents(this);
            var match = Regex.Match(uriString, RegEx.RESTableRequestUri);

            if (!match.Success)
            {
                throw new InvalidSyntax(ErrorCodes.InvalidUriSyntax, "Check URI syntax");
            }
            var resourceOrMacro = match.Groups["res"].Value.TrimStart('/');
            var view            = match.Groups["view"].Value.TrimStart('-');
            var conditions      = match.Groups["cond"].Value.TrimStart('/');
            var metaConditions  = match.Groups["meta"].Value.TrimStart('/');

            switch (conditions)
            {
            case string { Length: 0 } :

            case "_": break;

            default:
            {
                foreach (var uriCondition in ParseUriConditions(conditions, true))
                {
                    uri.Conditions.Add(uriCondition);
                }
                break;
            }
            }

            switch (metaConditions)
            {
            case string { Length: 0 } :

            case "_": break;

            default:
            {
                foreach (var uriCondition in ParseUriConditions(metaConditions, true))
                {
                    uri.MetaConditions.Add(uriCondition);
                }
                break;
            }
            }

            if (view.Length != 0)
            {
                uri.ViewName = view;
            }

            switch (resourceOrMacro)
            {
            case "":
            case "_":
                uri.ResourceSpecifier = context.WebSocket?.Status == WebSocketStatus.Waiting
                        ? ResourceCollection.GetResourceSpecifier <Shell>()
                        : ResourceCollection.GetResourceSpecifier <AvailableResource>();
                break;

            case var resource when resourceOrMacro[0] != '$':
                uri.ResourceSpecifier = resource;
                break;

            case var _macro when _macro.Substring(1) is string _: throw new MacrosNotSupported();
            }

            return(uri);
        }
Ejemplo n.º 12
0
 public AspNetCoreWebSocket(HttpContext httpContext, string webSocketId, RESTableContext context, Client client)
     : base(webSocketId, context, client)
 {
     HttpContext = httpContext;
 }
Ejemplo n.º 13
0
 public RequestTestBase(RESTableFixture fixture)
 {
     Fixture = fixture;
     Context = fixture.Context;
 }
Ejemplo n.º 14
0
 public bool TryAuthenticate(RESTableContext context, ref string uri, Headers headers, out Unauthorized error)
 {
     context.Client.AccessRights = RootAccess;
     error = null;
     return(true);
 }