Beispiel #1
0
        protected override IResult Run(string commandString,
                                       TypedResult <Dictionary <Device, ICollection <DeviceProperty> > > previousResult)
        {
            if (previousResult.TypedData == null)
            {
                return(previousResult);
            }
            else
            {
                var matched = new Dictionary <Device, ICollection <DeviceProperty> >();
                var values  = new List <String>();
                var cbuf    = previousResult.CommandBuffer;

                foreach (var dmap in previousResult.TypedData)
                {
                    var device = dmap.Key;
                    foreach (var prop in dmap.Value)
                    {
                        //actions
                        if (prop.MutatorTags.Any(tag => cbuf.Contains((string)tag)))
                        {
                            if (!matched.ContainsKey(device))
                            {
                                matched[device] = new HashSet <DeviceProperty>();
                            }
                            matched[device].Add(prop);

                            //values
                            if (prop.IsContinuous)
                            {
                            }
                            else if (prop.IsDiscrete)
                            {
                                prop.Metadata.DiscreteValues.ToList().ForEach(v =>
                                {
                                    if (cbuf.Contains(v.Value))
                                    {
                                        values.Add(v.Value);
                                        prop.Value = v.Value;
                                    }
                                });
                            }
                        }
                    }
                }

                IEnumerable <string> tags = matched.Values.SelectMany(dev => dev.Select(t => t.IdTags)
                                                                      .SelectMany(ts => ts.Select(t => t.Name)))
                                            .OrderByDescending(st => st.Length);
                tags.ToList().ForEach(p => cbuf = cbuf.Replace(p, ""));
                values.ForEach(p => cbuf        = cbuf.Replace(p, ""));

                return(new TypedResult <Dictionary <Device, ICollection <DeviceProperty> > >(matched, cbuf)
                {
                    Command = previousResult.Command
                });
            }
        }
        protected override IResult Run(string commandString, TypedResult <IEnumerable <Device> > previousResult)
        {
            if (previousResult.TypedData == null)
            {
                return(previousResult);
            }
            else
            {
                var matched = new Dictionary <Device, ICollection <DeviceProperty> >();
                var cbuf    = previousResult.CommandBuffer;
                foreach (var device in previousResult.TypedData)
                {
                    var property = device.Properties.FirstOrDefault(x => x.IsInCommand(commandString));

                    if (property != null)
                    {
                        var value = property.DetermineValue(commandString);
                        if (value == null)
                        {
                            throw new ApplicationException("value type not decernible");
                        }
                        previousResult.Command.DeviceID = device.Id;

                        previousResult.Command.Properties = new Core.Message.CommandProperty[] {
                            new Core.Message.CommandProperty()
                            {
                                Name  = property.Name,
                                Value = value
                            }
                        };
                    }
                    //foreach(var prop in device.Properties)
                    //{
                    //    //ids
                    //    if (prop.IdTags.Any(tag => cbuf.Contains((string)tag)))
                    //    {
                    //        if (!matched.ContainsKey(device)) matched[device] = new HashSet<DeviceProperty>();
                    //        matched[device].Add(prop);
                    //    }
                    //}
                }

                return(previousResult);

                //IEnumerable<string> tags = matched.Values.SelectMany(dev => dev.Select(t => t.IdTags)
                //                                         .SelectMany(ts => ts.Select(t => t.Name)))
                //                                         .OrderByDescending(st => st.Length);
                //tags.ToList().ForEach(p => cbuf = cbuf.Replace(p, ""));

                //return new TypedResult<Dictionary<Device, ICollection<DeviceProperty>>>(matched, cbuf)
                //{
                //    Command = previousResult.Command
                //};
            }
        }
