예제 #1
0
        public void GetSeleniumConfigById_Found_Android()
        {
            var device = new Device(_device1.Id, _device1.Name, true, DeviceType.Android, DeviceStatus.Online);

            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Find(device.Id))
            .Returns(device);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null, _externalProcesses);
            // Act
            var result = controller.GetSeleniumConfigById(device.Id);

            // Assert
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Contains(_device1.Id, viewResult.Value.ToString());
            Assert.Contains("platformName = android", viewResult.Value.ToString());
        }
        public async Task GetById_WithDeviceAvailable_ReturnsDevice()
        {
            //Arrange
            var dbContext         = DbContextMocker.GetDbContext(nameof(GetById_WithDeviceAvailable_ReturnsDevice));
            var devicesController = new DevicesController(dbContext);
            var expectedDevice    = new Device
            {
                Device_id = 1, Name = "testName1", Location = "testLocation1"
            };

            //Act
            var response = await devicesController.GetById(1);

            var result         = (ObjectResult)response.Result;
            var deviceReceived = result.Value.As <Device>();

            dbContext.Dispose();

            //Assert
            result.StatusCode.Should().Be((int)HttpStatusCode.OK);
            Assert.True(DevicesComparer.CompareDevices(deviceReceived, expectedDevice), "The device received is different " +
                        "than the expected.");
        }
예제 #3
0
        public void GetSeleniumConfigById_unsupportedDeviceType()
        {
            var device = new Device(_device1.Id, _device1.Name, true, (DeviceType)99, DeviceStatus.Online);

            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Find(device.Id))
            .Returns(device);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null,
                                                          _externalProcesses);
            // Act
            var result = controller.GetSeleniumConfigById(device.Id);

            // Assert
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Equal("Unsupported device type", viewResult.Value);
        }
예제 #4
0
        public void RestartDevice_DeviceNotAvailable()
        {
            var device = new Device(_device1.Id, _device1.Name, false, _device1.Type, DeviceStatus.Locked);

            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Find(device.Id))
            .Returns(device);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null,
                                                          _externalProcesses);
            // Act
            var result = controller.RestartDevice(device.Id);

            // Assert
            var viewResult = Assert.IsType <ObjectResult>(result);

            Assert.Equal(423, viewResult.StatusCode);
        }
예제 #5
0
        public void UpdateDevice_notFound()
        {
            // Arrange
            Device device = _device1;

            device.Name = "updated name";
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Find(_device1.Id))
            .Returns((Device)null);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null,
                                                          _externalProcesses);
            // Act

            var result = controller.Update(_device1.Id, device);

            // Assert
            Assert.IsType <NotFoundObjectResult>(result);
        }
예제 #6
0
        public void RemoveDevice()
        {
            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Add(_device1));
            mockRepository.Setup(repo => repo.Find(_device1.Id))
            .Returns(_device1);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null,
                                                          _externalProcesses);

            controller.Create(_device1);

            // Act
            var result = controller.Delete(_device1.Id);

            // Assert
            Assert.IsType <OkResult>(result);
        }
        public async Task AddADevice()
        {
            //Setting all
            var nameBD = Guid.NewGuid().ToString();

            var context = BuildContext(nameBD);

            context.Gateways.Add(new Gateway()
            {
                SerialNumber = "gw-001", Name = "Gateway 1", IpAddress = "10.0.0.1"
            });

            await context.SaveChangesAsync();

            var testContext = BuildContext(nameBD);

            //Tests
            var device = new Peripheral()
            {
                UID = 1, Vendor = "Device 1", Date = DateTime.Parse("2021-02-16T16:17:00"), Status = true
            };
            var controller = new DevicesController(testContext);

            var response = await controller.Post(device, "gw-001");

            //Verification
            var result = response.Result;

            Assert.IsNotNull(result);

            var countDevices = await testContext.Peripherals.CountAsync();

            Assert.AreEqual(1, countDevices);
            var countRelations = await testContext.PeripheralGateways.CountAsync();

            Assert.AreEqual(1, countRelations);
        }
