Exemplo n.º 1
0
        public Device Get(string id)
        {
            var deviceKey = PartionKeyRowKeyPair.CreateFromIdentity(id);

            var deviceRepository = new DeviceRepository(_tableEntityOperation);

            var deviceTableEntity = deviceRepository.Get(deviceKey);

            if (deviceTableEntity == null)
            {
                throw new NotFoundException();
            }

            return(new Device
            {
                Id = id,
                Name = deviceTableEntity.Name,
                Network = new Network()
                {
                    Id = deviceTableEntity.NetworkId
                },
                Service = new Service()
                {
                    Id = deviceTableEntity.ServiceId
                },
                Company = new Company()
                {
                    Id = deviceTableEntity.CompanyId
                },
                DeviceKey = deviceTableEntity.DeviceKey,
                NumericId = deviceTableEntity.NumericId
            });
        }
        public async Task <InvokeResult> AddDeviceAsync(DeviceRepository deviceRepo, Device device)
        {
            SetConnection(deviceRepo.DeviceStorageSettings.Uri, deviceRepo.DeviceStorageSettings.AccessKey, deviceRepo.DeviceStorageSettings.ResourceName);

            if (deviceRepo.RepositoryType.Value == RepositoryTypes.AzureIoTHub)
            {
                var iotHubDevice = new Microsoft.Azure.Devices.Device(device.DeviceId)
                {
                    Authentication = new Microsoft.Azure.Devices.AuthenticationMechanism()
                    {
                        Type         = Microsoft.Azure.Devices.AuthenticationType.Sas,
                        SymmetricKey = new Microsoft.Azure.Devices.SymmetricKey()
                        {
                            PrimaryKey   = device.PrimaryAccessKey,
                            SecondaryKey = device.SecondaryAccessKey,
                        }
                    }
                };

                var connString     = String.Format(AZURE_DEVICE_CLIENT_STR, deviceRepo.ResourceName, deviceRepo.AccessKeyName, deviceRepo.AccessKey);
                var regManager     = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(connString);
                var existingDevice = await regManager.GetDeviceAsync(device.DeviceId);

                if (existingDevice != null)
                {
                    return(InvokeResult.FromErrors(ErrorCodes.DeviceExistsInIoTHub.ToErrorMessage($"DeviceID={device.DeviceId}")));
                }
                await regManager.AddDeviceAsync(iotHubDevice);
            }
            await CreateDocumentAsync(device);

            return(InvokeResult.Success);
        }
Exemplo n.º 3
0
        public async Task <InvokeResult> DeleteDeviceAsync(DeviceRepository deviceRepo, string id, EntityHeader org, EntityHeader user)
        {
            if (deviceRepo.RepositoryType.Value == RepositoryTypes.AzureIoTHub)
            {
                var setRepoResult = await SetDeviceRepoAccessKeyAsync(deviceRepo, org, user);

                if (!setRepoResult.Successful)
                {
                    return(setRepoResult.ToInvokeResult());
                }
            }

            var device = await _deviceRepo.GetDeviceByIdAsync(deviceRepo, id);

            await AuthorizeAsync(device, AuthorizeActions.Delete, user, org);

            if (deviceRepo.RepositoryType.Value == RepositoryTypes.Local)
            {
                await _deviceConnectorService.DeleteDeviceAsync(deviceRepo.Instance.Id, id, org, user);

                return(InvokeResult.Success);
            }
            else
            {
                await _deviceRepo.DeleteDeviceAsync(deviceRepo, id);

                deviceRepo.AccessKey = null;

                return(InvokeResult.Success);
            }
        }