Beispiel #3
0
        public async Task <TypedResult <RegisterResponse> > RegisterAsync(RegisterRequest req, IEnumerable <string> roles)
        {
            var userExists = await userManager.FindByNameAsync(req.Username);

            if (userExists != null)
            {
                return(new TypedResult <RegisterResponse>(false, "User already exists!", null));
            }

            ApplicationUser user = new ApplicationUser()
            {
                Email         = req.Email,
                SecurityStamp = Guid.NewGuid().ToString(),
                UserName      = req.Username
            };
            var result = await userManager.CreateAsync(user, req.Password);

            if (!result.Succeeded)
            {
                return(new TypedResult <RegisterResponse>(false, "User creation failed! Please check user details and try again.", null));
            }

            if (roles != null)
            {
                foreach (string role in roles)
                {
                    await userManager.AddToRoleAsync(user, role);
                }
            }

            LoginRequest loginRequest = new LoginRequest()
            {
                Username = req.Username,
                Password = req.Password
            };
            TypedResult <LoginResponse> loginResponse = await LoginAsync(loginRequest);

            if (!loginResponse.Status)
            {
                return(new TypedResult <RegisterResponse>(false, loginResponse.Message, null));
            }
            return(new TypedResult <RegisterResponse>(new RegisterResponse()
            {
                Token = loginResponse.Data.Token, Expiration = loginResponse.Data.Expiration
            }));
        }
        protected override IResult Run(string commandString, TypedResult <IEnumerable <Device> > previousResult)
        {
            var devices = previousResult.TypedData;

            if (devices == null)
            {
                throw new NullReferenceException("no device list passed");
            }
            List <Device> discoverdDevices = new List <Device>();
            //have a list of tags that were found and later remove
            var discoveredTags = new List <string>();

            foreach (var d in devices)
            {
                //iterate through all the tags of a device
                foreach (var tag in d.IdTags)
                {
                    int idx = commandString.IndexOf(tag.Name, StringComparison.CurrentCultureIgnoreCase);
                    //if the tag exists then add that device to discovered devices and remove that tag in the command string
                    if (idx != -1)
                    {
                        discoveredTags.Add(tag.Name);
                        discoverdDevices.Add(d);
                        //commandString = commandString.Remove(idx, tag.Name.Length);
                        continue;
                    }
                }
            }
            if (discoveredTags.Count > 0)
            {
                //locate and remove from command starting with the longest tag
                foreach (var d in discoveredTags.OrderByDescending(x => x.Length))
                {
                    int idx = commandString.IndexOf(d);
                    if (idx != -1)
                    {
                        commandString = commandString.Remove(idx, d.Length);
                    }
                }
            }
            return(new TypedResult <IEnumerable <Device> >(discoverdDevices, commandString)
            {
                Command = previousResult.Command
            });
        }
        protected override IResult Run(string commandString, TypedResult <Dictionary <Device, ICollection <DeviceProperty> > > previousResult)
        {
            var dvs = previousResult.TypedData;

            if (dvs.Count != 1)
            {
                return(new TypedResult <object>(null));
            }
            else
            {
                previousResult.Command.DeviceID = dvs.First().Key.Id;
                //previousResult.Command.Properties = dvs.First().Value.Select(p => new CommandProperty { Name = p.Id, Value = p.Value }).ToArray();
                ///previousResult.Command.Action = (string)dvs.First().Value.First().MutatorTags.First();
                return(new TypedResult <object> {
                    Command = previousResult.Command
                });
            }
        }
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogger logger)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";
                    var contextFeature           = context.Features.Get <IExceptionHandlerFeature>();
                    if (contextFeature != null)
                    {
                        logger.LogError($"Something went wrong: {contextFeature.Error}");
                        Error err = new Error(contextFeature.Error.Message);
                        TypedResult <Error> errorBody = new TypedResult <Error>(false, "Internal Server Error.", err);

                        await context.Response.WriteAsync(errorBody.ToJsonString());
                    }
                });
            });
        }
Beispiel #7
0
 protected abstract IResult Run(string commandString, TypedResult <IResultDataType> previousResult);
        public async Task <int> Load_Valid(string sort, string order, string search, int limit, int offset, string extraParam)
        {
            if (_fixture.DOTNET_RUNNING_IN_CONTAINER)
            {
                return(0);                                                 //pass on fake DB with no data
            }
            // Arrange
            var query_input = new HashesDataTableLoadInput
            {
                Sort       = sort,
                Order      = order,
                Search     = search,
                Limit      = limit,
                Offset     = offset,
                ExtraParam = extraParam,
            }.ToDictionary();

            using (var content = new FormUrlEncodedContent(query_input))
            {
                var queryString = await content.ReadAsStringAsync();

                // Act
                using (HttpResponseMessage response = await _client.GetAsync($"{_fixture.AppRootPath}{VirtualScrollController.ASPX}/{nameof(HashesDataTableController.Load)}?{queryString}", HttpCompletionOption.ResponseContentRead))
                {
                    // Assert
                    Assert.NotNull(response);
                    response.EnsureSuccessStatusCode();
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                    var jsonString = await response.Content.ReadAsStringAsync();

                    var typed_result = new TypedResult
                    {
                        total = 1,
                        rows  = new ThinHashes[] { }
                    };

                    // Deserialize JSON String into concrete class
                    var data = JsonSerializer.Deserialize <TypedResult>(jsonString, new JsonSerializerOptions {
                        PropertyNameCaseInsensitive = true
                    });
                    Assert.IsType(typed_result.GetType(), data);
                    Assert.IsAssignableFrom <IEnumerable <ThinHashes> >(data.rows);

                    Assert.True(data.rows.Length == 5 || data.rows.Length == 0);
                    Assert.True(data.total >= 0);

                    if (data.rows.Length > 0)
                    {
                        Assert.StartsWith(search, data.rows[0].Key);

                        if (query_input.TryGetValue("ExtraParam", out string value) && value == "cached")
                        {
                            Assert.True(response.Headers.CacheControl.Public &&
                                        response.Headers.CacheControl.MaxAge == DotnetPlayground.Repositories.HashesRepository.HashesInfoExpirationInMinutes);
                        }
                        else
                        {
                            Assert.Null(response.Headers.CacheControl?.Public);
                        }
                    }
                    else
                    {
                        Assert.Null(response.Headers.CacheControl?.Public);
                    }

                    return(data.total);
                }
            }
        }