예제 #8
0
        public async Task Should_Add_And_Remove_A_Device()
        {
            var consumerController = new ConsumersController(fixture.GetDataProvider());
            var consumer           = (await consumerController.AddConsumer(new ConsumerRequestAdd()
            {
                Email = "*****@*****.**"
            }) as OkObjectResult).Value as Consumer;

            var device = new DeviceRequestAdd()
            {
                Available    = true,
                Description  = "Description...",
                ProjectId    = "Project test",
                Regionid     = "europe-west1",
                RegisteredOn = System.DateTime.Now,
                RegistryId   = "my-registry",
                TenantId     = Guid.NewGuid().ToString(),
                ConsumerId   = consumer.ConsumerId.ToString()
            };
            //-------------------------------------------

            var controller = new DevicesController(fixture.GetDataProvider());
            var added      = await controller.AddDevice(device) as OkObjectResult;

            Assert.NotNull(added.Value);
            Assert.Equal(added.StatusCode, (int)HttpStatusCode.OK);

            var foundItem = (await controller.GetDevice((added.Value as Device).DeviceId.ToString()) as OkObjectResult).Value as Device;

            Assert.Equal(foundItem, added.Value);

            var deleteResult = await controller.RemoveDevice(foundItem.DeviceId.ToString());

            var foundItem2 = await controller.GetDevice((added.Value as Device).DeviceId.ToString()) as NotFoundObjectResult;

            Assert.Equal(foundItem2.StatusCode, (int)HttpStatusCode.NotFound);
        }
예제 #9
0
        public void GetAllDevices()
        {
            // Arrange
            var testDevices    = GetTestDevices();
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(mpr => mpr.GetAll()).Returns(testDevices);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null, _externalProcesses);

            // Act
            var result = controller.GetAll();

            // Assert
            var viewResult = Assert.IsType <List <Device> >(result);

            Assert.Equal(testDevices.Count(), result.Count());
            Assert.Contains(_device1, viewResult);
            Assert.Contains(_device2, viewResult);
            Assert.Contains(_device3, viewResult);
        }
예제 #10
0
        public void RestartDevice_RestartFailed()
        {
            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Find(_device1.Id))
            .Returns(_device1);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var mockDeviceUtils   = new Mock <IDeviceUtils>();

            mockDeviceUtils.Setup(x => x.RestartDevice(_device1)).Returns("ERROR");

            var controller = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                   mockDeviceUtils.Object, null, _externalProcesses);
            // Act
            var result = controller.RestartDevice(_device1.Id);

            // Assert
            var viewResult = Assert.IsType <ObjectResult>(result);

            Assert.Equal(500, viewResult.StatusCode);
        }
예제 #11
0
        public void GetAllPropertiesKeys()
        {
            var device           = new Device(_device1.Id, _device1.Name, true, _device1.Type, DeviceStatus.Online);
            var device2          = new Device(_device1.Id, _device1.Name, true, _device1.Type, DeviceStatus.Online);
            var deviceProperties = new List <DeviceProperties>
            {
                new DeviceProperties("key1", "value1"),
                new DeviceProperties("key2", "value2")
            };

            device.Properties  = deviceProperties;
            device2.Properties = deviceProperties;

            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.GetAll())
            .Returns(new List <Device> {
                device, device2
            });

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null,
                                                          _externalProcesses);
            // Act
            var result = controller.GetAllPropertiesKeys();

            // Assert
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Equal(new List <string> {
                "key1", "key2"
            }, viewResult.Value);
        }
예제 #12
0
        public void RemoveDevice_DeviceNotFound()
        {
            var device = new Device(_device1.Id, _device1.Name, false, _device1.Type, DeviceStatus.Locked);
            // Arrange
            var mockRepository = new Mock <IRepository <Device> >();

            mockRepository.Setup(repo => repo.Add(device));
            mockRepository.Setup(repo => repo.Find(device.Id))
            .Returns((Device)null);

            var mockLogger        = new Mock <IManagerLogger>();
            var mockConfiguration = new Mock <IManagerConfiguration>();
            var controller        = new DevicesController(mockRepository.Object, mockLogger.Object, mockConfiguration.Object,
                                                          null, null,
                                                          _externalProcesses);

            controller.Create(_device1);

            // Act
            var result = controller.Delete(device.Id);

            // Assert
            Assert.IsType <NotFoundObjectResult>(result);
        }