Exemplo n.º 4
0
        public WorkflowAction(string workflowId, JToken json)
        {
            _workflowId = workflowId;

            Fields = json.ToObject <Dictionary <string, dynamic> >();

            _workflowRules = new List <WorkflowActionRule>();
            if (Fields.GetValue <JArray>("rules") != null)
            {
                foreach (var j in Fields.GetValue <JArray>("rules"))
                {
                    _workflowRules.Add(new WorkflowActionRule(j));
                }
            }

            _devices = new List <IDevice>();
            if (Fields.GetValue <JArray>("devices") != null)
            {
                foreach (var j in Fields.GetValue <JArray>("devices"))
                {
                    var deviceId  = j["id"]?.ToString();
                    var deviceObj = DeviceRepository.Get(deviceId);

                    if (deviceObj == default(IDevice))
                    {
                        throw new Exception($"{FriendlyName} Could not find the workflow action device: '{deviceId}'");
                    }

                    _devices.Add(deviceObj);
                }
            }
        }
Exemplo n.º 5
0
        public async void Delete_Device_Deletes_Element()
        {
            builder.UseInMemoryDatabase("Delete_Device_Deletes_Element");
            var options = builder.Options;
            var device  = new Domain.Device();

            using (var context = new TestDbContext(options))
            {
                device = new Domain.Device()
                {
                    Id          = 1,
                    Vendor      = "V1",
                    Status      = true,
                    UId         = 1,
                    DateCreated = DateTime.Today
                };
                context.Devices.Add(device);
                context.SaveChanges();
                var repository = new DeviceRepository(context);
                await repository.Delete(device);

                device = context.Devices.Find(1);
            }

            Assert.True(device == null);
        }
Exemplo n.º 6
0
        public void PostConstructor(EDataFlow dataFlow)
        {
            var devices = EDataFlow.eRender.Equals(dataFlow) ? DeviceRepository.FindPlayBackDevices() : DeviceRepository.FindCaptureDevices();
            var cnt     = 0;

            foreach (var dev in devices)
            {
                var devID  = dev.MMDevice.ID;
                var lvitem = new ListViewItem {
                    Text = dev.MMDevice.FriendlyName, ImageIndex = cnt, Tag = devID
                };

                var devSettings = Program.settings.Device.Find(x => x.DeviceID == devID);
                if (devSettings != null)
                {
                    lvitem.Font = new Font(lvitem.Font, FontStyle.Bold);

                    if (devSettings.HideFromList)
                    {
                        lvitem.Font = new Font(lvitem.Font, FontStyle.Italic);
                    }
                }

                listDevices.LargeImageList.Images.Add(DeviceIcons.GetIcon(dev.MMDevice.IconPath));
                listDevices.Items.Add(lvitem);
                cnt++;
            }
        }
Exemplo n.º 7
0
        public static IActionResult V2Put(
            [HttpTrigger(AuthorizationLevel.Function, "put", Route = "v2/devices/{deviceId}")]
            DeviceModel input,
            ILogger log,
            string deviceId)
        {
            var device = new Device
            {
                DeviceId     = deviceId,
                CreationDate = input.CreationDate,
                Location     = input.Location,
                Department   = input.Department,
            };

            try
            {
                DeviceRepository
                .Get()
                .Update(deviceId, device);


                return(new AcceptedResult());
            }
            catch (DeviceNotFound)
            {
                return(new NotFoundResult());
            }
        }
Exemplo n.º 8
0
        public static IActionResult V2Post(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "v2/devices")]
            DeviceModel input,
            ILogger log)
        {
            var device = new Device
            {
                DeviceId     = input.DeviceId,
                CreationDate = input.CreationDate,
                Location     = input.Location,
                Department   = input.Department,
            };

            try
            {
                DeviceRepository
                .Get()
                .Create(device);

                return(new AcceptedResult());
            }
            catch (DuplicateDeviceException)
            {
                return(new BadRequestResult());
            }
        }
Exemplo n.º 9
0
        public static IActionResult V2Get(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "v2/devices/{deviceId}")]
            HttpRequest req,
            ILogger log,
            string deviceId)
        {
            var device = DeviceRepository
                         .Get()
                         .Get(deviceId);

            if (device == null)
            {
                return(new NotFoundResult());
            }

            var deviceModel = new DeviceModel
            {
                DeviceId     = device.DeviceId,
                CreationDate = device.CreationDate,
                Location     = device.Location,
                Department   = device.Department,
            };

            return(new OkObjectResult(deviceModel));
        }
