示例#1
0
        /// <inheritdoc />
        public async Task <Guid> Create(CreateDeviceRequest request, string token)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentNullException(nameof(token));
            }

            var devices = await _deviceRepository.GetAsync();

            if (devices.Any(x => x.Udid == request.Udid))
            {
                throw new ApplicationException($"Device with udid: {request.Udid} already exist");
            }

            var scopeArray       = new [] { Const.Permissions.Device.AdminCreate };
            var correctCompanyId = await _validationHelper.GetCompanyIdByPermission(token, scopeArray, request.CompanyId);

            if (!correctCompanyId.HasValue)
            {
                throw new ArgumentException("Invalid companyId", nameof(request.CompanyId));
            }
            request.CompanyId = correctCompanyId.Value;

            await _validationHelper.ValidateCompanyAndBranch(request.CompanyId, request.BranchId, token);

            var device = request.Adapt <Device>();

            device.CreatedOn = DateTime.UtcNow;
            return(await _deviceRepository.AddAsync(device));
        }
示例#2
0
 /// <summary>
 /// Function to add a Device.
 /// </summary>
 /// <param name="d">Device view model</param>
 /// <returns>The created device</returns>
 public async Task <Device> AddAsync(DeviceViewModel d)
 {
     if (NameExists(d.Name))
     {
         throw new Exception("Device with the name \"" + d.Name + "\" already exists. Please choose a different name.");
     }
     return(await _repo.AddAsync(new Device { Name = d.Name, Active = d.Active }));
 }
示例#3
0
        public async Task <ActionResult <NormalResponse> > DeviceId([FromBody] DeviceIdRequest request)
        {
            await _deviceRepository.AddAsync(new DomainLayer.Entities.Device
            {
                DeviceId = request.DeviceId,
                Type     = (DomainLayer.Entities.DeviceType)request.DeviceType
            });

            return(Ok());
        }
示例#4
0
        public async Task <IActionResult> Create([Bind("Name")] Device device)
        {
            if (!ModelState.IsValid)
            {
                return(View(device));
            }
            await _repository.AddAsync(device, await GetCurrentUserAsync());

            return(RedirectToAction(nameof(Index)));
        }
示例#5
0
        public async Task <IActionResult> Register(DeviceModel device)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            await _deviceRepository.AddAsync(new Device(device.Type));

            return(RedirectToAction(nameof(Index)));
        }
示例#6
0
 public async Task <IActionResult> PostDevice([FromBody] Device device)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     if (await _repository.AddAsync(device, await GetCurrentUserAsync()))
     {
         return(CreatedAtAction("GetDevice", new { id = device.Id }, device));
     }
     return(InternalServerError());
 }
示例#7
0
        public async Task <DeviceResponse> SaveAsync(Device device)
        {
            try
            {
                await _deviceRepository.AddAsync(device);

                await _unitOfWork.CompleteAsync();

                return(new DeviceResponse(device));
            }
            catch (Exception e)
            {
                return(new DeviceResponse($"An error occurred when saving the access: {e.Message}"));
            }
        }
示例#8
0
        public async Task <bool> Handle(AddNewDeviceCommand request, CancellationToken cancellationToken = default)
        {
            var device = await _deviceRepository.GetAsync(request.DeviceId.ToString());

            if (device == null)
            {
                device = new Device(request.DeviceId, request.DeviceUserAgent, request.UsedBy);
                await _deviceRepository.AddAsync(device);
            }
            else
            {
                device.Reregister(request.UsedBy);
            }

            await _deviceRepository.UnitOfWork.SaveEntitiesAsync();

            return(true);
        }