예제 #13
0
 public SmsViewModel()
 {
     _devicesController = DevicesController.getInstance();
 }
        public async Task AddADeviceToAFullGateway()
        {
            //Setting all
            var nameBD = Guid.NewGuid().ToString();

            var context = BuildContext(nameBD);

            context.Gateways.Add(new Gateway()
            {
                SerialNumber = "gw-001", Name = "Gateway 1", IpAddress = "10.0.0.1"
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 1, Vendor = "Device 1", Date = DateTime.Parse("2021-02-16T16:17:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 1
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 2, Vendor = "Device 2", Date = DateTime.Parse("2021-02-16T16:18:00"), Status = false
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 2
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 3, Vendor = "Device 3", Date = DateTime.Parse("2021-02-16T16:19:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 3
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 4, Vendor = "Device 4", Date = DateTime.Parse("2021-02-16T16:20:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 4
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 5, Vendor = "Device 5", Date = DateTime.Parse("2021-02-16T16:21:00"), Status = false
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 5
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 6, Vendor = "Device 6", Date = DateTime.Parse("2021-02-16T16:22:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 6
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 7, Vendor = "Device 7", Date = DateTime.Parse("2021-02-16T16:23:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 7
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 8, Vendor = "Device 8", Date = DateTime.Parse("2021-02-16T16:24:00"), Status = false
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 8
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 9, Vendor = "Device 9", Date = DateTime.Parse("2021-02-16T16:25:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 9
            });
            context.Peripherals.Add(new Peripheral()
            {
                UID = 10, Vendor = "Device 10", Date = DateTime.Parse("2021-02-16T16:26:00"), Status = true
            });
            context.PeripheralGateways.Add(new PeripheralsGateways()
            {
                GatewaySerialNumber = "gw-001", PeripheralId = 10
            });

            await context.SaveChangesAsync();

            var testContext = BuildContext(nameBD);

            //Tests
            var device = new Peripheral()
            {
                UID = 11, Vendor = "Device 11", Date = DateTime.Parse("2021-02-16T16:27:00"), Status = true
            };
            var controller = new DevicesController(testContext);

            var response = await controller.Post(device, "gw-001");

            //Verification
            var result = response.Result as BadRequestObjectResult;

            //Bad Request Http Status Code
            Assert.AreEqual(400, result.StatusCode);

            var countDevices = await testContext.Peripherals.CountAsync();

            Assert.AreEqual(10, countDevices);
            var countRelations = await testContext.PeripheralGateways.CountAsync();

            Assert.AreEqual(10, countRelations);
        }
예제 #15
0
 public CommunicationViewModel()
 {
     _devicesController = DevicesController.getInstance();
 }
        public string DeviceCurrectLineChart(string type, string roomId)
        {
            DevicesController DevicesControl = new DevicesController();

            string tableName = "";
            List <DevicesListModel> DevicesDataList = DevicesControl.GetSearchDevices().Where(d => d.roomId.Contains(roomId)).ToList();

            switch (type)
            {
            case "AC":
                DevicesDataList  = DevicesDataList.Where(x => x.devicesId.Contains("AC")).ToList();
                ViewBag.unit     = " C";
                ViewBag.unitName = "Air Conditioner Temperature";
                tableName        = "AC";

                break;

            case "LT":
                DevicesDataList  = DevicesDataList.Where(x => x.devicesId.Contains("LT")).ToList();
                ViewBag.unit     = " lm";
                ViewBag.unitName = "Light Luminosity";
                tableName        = "LIGHT";

                break;

            case "HD":
                DevicesDataList  = DevicesDataList.Where(x => x.devicesId.Contains("HD")).ToList();
                ViewBag.unit     = " %";
                ViewBag.unitName = "Humidifier Humidity";
                tableName        = "HUM";

                break;

            case "EF":
                DevicesDataList  = DevicesDataList.Where(x => x.devicesId.Contains("EF")).ToList();
                ViewBag.unit     = " rpm";
                ViewBag.unitName = "FAN Revolution(s)";
                tableName        = "EXH_FAN";

                break;

            case "AS":
                DevicesDataList  = DevicesDataList.Where(x => x.devicesId.Contains("AS")).ToList();
                ViewBag.unit     = " ";
                ViewBag.unitName = "AS";
                tableName        = "AS_SENSOR";

                break;

            default:

                break;
            }

            List <CurrentDataModel> CurrentList = new List <CurrentDataModel>();

            DateTime today = DateTime.Now;


            //end set time
            List <string> labelss = new List <string>();

            List <object> datas = new List <object>();

            var start = today.AddHours(time * -1);
            //var start = today.AddHours(-3);
            var end = today;
            //end set time
            List <CurrentDataModel> searchResultOfCurrentDataList = new List <CurrentDataModel>();
            var filterStartDateTime = Builders <CurrentDataModel> .Filter.Gte(x => x.latest_checking_time, start);

            var filterEndDateTime = Builders <CurrentDataModel> .Filter.Lte(x => x.latest_checking_time, end);

            if (DevicesDataList.Count() > 0)
            {
                foreach (var get in DevicesDataList)
                {
                    var filterId = Builders <CurrentDataModel> .Filter.Eq(x => x.devicesId, get.devicesId);

                    labelss.Add(get.devicesId);
                    searchResultOfCurrentDataList = new DBManger().DataBase.GetCollection <CurrentDataModel>(tableName).Find(filterId & filterStartDateTime & filterEndDateTime).Sort(Builders <CurrentDataModel> .Sort.Descending(s => s.latest_checking_time)).ToList();
                    datas.Add(MangeData(searchResultOfCurrentDataList).ToArray());
                }
            }

            return(LineChart(DevicesDataList.Count, labelss, datas));
        }
        //[Route("RoomDetail/RoomDetail/{roomID}")]
        public IActionResult RoomDetail(String roomID)
        {
            ViewData["roomID"] = roomID;
            //get sensor and device list
            SensorsController       sensorsController = new SensorsController();
            List <SensorsListModel> sensorsList       = sensorsController.GetSensorsListByRoomid(roomID);
            DevicesController       DevicesController = new DevicesController();
            List <DevicesListModel> devicesList       = DevicesController.GetDevicesListByRoomid(roomID);

            //power list
            List <DailyUsageModel>      dailyUsageModelList = devicesPowerUseOutputUtil.Dailyusage();
            List <MongoDevicesPowerUse> totalPowerUsageList = devicesPowerUseOutputUtil.getPowerUseList();

            double totalPowerUsage = 0;//total power usage of this room

            foreach (MongoDevicesPowerUse mpu in totalPowerUsageList)
            {
                if (mpu.roomId == roomID)
                {
                    totalPowerUsage += mpu.power_used;
                }
            }

            double monthPowerUsage = 0;//total power usage of this room

            foreach (DailyUsageModel dum in dailyUsageModelList)
            {
                if (dum.roomId == roomID)
                {
                    monthPowerUsage += dum.power_used;
                }
            }
            double thisMonthAcUsage = getRoomACPowerUse(roomID);

            //double monthPowerUsage = devicesPowerUseOutputUtil.getTotalPowerUse();//all device this month usage
            ViewData["monthPowerUsage"]  = Math.Round(monthPowerUsage, 2, MidpointRounding.AwayFromZero);
            ViewData["totalPowerUsage"]  = Math.Round(totalPowerUsage, 2, MidpointRounding.AwayFromZero);
            ViewData["thisMonthAcUsage"] = Math.Round(thisMonthAcUsage, 2, MidpointRounding.AwayFromZero);

            //get room model
            var collection = dBManger.DataBase.GetCollection <MongoRoomModel>("ROOM");
            var roomList   = collection.Find(x => x.roomId == roomID).ToList();

            //Debug.WriteLine("roomList list = " + roomList.ToJson().ToString());
            if (roomList.Count > 0)
            {
                ViewData["roomModel"] = roomList[0];
            }
            else
            {
                ViewData["roomModel"] = new MongoRoomModel();
            }


            //Debug.WriteLine("Devices list = " + deviceslist.ToJson().ToString());
            ViewData["sensorsList"] = sensorsList;
            ViewData["devicesList"] = devicesList;
            //ViewData["powerUsageList"] = totalPowerUsageList;

            //Debug.WriteLine("powerUsageList list = " + powerUsageList.ToJson().ToString());
            return(View());
        }
예제 #18
0
        public static string[] interpretation(JObject json)
        {
            Console.WriteLine(json);
            string[] res = new string[3] {
                "", "", ""
            };
            string type = (string)json["type"];
            string conn = (string)(json["conn"]);

            if (!String.IsNullOrEmpty(type))
            {
                int      port;
                string[] adressBuffer = conn.Split(':');
                string[] pairaineKey  = adressBuffer[1].Split('@');
                //ip@port
                IPAddress ipAddress = IPAddress.Parse(adressBuffer[0]);
                port = Int32.Parse(pairaineKey[0]);
                string author = (string)json["author"];
                if (type.ToLower() == "connect") //1.Type 2.Author 3.IPaddress@Port
                {
                    res[0] = "Connection";
                    res[1] = author;
                    res[2] = ipAddress.ToString() + ":" + port.ToString() + ":" + pairaineKey[1];

                    Console.WriteLine("Demande Connection");
                    Console.WriteLine("L'appareil " + author + "(" + ipAddress.ToString() + ":" + port.ToString() + ") souhaite se connecter.");
                }
                else if (type.ToLower() == "disconnect") //1.Type 2.Author 3.IPaddress@Port
                {
                    res[0] = "Disconnection";
                    res[1] = author;
                    res[2] = ipAddress.ToString() + ":" + port.ToString();
                    Console.WriteLine("Demande Connection");
                    Console.WriteLine("L'appareil " + author + "(" + ipAddress.ToString() + ":" + port.ToString() + ") souhaite se deconnecter.");
                }

                else if (type.ToLower() == "notification") //1.Type 2.Application 3.Message
                {
                    res = new string[5] {
                        "", "", "", "", ""
                    };
                    res[0] = "Notification";
                    Console.WriteLine("Notification");
                    IList <string> allObject   = json["object"].Select(t => (string)t).ToList();
                    string         application = allObject[0];
                    string         date        = allObject[1];
                    string         message     = allObject[2];
                    string         title       = allObject[3];
                    res[1] = application;
                    res[2] = message;
                    res[3] = title;
                    res[4] = date;
                    //Démonstration utilisation des objets obtenus depuis le JSON
                    Console.WriteLine("L'application " + application + " a reçu le message suivant: '" + message + "' depuis l'appareil de " + author + " à " + date + ".");
                }
                else if (type.ToLower() == "batterystate")
                {
                    res[0] = "batteryState";
                    string etat;
                    string pourcentage;
                    Console.WriteLine("batteryState");
                    IList <string> allObject = json["object"].Select(t => (string)t).ToList();
                    pourcentage = allObject[1];

                    if (allObject[0].ToLower() == "true")
                    {
                        etat = "isCharging";
                    }
                    else
                    {
                        etat = "notCharging";
                    }
                    res[1] = pourcentage;
                    res[2] = etat;
                    //Démonstration utilisation des objets obtenus depuis le JSON
                    Console.WriteLine("L'appareil " + author + " est a " + pourcentage + "%. Etat: " + etat);
                }
                else if (type.ToLower() == "contacts")
                {
                    res[0] = "contacts";
                    Console.WriteLine("contacts");

                    JObject array    = (JObject)json["object"];
                    var     contacts = array["contacts"];
                    var     name     = json.GetValue("conn").ToString().Split(':')[0];

                    Device dev  = DevicesController.getInstance().getDevice(name);
                    var    list = DevicesController.getInstance().Devices;
                    foreach (JObject contact in contacts)
                    {
                        JToken[] numbers = contact["numbers"].ToArray();
                        Contact  cont    = new Contact((String)contact["nom"], (string)numbers[0], "*****@*****.**");
                        System.Windows.Application.Current.Dispatcher.Invoke(
                            DispatcherPriority.Normal,
                            (Action) delegate()
                        {
                            dev.listContact.Add(cont);
                        }
                            );
                    }

                    //Démonstration utilisation des objets obtenus depuis le JSON
                    Console.WriteLine("L'appareil a envoyé " + " contacts");
                }
            }
            else
            {
                Console.WriteLine("Message invalide.");
            }
            return(res);
        }
예제 #19
0
        private async void TestNotificationRegister(object sender, EventArgs e)
        {
            DevicesController dc = new DevicesController();

            dc.UpdateServersDb();
        }
        /// <summary>
        /// This method is called after authentication is successfull.
        /// Implement functionality that is useful as initial server communication.
        /// </summary>
        /// <param name="account"></param>
        async void PerformAuth2TestRequests(Account account)
        {
            Authorized = true;
            App.SuccessfulLoginAction();

            try
            {
                /*
                 * System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests before looop");
                 *
                 *
                 * foreach (KeyValuePair<string, string> p in account.Properties)
                 * {
                 *  System.Diagnostics.Debug.WriteLine("Property: Key:" + p.Key + " Value:" + p.Value);
                 * }
                 * System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests before looop");
                 *
                 * System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests: Url:" + AuthProvider.ApiRequests);
                 * System.Diagnostics.Debug.WriteLine("Request Url:" + AuthProvider.ApiRequests);
                 */
                Uri requestLocalToken = new Uri(AuthProvider.ApiRequests + account.Properties["access_token"]);
                System.Diagnostics.Debug.WriteLine("Requesting local token");
                System.Diagnostics.Debug.WriteLine("Using access_token: " + account.Properties["access_token"]);
                OAuth2Request request1 = new OAuth2Request("GET", requestLocalToken, null, account);
                //OAuth2Request request1 = new OAuth2Request("GET", requestLocalToken, null, null);

                IResponse response1 = await request1.GetResponseAsync();

                System.Diagnostics.Debug.WriteLine("After Response");


                Dictionary <string, string> responseDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(response1.GetResponseText());


                string localToken = "";
                string username   = "";

                if (response1.StatusCode == 200)
                {
                    System.Diagnostics.Debug.WriteLine("Response code from backend: 200");
                    localToken = responseDict["access_token"];
                    username   = responseDict["userName"];
                    System.Diagnostics.Debug.WriteLine("username: "******"localToken: " + localToken);

                    StudentsController sc        = new StudentsController();
                    DbStudent          dbStudent = new DbStudent();
                    if (dbStudent.CheckIfStudentExist(username))
                    {
                        System.Diagnostics.Debug.WriteLine("Student did exist");
                        Student student = dbStudent.GetStudent(username);
                        student.accessToken = localToken;
                        dbStudent.UpdateStudent(student);
                        DevicesController dc = new DevicesController();
                        dc.UpdateServersDb();
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Student did not exist");
                        dbStudent.DeleteAllStudents();
                        Student student = new Student();
                        student.username                    = username;
                        student.accessToken                 = localToken;
                        student.receiveNotifications        = true;
                        student.receiveJobNotifications     = true;
                        student.receiveProjectNotifications = true;
                        dbStudent.InsertStudent(student);
                        DevicesController dc       = new DevicesController();
                        DbDevice          dbDevice = new DbDevice();
                        dbDevice.FixStudentForeignKey(username);
                        dc.UpdateServersDb();
                    }
                }

                /*
                 * string studentEndpoint = "http://kompetansetorgetserver1.azurewebsites.net/api/v1/students";
                 * Uri testAuthorize = new Uri(studentEndpoint);
                 *
                 *
                 * //authorization: bearer b2Dvqzi9Ux_FAjbBYat6PE-LgNGKL_HDBWbnJ3Fb9cwfjaE8NQdqcvC8jwSB5QJUIVRog_gQQPjaRI0DT7ahu7TEpqP28URtPr1LjgaV - liCqgIuTdSHW_NqD3qh - 5shVh - h7TCin7XNHq8GSkGg5qtOlcHeFPSZ4xMwMbw5_1rBfKYJr3w0_D5R9jk0hJPEfJldCTYcawatz7wVfbmz0qKHAkrKxZyaqum6IHJWdczWz5K26RCfZWMwEmK1uLN5
                 *
                 * var client = new HttpClient();
                 * System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests before Setting AuthenticationHeaderValue");
                 * client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", localToken);
                 * System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests after Setting AuthenticationHeaderValue");
                 * System.Diagnostics.Debug.WriteLine(client.DefaultRequestHeaders.Authorization.Parameter);
                 *
                 *
                 * var response = await client.GetAsync(testAuthorize);
                 *
                 *
                 * System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests: StatusCode:" + response.StatusCode);
                 *                               // + " ResponseUri:" + response.ResponseUri);
                 * //System.Diagnostics.Debug.WriteLine("PerformAuth2TestRequests: Headers:");
                 *
                 *
                 * foreach (KeyValuePair<string, string> h in response.Headers)
                 * {
                 *  System.Diagnostics.Debug.WriteLine("Header: Key:" + h.Key + " Value:" + h.Value);
                 * }
                 * System.Diagnostics.Debug.WriteLine("Response(" + response.StatusCode);
                 * string jsonString = await response.Content.ReadAsStringAsync();
                 * System.Diagnostics.Debug.WriteLine(jsonString);
                 */
                // TODO Implement relevant GET, PUT or POST Requests
                // Notifies the app that the login was successful and that its safe to shift page.
                Authorized = true;
                App.SuccessfulLoginAction();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: PerformAuth2TestRequests: Message:" + ex.Message);
                foreach (KeyValuePair <string, string> p in account.Properties)
                {
                    System.Diagnostics.Debug.WriteLine("Key:" + p.Key + " Value:" + p.Value);
                }
            }
        }