Exemplo n.º 10
0
        public override void Process(HttpRequestArgs args)
        {
            HttpContext currentHttpContext = HttpContext.Current;

            if (currentHttpContext == null || Context.Database == null)
            {
                return;
            }

            if (Context.Site.Name.ToLower() != "website")
            {
                return;
            }

            DeviceType deviceType = DeviceRepository.RetrieveContext();

            switch (deviceType)
            {
            case DeviceType.Default:
                break;

            case DeviceType.Mobile:
                this.SetDevice("Mobile");
                break;

            case DeviceType.Tablet:
                this.SetDevice("Tablet");
                break;
            }
        }
Exemplo n.º 11
0
 public DevicesHub(ILogger <DevicesHub> logger, DeviceRepository deviceRepository, TemplateRepository templateRepository, MasterService masterService)
 {
     _logger             = logger;
     _deviceRepository   = deviceRepository;
     _templateRepository = templateRepository;
     _masterService      = masterService;
 }
        public void Add()
        {
            var repo   = new DeviceRepository();
            var device = DeviceFactory.CreateDevice("OldCamera", "old camera");

            Assert.Equal(device, repo.Add(device));
        }
        public async Task UpdateDeviceAsync(DeviceRepository deviceRepo, Device device)
        {
            SetConnection(deviceRepo.DeviceStorageSettings.Uri, deviceRepo.DeviceStorageSettings.AccessKey, deviceRepo.DeviceStorageSettings.ResourceName);

            await UpsertDocumentAsync(device);

            if (deviceRepo.RepositoryType.Value == RepositoryTypes.AzureIoTHub)
            {
                var connString   = String.Format(AZURE_DEVICE_CLIENT_STR, deviceRepo.ResourceName, deviceRepo.AccessKeyName, deviceRepo.AccessKey);
                var regManager   = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(connString);
                var iotHubDevice = await regManager.GetDeviceAsync(device.DeviceId);

                if (iotHubDevice.Authentication.Type != Microsoft.Azure.Devices.AuthenticationType.Sas)
                {
                    throw new InvalidOperationException("Currently only support Shared Access Key Authentication");
                }

                iotHubDevice.Authentication.SymmetricKey = new Microsoft.Azure.Devices.SymmetricKey()
                {
                    PrimaryKey   = device.PrimaryAccessKey,
                    SecondaryKey = device.SecondaryAccessKey,
                };

                await regManager.AddDeviceAsync(iotHubDevice);
            }
        }
        public async Task <InvokeResult <DeviceGroupEntry> > AddDeviceToGroupAsync(DeviceRepository deviceRepo, String deviceGroupId, String deviceUniqueId, EntityHeader org, EntityHeader user)
        {
            var group = await GetDeviceGroupAsync(deviceRepo, deviceGroupId, org, user);

            await AuthorizeAsync(group, AuthorizeResult.AuthorizeActions.Update, user, org, "Add Device to Device Group");

            var device = await GetDeviceManagementRepo(deviceRepo).GetDeviceByIdAsync(deviceRepo, deviceUniqueId);

            await AuthorizeAsync(device, AuthorizeResult.AuthorizeActions.Update, user, org, "Add Devvice to Device Group");

            //TODO: Add localization
            if (group.Devices.Where(grp => grp.DeviceUniqueId == deviceUniqueId).Any())
            {
                return(InvokeResult <DeviceGroupEntry> .FromError($"The device [{device.DeviceId}] already belongs to this device group and can not be added again."));
            }

            var entry = DeviceGroupEntry.FromDevice(device, user);

            group.Devices.Add(entry);

            device.DeviceGroups.Add(new EntityHeader()
            {
                Id = group.Id, Text = group.Name
            });

            await GetDeviceManagementRepo(deviceRepo).UpdateDeviceAsync(deviceRepo, device);
            await GetDeviceGroupRepo(deviceRepo).UpdateDeviceGroupAsync(deviceRepo, group);

            return(InvokeResult <DeviceGroupEntry> .Create(entry));
        }