示例#9
0
        public async Task <AccessResponse> FisrtReadAsync(Device device)
        {
            try
            {
                CultureInfo  ci         = new CultureInfo("en-US");
                TimeZoneInfo hrBrasilia = TZConvert.GetTimeZoneInfo("E. South America Standard Time");
                Device       deviceOut  = new Device();
                device = await _deviceRepository.AddAsync(device);

                foreach (Access accessIn in await _accessRepository.ListAsync())
                {
                    string firstKey  = accessIn.Device.FirstBlock + "" + accessIn.Device.SecondBlock + "" + accessIn.Device.ThirdBlock + "" + accessIn.Device.FourthBlock;
                    string secondKey = device.FirstBlock + "" + device.SecondBlock + "" + device.ThirdBlock + "" + device.FourthBlock;
                    if (firstKey == secondKey)
                    {
                        deviceOut = accessIn.Device;
                    }
                }

                Access    access    = new Access();
                AccessLog accessLog = new AccessLog();
                if (deviceOut.Code != 0)
                {
                    return(new AccessResponse($"Device {deviceOut.Code} already exists."));
                }
                else if (deviceOut.Code == 0)
                {
                    access = new Access {
                        Entry = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, hrBrasilia).ToString(), Exit = "Waiting", CodeDevice = device.Code, Device = device, CodeControl = 1
                    };
                    await _accessRepository.AddAsync(access);

                    await _unitOfWork.CompleteAsync();
                }
                access.AccessLogs = await _accessLogRepository.ListByAccessCodeAsync(access.Code);

                return(new AccessResponse(access));
            }
            catch (Exception e)
            {
                return(new AccessResponse($"An error occurred when saving the access: {e.Message}"));
            }
        }
示例#10
0
        private async Task <UserDevice> UpdateUserDevice(ArmUser user, string deviceName)
        {
            var userDevice = user.Devices.SingleOrDefault(x => x.Name == deviceName);

            if (userDevice == null)
            {
                userDevice = UserDevice.Create(Guid.NewGuid(), deviceName, DateTime.Now, user.Id, GenerateRefreshToken(), DateTime.Now, DateTime.Now.AddMinutes(_options.RefreshTokenLifetimeMinutes));
                await _deviceRepository.AddAsync(userDevice);
            }
            else
            {
                userDevice.Token           = GenerateRefreshToken();
                userDevice.TokenCreateDate = DateTime.Now;
                userDevice.TokenExpireDate = DateTime.Now.AddMinutes(_options.RefreshTokenLifetimeMinutes);
                await _deviceRepository.UpdateAsync(userDevice);
            }

            return(userDevice);
        }
示例#11
0
        public async Task <IActionResult> Register(Device device)
        {
            device.LastOnline = DateTime.Now;

            var currentDevice = await _deviceRepository.GetAsync(x => x.MacAddress == device.MacAddress);

            var currentGame = await _attemptRepository.GetLastAsync();

            var responseDto = new RegisterDeviceResponseDto(device);

            if (currentGame != null && currentDevice != null)
            {
                // Fetch status (started, finished) for this device in the current game
                var attemptDevice = await _attemptDeviceRepository.GetAsync(x =>
                                                                            x.DeviceId == currentDevice.Id && x.AttemptId == currentGame.Id);

                // If it found an attempt device, overwrite the started and finished bool
                if (attemptDevice != null)
                {
                    responseDto.Finished = attemptDevice.FinishedAt != null;
                    responseDto.Started  = attemptDevice.StartedAt != null;
                }
            }

            // Found a matching device, update it
            if (currentDevice != null && currentDevice.Id != 0)
            {
                currentDevice.LastOnline = DateTime.Now;
                currentDevice.Category   = device.Category;
                currentDevice.Name       = device.Name;
                responseDto.Device       = currentDevice;
                await _deviceRepository.UpdateAsync(currentDevice);

                return(Ok(JsonHelper.FixCycle(responseDto)));
            }

            // No device found with this MAC address, make it
            await _deviceRepository.AddAsync(device);

            return(Ok(JsonHelper.FixCycle(responseDto)));
        }
示例#12
0
        public async Task <DeviceResponse> SaveAsync(Device device)
        {
            try
            {
                Device deviceObj = await _deviceRepository.FindByPortAsync(device.Port);

                if (deviceObj != null)
                {
                    return(new DeviceResponse($"Device by port { device.Port } already exist"));
                }

                await _deviceRepository.AddAsync(device);

                await _unitOfWork.CompleteAsync();

                return(new DeviceResponse(device));
            }
            catch (Exception e)
            {
                return(new DeviceResponse($"An error occurred when saving the device: {e.Message}"));
            }
        }