Exemplo n.º 15
0
        public void Delete(string id)
        {
            var deviceKey = PartionKeyRowKeyPair.CreateFromIdentity(id);

            var deviceRepository  = new DeviceRepository(_tableEntityOperation);
            var networkRepository = new NetworkRepository(_tableEntityOperation);

            var deviceTableEntity = deviceRepository.Get(deviceKey);

            if (deviceTableEntity == null)
            {
                throw new NotFoundException();
            }

            var parentNetworkKey = PartionKeyRowKeyPair.CreateFromIdentity(deviceTableEntity.NetworkId);

            deviceRepository.Delete(deviceTableEntity);

            TransientErrorHandling.Run(() =>
            {
                var parentNetwork = networkRepository.Get(parentNetworkKey);
                for (var idx = 0; idx < parentNetwork.Devices.Count; idx++)
                {
                    if (parentNetwork.Devices[idx].Id == id)
                    {
                        parentNetwork.Devices.RemoveAt(idx);
                        break;
                    }
                }
                networkRepository.Update(parentNetwork);
            });
        }
Exemplo n.º 16
0
        public string Create(Device device)
        {
            var deviceIdentity = Identity.Next();

            var deviceKey = PartionKeyRowKeyPair.CreateFromIdentity(deviceIdentity);

            var deviceRepository  = new DeviceRepository(_tableEntityOperation);
            var networkRepository = new NetworkRepository(_tableEntityOperation);

            var deviceTableEntity = new DeviceTableEntity(deviceKey, device.Name, device.Network.Id, device.Service.Id,
                                                          device.Company.Id, device.DeviceKey, device.NumericId);

            deviceRepository.Create(deviceTableEntity);

            TransientErrorHandling.Run(() =>
            {
                var parentNetworkKey = PartionKeyRowKeyPair.CreateFromIdentity(device.Network.Id);

                var parentNetwork = networkRepository.Get(parentNetworkKey);
                parentNetwork.Devices.Add(new Small()
                {
                    Id = deviceIdentity, Name = device.Name
                });
                networkRepository.Update(parentNetwork);
            });

            return(deviceIdentity);
        }
Exemplo n.º 17
0
        public async Task <DeviceMedia> GetMediaItemAsync(DeviceRepository repo, string deviceId, string itemId)
        {
            SetConnection(repo.DeviceArchiveStorageSettings.AccountId, repo.DeviceArchiveStorageSettings.AccessKey);
            SetTableName(repo.GetDeviceMediaStorageName());

            return((await GetAsync(deviceId, itemId)).ToDeviceMedia());
        }
Exemplo n.º 18
0
 public ProjectController(UserManager <ApplicationUser> userManager, ProjectRepository projectRepository, AppDbContext context, DeviceRepository deviceRepository)
 {
     this.userManager   = userManager;
     _projectRepository = projectRepository;
     this.context       = context;
     _deviceRepository  = deviceRepository;
 }
Exemplo n.º 19
0
        public async Task <bool> InitDevice(Device newSlave)
        {
            if (newSlave != null)
            {
                var success = Devices.TryAdd(newSlave.MAC, new HouseSlaveDeviceClient {
                    Slave = newSlave, ConnectionId = Context.ConnectionId
                });
                if (success)
                {
                    _logger.Info($"Device with MAC: {newSlave.MAC}  has been added to current list");

                    var containsEntity =
                        await DeviceRepository.ContainsEntityWithMAC(newSlave.MAC, CancellationToken.None);

                    if (!containsEntity)
                    {
                        await DeviceRepository.Add(newSlave, Token);

                        _logger.Info($"Device with MAC: {newSlave.MAC} has been added to repository.");
                    }
                    else
                    {
                        await DeviceRepository.Update(newSlave, Token);

                        _logger.Info($"Device with MAC: {newSlave.MAC} has been updated.");
                    }
                }
            }

            return(false);
        }
Exemplo n.º 20
0
        public void GetPersonById()
        {
            // ARRANGE
            ApplicationConfiguration appApplicationConfiguration = new ApplicationConfiguration();
            PersonRepository         personRepository            = new PersonRepository(_session);
            DeviceRepository         deviceRepository            = new DeviceRepository(_session);
            SessionRepository        sessionRepository           = new SessionRepository(_session);
            ScheduledEmailRepository scheduledEmailRepository    = new ScheduledEmailRepository(_session);
            EmailNotificationService emailNotificationService    = new EmailNotificationService(appApplicationConfiguration);
            ScheduledEmailService    scheduledEmailService       = new ScheduledEmailService(scheduledEmailRepository, emailNotificationService, personRepository);
            PersonService            personService = new PersonService(personRepository, deviceRepository, sessionRepository, emailNotificationService, scheduledEmailService, appApplicationConfiguration, scheduledEmailRepository);

            SessionService   sessionService   = new SessionService(sessionRepository);
            PersonController personController = new PersonController(sessionService, personService)
            {
                Configuration = new HttpConfiguration(),
                Request       = new HttpRequestMessage()
            };

            personController.Request.Headers.Add("XClientId", Guid.NewGuid().ToString());
            personController.Request.RequestUri = new Uri("http://localhost?xerxes=1");             // Authentication shortcut

            // ACT
            var personModel = personController.GetPersonById(Convert.ToInt32(appApplicationConfiguration.GetSetting("personId")));

            // ASSERT
            Assert.IsNotNull(personModel);
        }
Exemplo n.º 21
0
        public void A_ChangedDevice_modifies_Existing_country_in_the_database()
        {
            var bootStrapper = new BootStrapper();
            bootStrapper.StartServices();
            var serviceEvents = bootStrapper.GetService<IServiceEvents>();
            //1.- Create message
            var aggr = GenerateRandomAggregate();

            //2.- Create the tuple in the database
            var repository = new DeviceRepository(_configuration.TestServer);
            repository.Insert(aggr);

            //3.- Change the aggregate
            aggr.DescriptionKeyId = StringExtension.RandomString(10);
            aggr.DeviceGroup.SapCode = StringExtension.RandomString(10);
            aggr.DeviceGroup.DeviceType.NameKeyId = StringExtension.RandomString(10);

            //4.- Emit message
            var message = GenerateMessage(aggr);
            message.MessageType = typeof(ChangedDevice).Name;
            serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message });

            //5.- Load the saved country
            var service = repository.Get(aggr.Id);
            //6.- Check equality
            Assert.True(ObjectExtension.AreEqual(aggr, service));
        }
Exemplo n.º 22
0
        public HttpResponseMessage Deletevalue(Device device)
        {
            string text       = "";
            string errMessage = "";

            try
            {
                string query = string.Format("DELETE from device WHERE id = '{0}'", device.id);
                DeviceRepository.ReadData(query);
            }
            //list_user.number = ds.Tables[0].Rows.Count;
            catch (Exception err)
            {
                errMessage = err.Message;
            }
            if (errMessage != "")
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, errMessage));
            }
            else
            {
                text = "Delete finish";
                return(Request.CreateResponse(HttpStatusCode.OK, text));
            }
        }
Exemplo n.º 23
0
        public HttpResponseMessage Postdevice(Device device)
        {
            //bool result = false;
            string text       = "";
            string errMessage = "";

            try
            {
                var query = string.Format("INSERT INTO device(id, room, status) VALUES ('{0}', '{1}', '{2}')",
                                          device.id, device.room, device.status); //SQL query language
                DeviceRepository.ReadData(query);
            }
            catch (Exception err)
            {
                errMessage = err.Message;
            }
            if (errMessage != "")
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, errMessage));
            }
            else
            {
                text = "Save finish!";
                return(Request.CreateResponse(HttpStatusCode.OK, text));
            }
        }