示例#13
0
        public async Task SeedAsync()
        {
            Logger.Info("Initializing data...");
            var tasks = new List <Task>();

            tasks.Add(_userService.RegisterAsync(Guid.NewGuid(), "*****@*****.**", "lukasz", "test", "admin"));
            tasks.Add(_userService.RegisterAsync(Guid.NewGuid(), "*****@*****.**", "marek", "test", "serviceman"));
            tasks.Add(_userService.RegisterAsync(Guid.NewGuid(), "*****@*****.**", "pawel", "test", "servicecoordinator"));
            Logger.Info("Created users: admin, serviceman, servicecoordinator");

            List <Device> devices = new List <Device>()
            {
                new Device(Guid.NewGuid(), "ab12", DateTime.Now, DateTime.Now,
                           new Shop(Guid.NewGuid(), "Toruñ Kwiatowa 18/4",
                                    new Person("£ukasz", "Zieliñski", "*****@*****.**", "530230655"),
                                    "001", "520640330")),
                new Device(Guid.NewGuid(), "bc34", DateTime.Now, DateTime.Now.AddDays(-1),
                           new Shop(Guid.NewGuid(), "Bydgoszcz Polna 22/4",
                                    new Person("Marek", "Kowalski", "*****@*****.**", "540270695"),
                                    "002", "524740360")),
                new Device(Guid.NewGuid(), "b69", DateTime.Now.AddDays(-1), DateTime.Now,
                           new Shop(Guid.NewGuid(), "Warszwa Jana III Sobieskiego 12/3",
                                    new Person("Pawe³", "Wiœniewski", "*****@*****.**", "560260895"),
                                    "003", "524745360"))
            };

            List <ServiceOrder> serviceOrders = new List <ServiceOrder>()
            {
                new ServiceOrder(Guid.NewGuid(),
                                 new Person("£ukasz", "Zieliñski", "*****@*****.**", "530230655"),
                                 new Person("Pawe³", "Wiœniewski", "*****@*****.**", "560360895")),
                new ServiceOrder(Guid.NewGuid(),
                                 new Person("£ukasz", "Zieliñski", "*****@*****.**", "530230655"),
                                 new Person("Marek", "Kowalski", "*****@*****.**", "540270495")),
                new ServiceOrder(Guid.NewGuid(),
                                 new Person("£ukasz", "Zieliñski", "*****@*****.**", "53023655"),
                                 new Person("Marcin", "Wolski", "*****@*****.**", "560230895")),
                new ServiceOrder(Guid.NewGuid(),
                                 new Person("£ukasz", "Zieliñski", "*****@*****.**", "53023655")),
                new ServiceOrder(Guid.NewGuid(),
                                 new Person("£ukasz", "Zieliñski", "*****@*****.**", "53023655"))
            };

            serviceOrders[0].AddServiceOrderDescription("Naprawa Wilanoska 36", "Urz¹dznie mia³o problem z po³aczeniem internetowym. " +
                                                        "Problem ze statycznymi adresami IP zosta³ rozwi¹zany. Wina po stronie klinta.",
                                                        new Person("Pawe³", "Wiœniewski", "*****@*****.**", "560360895"), "true");
            serviceOrders[1].AddServiceOrderDescription("Brak danych", "Urz¹dznie nie wysy³a³o danych. " +
                                                        "Problem z niepoprawn¹ konfiguracj¹ urz¹dzenia. Wina po naszej stronie.",
                                                        new Person("Marek", "Kowalski", "*****@*****.**", "540270495"), "true");
            serviceOrders[2].AddServiceOrderDescription("Warszawa PL35", "Uszkodzona karta SD. " +
                                                        "Nowa karta zostanie wys³ana do klinta i zamontowana. Naprawa w raczej ramach gwarncji, " +
                                                        "aczkolwiek karta mog³abyæ naruszona przez klinta.",
                                                        new Person("Marek", "Kowalski", "*****@*****.**", "540270495"), "false");
            //serviceOrders[2].AddServiceOrderDescription("Warszawa PL35", "Uszkodzona karta SD. " +
            //    "Klient dosta³ i wymini³ kartê. Urzadzenie dzia³a poprawnie.",
            //    new Person("Marek", "Kowalski", "*****@*****.**", "540270495"),true);

            devices[0].AddServiceOrder(serviceOrders[0]);
            devices[1].AddServiceOrder(serviceOrders[1]);
            devices[2].AddServiceOrder(serviceOrders[2]);
            devices[2].AddServiceOrder(serviceOrders[2]);

            foreach (var serviceOrder in serviceOrders)
            {
                await _serviceOrderRepository.AddAsync(serviceOrder).ConfigureAwait(false);
            }

            foreach (var device in devices)
            {
                await _deviceRepository.AddAsync(device);
            }

            Logger.Info("Add serviceOrders with ServiceOrderDescriptions");

            foreach (var device in await _deviceRepository.GetAllAsync())
            {
                _shopRepository.AddAsync(device.Shop);
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Monday, "10:00", "18:00");
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Tuesday, "10:00", "18:00");
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Wednesday, "10:00", "18:00");
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Thursday, "10:00", "18:00");
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Friday, "10:00", "18:00");
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Saturday, "10:00", "18:00");
                _shopRepository.AddShopTime(device.Shop.Id, DayOfWeek.Saturday, "10:00", "18:00");
            }
            Logger.Info("Add shops and set shopTimes");

            await Task.WhenAll(tasks);

            Logger.Info("Data was initialized.");
        }