Exemplo n.º 24
0
        public HttpResponseMessage Getdevice()
        {
            //bool result = false;
            string     errMessage  = "";
            ListDevice list_device = new ListDevice();
            string     SQL         = "SELECT id,room,status from device";
            DataSet    ds          = DeviceRepository.ReadData(SQL);

            //list_device.number = ds.Tables[0].Rows.Count;
            if (ds.Tables[0].Rows.Count > 0)
            {
                //list_user.number = ds.Tables[0].Rows.Count;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    Device item = new Device()
                    {
                        id     = dr["id"].ToString(),
                        room   = dr["room"].ToString(),
                        status = dr["status"].ToString(),
                    };

                    list_device.devices.Add(item);
                }
            }
            if (errMessage != "")
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, errMessage));
            }
            else
            {
                //Console.WriteLine(HttpStatusCode.OK);
                //return Request.CreateResponse(HttpStatusCode.OK, result);
                return(Request.CreateResponse(HttpStatusCode.OK, list_device));
            }
        }
Exemplo n.º 25
0
        static AppActs.API.Service.Interface.IDeviceService setup()
        {
            MongoClient client   = new MongoClient(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
            string      database = ConfigurationManager.AppSettings["database"];

            AppActs.Repository.Interface.IApplicationRepository applicationRepository = new AppActs.Repository.ApplicationRepository(client, database);
            IDeviceRepository      deviceRepository   = new DeviceRepository(new DeviceMapper(client, database));
            IFeedbackRepository    feedbackRepository = new FeedbackRepository(new FeedbackMapper(client, database));
            IEventRepository       eventRep           = new EventRepository(new EventMapper(client, database));
            ICrashRepository       crashRep           = new CrashRepository(new CrashMapper(client, database));
            IAppUserRepository     appUserRep         = new AppUserRepository(new AppUserMapper(client, database));
            IErrorRepository       errorRep           = new ErrorRepository(new ErrorMapper(client, database));
            ISystemErrorRepository systemErrorRep     = new SystemErrorRepository(new SystemErrorMapper(client, database));

            return(new DeviceService
                   (
                       deviceRepository,
                       errorRep,
                       eventRep,
                       crashRep,
                       feedbackRepository,
                       systemErrorRep,
                       appUserRep,
                       applicationRepository,
                       new Model.Settings()
            {
                DataLoggingRecordRaw = true,
                DataLoggingRecordSystemErrors = true
            }
                   ));
        }
Exemplo n.º 26
0
        public HttpResponseMessage ControlDevice(int id, int status, Device device)
        {
            string text       = "";
            string errMessage = "";

            //Device device = new Device();

            try
            {
                string query = string.Format("UPDATE device set status = '{0}' WHERE id = '{1}' ", status, id);
                //query = query.Replace("@device_id", device.device_id);
                //query = query.Replace("@device_n", device.device_name);
                DeviceRepository.ReadData(query);
            }
            //list_device.number = ds.Tables[0].Rows.Count;
            catch (Exception err)
            {
                errMessage = err.Message;
            }


            if (errMessage != "")
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, errMessage));
            }

            else
            {
                text = "Update finish!";
                return(Request.CreateResponse(HttpStatusCode.OK, text));
            }
        }
Exemplo n.º 27
0
        public async Task DeviceRepository__GetDeviceByIdAsync__NotFound()
        {
            var options = GetDbContextOptions();

            // Arrange
            await using (var context = GetDdContext(options))
            {
                context.Designs.Add(new Design {
                    Id = 1, Name = "dname", Quantity = 11
                });
                context.Designs.Add(new Design {
                    Id = 2, Name = "dname2", Quantity = 22
                });
                context.Designs.Add(new Design {
                    Id = 3, Name = "dname3", Quantity = 33
                });
                context.Montages.Add(new Montage {
                    Id = 1, Name = "mname", Quantity = 10
                });
                context.Montages.Add(new Montage {
                    Id = 2, Name = "mname2", Quantity = 20
                });
                context.Montages.Add(new Montage {
                    Id = 3, Name = "mname3", Quantity = 30
                });
                context.Devices.Add(new Device {
                    Id = 1, Name = "name", Quantity = 1
                });
                context.Devices.Add(new Device {
                    Id = 2, Name = "name2", Quantity = 2
                });
                context.DesignInDevices.Add(new DesignInDevice()
                {
                    DeviceId = 1, ComponentId = 1, Quantity = 5
                });
                context.DesignInDevices.Add(new DesignInDevice()
                {
                    DeviceId = 1, ComponentId = 2, Quantity = 10
                });
                context.MontageInDevices.Add(new MontageInDevice()
                {
                    DeviceId = 1, ComponentId = 1, Quantity = 15
                });
                context.MontageInDevices.Add(new MontageInDevice()
                {
                    DeviceId = 1, ComponentId = 2, Quantity = 20
                });
                await context.SaveChangesAsync();
            }

            await using (var context = GetDdContext(options))
            {
                // Act
                var repository = new DeviceRepository(context);
                var result     = await repository.GetByIdAsync(5);

                // Assert
                Assert.Null(result);
            }
        }