示例#14
0
        public async Task <BaseResponse> AddDeviceAsync(DeviceAddDto req, string account, string GroupId)
        {
            BaseResponse br = new BaseResponse();
            //查找是否存在相同的设备序号
            var device = _dr.Find(a => a.DeviceNo == req.DeviceNo);

            if (await device.FirstOrDefaultAsync() != null)
            {
                br.Success = false;
                br.Message = "该设备已存在,请确认";
                return(br);
            }
            //获取设备所属项目路径
            string pathId, PathName;

            if (req.ProjectId.HasValue && req.ProjectId.Value != 0)
            {
                var p = await _ps.GetProjectAsync(req.ProjectId.Value);

                if (p != null)
                {
                    //设备增加所属场站编号和名称
                    pathId   = $"{p.PathId}/{p.Id}";
                    PathName = $"{p.PathName}/{p.Name}";
                }
                else
                {
                    br.Success = false;
                    br.Message = "输入的场站不存在";
                    return(br);
                }
            }
            else
            {
                pathId   = null;
                PathName = null;
            }

            try
            {
                var entity = _mapper.Map <DeviceModel>(req);
                entity.DeviceSn = Guid.NewGuid().ToString("N");
                entity.Create   = account;
                entity.FullId   = pathId;
                entity.FullName = PathName;
                entity.GroupId  = GroupId;
                //获取类型硬件配置数据
                var data = await _th.GetTypeHardwareConfigAsync(req.TypeId);

                var dtos = _mapper.Map <List <TypeHardwareConfigModel>, List <DeviceHardwareConfigModel> >(data);
                foreach (var item in dtos)
                {
                    item.Device = entity;
                    item.Create = account;
                }
                await _dr.AddAsync(entity, dtos);

                br = new BResponse <string> {
                    Data = entity.DeviceSn, Success = true, Message = "添加设备成功"
                };
                _log.LogInformation($"{account}删除类型标示为{entity.DeviceSn}的设备数据成功");
            }
            catch (Exception ex)
            {
                _log.LogError($"{account}添加设备失败,失败原因:{ex.Message}->{ex.StackTrace}->{ex.InnerException}");
                br.Success = false;
                br.Message = "添加设备失败,请联系管理员";
            }
            return(br);
        }