Exemplo n.º 28
0
        public MasterServiceTests()
        {
            MqttConfiguration = new MqttConfiguration()
            {
                Host     = "192.168.66.200",
                Port     = 64220,
                Username = "******",
                Password = "******"
            };

            var configuration = new TasmotaConfiguration()
            {
                Subnet = IPAddress.Parse("192.168.66.0"),
            };

            Network = new MockNetwork(configuration.Subnet, 30, MqttConfiguration);

            var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            var tasmotaClient = new MockTasmotaClient(Network);
            var mongoClient   = new MongoClient("mongodb://localhost");

            Database         = mongoClient.GetDatabase("tasmocc-test");
            DeviceRepository = new DeviceRepository(Database);
            var deviceConfigurationRepository = new DeviceConfigurationRepository(Database);

            TasmotaService = new TasmotaService(Options.Create(configuration), loggerFactory.CreateLogger <TasmotaService>(), tasmotaClient);
            MasterService  = new MasterService(Options.Create(MqttConfiguration), loggerFactory.CreateLogger <MasterService>(), TasmotaService, DeviceRepository, deviceConfigurationRepository)
            {
                ScanNetworkOnStart = false
            };
        }
Exemplo n.º 29
0
        public async Task DeviceRepository__DeleteDevice__WithoutComponents()
        {
            var options = GetDbContextOptions();

            // Arrange
            await using (var context = GetDdContext(options))
            {
                context.Devices.Add(new Device {
                    Id = 1, Name = "name", Quantity = 10
                });
                await context.SaveChangesAsync();
            }

            // Act
            await using (var context = GetDdContext(options))
            {
                var repository = new DeviceRepository(context);
                repository.Delete(new Device {
                    Id = 1
                });
                await repository.SaveAsync();

                var montage = await context.Devices.FirstOrDefaultAsync();

                // Assert
                Assert.Null(montage);
            }
        }
Exemplo n.º 30
0
        public async Task DeviceRepository__UpdateDevice__WithoutComponents()
        {
            var options = GetDbContextOptions();

            // Arrange
            await using (var context = GetDdContext(options))
            {
                context.Devices.Add(new Device {
                    Id = 1, Name = "name", Quantity = 10
                });
                await context.SaveChangesAsync();
            }

            // Act
            await using (var context = GetDdContext(options))
            {
                var repository = new DeviceRepository(context);
                repository.UpdateAsync(new Device {
                    Id = 1, Name = "name123", Quantity = 15, Description = "nominal"
                });
                await repository.SaveAsync();

                var montage = await context.Devices.FirstOrDefaultAsync();

                // Assert
                Assert.NotNull(montage);
                Assert.AreEqual(1, montage.Id);
                Assert.AreEqual("name123", montage.Name);
                Assert.AreEqual(15, montage.Quantity);
                Assert.AreEqual("nominal", montage.Description);
            }
        }
Exemplo n.º 31
0
        public async Task <DeviceRepository> AddTrialRepository(string name, string key, Subscription subscription, EntityHeader org, EntityHeader user, DateTime createTimestamp)
        {
            await _storageUtils.DeleteIfExistsAsync <DeviceRepository>(key, org);

            var repo = new DeviceRepository()
            {
                Key             = key,
                Name            = name,
                Description     = "Trial Device Repository that you can use with up to 25 devices.  Contact Software Logistics if you need additional devices",
                RepositoryType  = EntityHeader <RepositoryTypes> .Create(RepositoryTypes.NuvIoT),
                DeviceCapacity  = EntityHeader.Create("trialdevices", "25 Device Trial"),
                StorageCapacity = EntityHeader.Create("trialstorage", "200mb Trial Storage"),
                Subscription    = EntityHeader.Create(subscription.Id.ToString(), subscription.Name),
            };

            AddId(repo);
            AddOwnedProperties(repo, org);
            AddAuditProperties(repo, createTimestamp, org, user);

            await this._deviceRepoMgr.AddDeviceRepositoryAsync(repo, org, user);

            /* when it gets created all the "stuff" to access the repo won't be present, load it to get those values. */
            repo = await this._deviceRepoMgr.GetDeviceRepositoryWithSecretsAsync(repo.Id, org, user);

            return(repo);
        }
Exemplo n.º 32
0
 public UnitOfWork()
 {
     _context = new FxContext();
     Devices = new DeviceRepository(_context);
     Suppliers = new SupplierRepository(_context);
     Categories = new CategoryRepository(_context);
     PointNames = new PointNameRepository(_context);
     Sockets = new SocketRepository(_context);
     ProductTypes = new ProductTypeRepository(_context);
     IncludedProducts = new IncludedProductRepository(_context);
     SignalTypes = new SignalTypeRepository(_context);
     CableTypes = new CableTypeRepository(_context);
 }
Exemplo n.º 33
0
 public UnitOfWork(FxContext context)
 {
     _context = context;
     // client of unitOfWork uses same context on all properties
     Devices = new DeviceRepository(_context);
     Suppliers = new SupplierRepository(_context);
     Categories = new CategoryRepository(_context);
     PointNames = new PointNameRepository(_context);
     Sockets = new SocketRepository(_context);
     ProductTypes = new ProductTypeRepository(_context);
     IncludedProducts = new IncludedProductRepository(_context);
     SignalTypes = new SignalTypeRepository(_context);
     CableTypes = new CableTypeRepository(_context);
 }
Exemplo n.º 34
0
 public void A_RegisteredDevice_creates_a_new_currency_in_the_database()
 {
     var bootStrapper = new BootStrapper();
     bootStrapper.StartServices();
     var serviceEvents = bootStrapper.GetService<IServiceEvents>();
     //1.- Create message
     var aggr = GenerateRandomAggregate();
     var message = GenerateMessage(aggr);
     //2.- Emit message
     serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message });
     //3.- Load the saved country
     var repository = new DeviceRepository(_configuration.TestServer);
     var service = repository.Get(aggr.Id);
     //4.- Check equality
     Assert.True(ObjectExtension.AreEqual(aggr, service));
 }
Exemplo n.º 35
0
        public void A_UnregisteredDevice_removes_Existing_device_in_the_database()
        {
            var bootStrapper = new BootStrapper();
            bootStrapper.StartServices();
            var serviceEvents = bootStrapper.GetService<IServiceEvents>();
            //1.- Create message
            var aggr = GenerateRandomAggregate();

            //2.- Create the tuple in the database
            var repository = new DeviceRepository(_configuration.TestServer);
            repository.Insert(aggr);

            //2.- Emit message
            var message = GenerateMessage(aggr);
            message.MessageType = typeof(UnregisteredDevice).Name;
            serviceEvents.AddIncommingEvent(new IncommingEvent { @event = message });

            var service = repository.Get(aggr.Id);
            Assert.Null(service);
        }
        public void LoadFail()
        {
            IDeviceRepository iDeviceRepository = new DeviceRepository(this.connectionString);

            Assert.IsNull(iDeviceRepository.Find(Guid.NewGuid()));
        }
        public void Load()
        {
            IDeviceRepository iDeviceRepository = new DeviceRepository(this.connectionString);

            Assert.IsNotNull(iDeviceRepository.Find(this.Device.Guid));
        }
Exemplo n.º 38
0
        public DeviceController()
        {
            var userName = User?.Identity?.GetUserName() ?? "Anonymous";

            _deviceRepository = new DeviceRepository(userName);
        }