public IEnumerable<JObject> ToJsonForYdiff(RegisteredDevice device, KnowledgeGenerator knowledgeGenerator)
 {
     yield return new JObject
     {
         { "accepted", true },
         { "accountId", this.Account.Id },
         { "amount", this.Amount },
         { "categoryId", this.Category.Id },
         { "checkNumber", null },
         { "cleared", this.Cleared ? "Cleared" : "Uncleared" },
         { "date", DateTime.Today.ToString("yyyy-MM-dd") },
         { "dateEnteredFromSchedule", null },
         { "entityId", this.Id },
         { "entityType", "transaction" },
         { "entityVersion", $"{device.ShortDeviceId}-{knowledgeGenerator.GetNext()}" },
         { "flag", null },
         { "importedPayee", null },
         { "isTombstone", false },
         { "madeWithKnowledge", null },
         { "memo", this.Memo },
         { "payeeId", this.Payee.Id },
         { "subTransactions", new JArray() },
         { "targetAccountId", null },
         { "transferTransactionId", null }
     };
 }
Пример #2
0
        public async void Search()
        {
            if (firstAdapter == null)
            {
                return;
            }

            await firstAdapter.ScanAsync();

            //firstAdapter.AvailableNetworksChanged += FirstAdapter_AvailableNetworksChanged;

            var qualifyingWifi = firstAdapter.NetworkReport.AvailableNetworks.Where(N => N.Ssid.ToLower().StartsWith("ioespt-thing"));

            foreach (WiFiAvailableNetwork deviceWifi in qualifyingWifi)
            {
                RegisteredDevice FoundDevice = new RegisteredDevice()
                {
                    Status          = DeviceStatus.UnProvisioned,
                    ConnectedTo     = "None",
                    GivenName       = deviceWifi.Ssid,
                    ChipId          = "Unknown",
                    FirmwareName    = "Unknown",
                    FirmwareVersion = "Unknown",
                    ModuleType      = "Unknown"
                };

                if (DeviceFound != null)
                {
                    DeviceFound(this, new DeviceFoundEventArgs(FoundDevice));
                }
            }
        }
Пример #3
0
 public void Work(string log, RegisteredDevice device)
 {
     if (device.DeviceParseMethod == "Regex")
     {
         if (_regexParser.Work(log, device.RegexStatements, ref values))
         {
             CheckToProcesses(device.Id, true);
         }
         else
         {
             _errorLogService.Create(new ErrorLog {
                 Date = DateTime.Now.ToString(), Level = "Level=Error", ErrorMessage = "Message=Log is not parsed"
             });
         }
     }
     else if (device.DeviceParseMethod == "Code")
     {
         if (_codeParser.Work(log, ref values))
         {
             CheckToProcesses(device.Id, true);
         }
         else
         {
             _errorLogService.Create(new ErrorLog {
                 Date = DateTime.Now.ToString(), Level = "Level=Error", ErrorMessage = "Message=Log is not parsed"
             });
         }
     }
 }
Пример #4
0
        public bool SaveVideoPartial(MemoryStream FilePartial, string DeviceIdName, DateTime CaptureStart, bool IsFinished = false, DateTime?CaptureFinish = null)
        {
            //Will append this stream to the end of the other file
            RegisteredDevice Camera = _RegisteredDeviceService.GetDeviceByName(DeviceIdName);
            var footage             = _FootageStorageService.GetFootage(Camera.IdRegisteredDevice, CaptureStart);

            return(false);
        }
        public IEnumerable<JObject> ToJsonForYdiff(RegisteredDevice device, KnowledgeGenerator knowledgeGenerator)
        {
            var json = this.Transaction.GetJson();
            json["isTombstone"] = true;
            json["entityVersion"] = $"{device.ShortDeviceId}-{knowledgeGenerator.GetNext()}";

            yield return json;
        }
Пример #6
0
        private async Task <List <AuthenticatedWebSocketConnection> > GetOnlinePairedDevices(
            RegisteredDevice device, AnperiDbContext dbContext)
        {
            IEnumerable <int> pairedDeviceIds = await GetPairedDeviceIds(device, dbContext);

            lock (_activeConnections)
            {
                return(_activeConnections.Where(c => pairedDeviceIds.Contains(c.Key)).Select(c => c.Value).ToList());
            }
        }
Пример #7
0
 public async Task DeleteDevice(RegisteredDevice device)
 {
     if (device != null)
     {
         using (var uow = new UnitOfWork <RegisteredDevice, RomiDbContext>())
         {
             await Task.Run(() => uow.Repository().Delete(device));
         }
     }
 }
Пример #8
0
 public AuthenticatedWebSocketConnection(HttpContext context, WebSocket socket, byte[] buffer, RegisteredDevice device, AnperiDbContext dbContext, ILogger <AnperiWebSocketMiddleware> logger, AnperiWebSocketMiddleware anperiManager, List <AuthenticatedWebSocketConnection> onlinePairedDevices)
 {
     _context               = context;
     _socket                = socket;
     _buffer                = buffer;
     _device                = device;
     _logger                = logger;
     _anperiManager         = anperiManager;
     _db                    = dbContext;
     _loggedInPairedDevices = onlinePairedDevices ?? new List <AuthenticatedWebSocketConnection>();
 }
 public static IDevice MakeDevice(string DeviceType, RegisteredDevice DeviceDetails)
 {
     switch(DeviceType)
     {
         case "IOESPT-Display":
             return new DisplayDevice() { DeviceDetails = DeviceDetails };
         case "IOESPT-Thermometer":
             return new ThermometerDevice() { DeviceDetails = DeviceDetails };
         default:
             return new UnknownDevice() { DeviceDetails = DeviceDetails };
     }
 }
Пример #10
0
        public async Task <IActionResult> DeviceId([FromBody] RegisterViewModel viewModel)
        {
            var logger = await _tableService.GetLogger(viewModel.Id, viewModel.Password);

            var result = new RegisteredDevice
            {
                Find = logger != null,
                Id   = logger?.DeviceId,
                Name = logger?.Name
            };

            return(new JsonResult(result));
        }
Пример #11
0
        private void btnAddORSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!IPAddress.TryParse(txtIP.Text, out _))
                {
                    MessageBox.Show("IP address is incorrect!");
                    return;
                }
                if (string.IsNullOrEmpty(txtName.Text) || string.IsNullOrEmpty(txtHostname.Text))
                {
                    MessageBox.Show("Hostname/Name cannot be empty!");
                    return;
                }
                if (cbType.SelectedItem == null)
                {
                    MessageBox.Show("Select type, it cannot be empty!");
                    return;
                }

                var  type = (DeviceType)Enum.Parse(typeof(DeviceType), cbType.SelectedItem.ToString());
                bool?ret  = null;
                switch (currWork)
                {
                case TypeOfWork.FromScannedDevice:
                case TypeOfWork.AddDevice:
                    RegisteredDevice.AddRegisteredDevice(txtIP.Text, txtName.Text, txtHostname.Text, type, (short)numPort.Value);
                    break;

                case TypeOfWork.UpdateDevice:
                    ret = RegisteredDevice.UpdateRegisteredDevice(txtName.Text, type, (short)numPort.Value, RegisteredDevicePK);
                    break;
                }
                if (ret == null)
                {
                    DialogResult = DialogResult.OK;
                }
                if (ret != null && ret == true)
                {
                    DialogResult = DialogResult.OK;
                }
                else if (ret != null && ret == false)
                {
                    MessageBox.Show("Internal error! Could not update device!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Internal error! {ex.Message}");
            }
        }
Пример #12
0
        public async Task <ActionResult> Update(RegisteredDevice device)
        {
            try
            {
                await _database.Update(device);

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogError("Failed to update object {@Object} with error {@Exception}", device, e.Message);
                return(Conflict());
            }
        }
Пример #13
0
 public IEnumerable<JObject> ToJsonForYdiff(RegisteredDevice device, KnowledgeGenerator knowledgeGenerator)
 {
     yield return new JObject
     {
         { "budgeted", this.Amount },
         { "categoryId", this.Category.Id },
         { "entityId", $"MCB/{this.MonthAndYear.Year}-{this.MonthAndYear.Month}/{this.Category.Id}" },
         { "entityType", "monthlyCategoryBudget" },
         { "entityVersion", $"{device.ShortDeviceId}-{knowledgeGenerator.GetNext()}" },
         { "isTombstone", false },
         { "madeWithKnowledge", null },
         { "note", this.Note },
         { "overspendingHandling", null },
         { "parentMonthlyBudgetId", $"MB/{this.MonthAndYear.Year}-{this.MonthAndYear.Month}" }
     };
 }
        public IActionResult VerifyOTP(VerifyOTPReq req)
        {
            VerifyOTPResp resp = new VerifyOTPResp();

            try
            {
                if (RequestValidator.VerifyOTP(req))
                {
                    if (UserCRUD.IsValidUser(req.user_id))
                    {
                        if (DeviceCRUD.VerifyOTP(req.device_id, req.user_id, Convert.ToString(req.otp)) || req.otp == 1111)
                        {
                            var user = UserCRUD.GetUser(req.user_id);
                            // DeviceCRUD.NulifyOTP(req.device_id, req.user_id, Convert.ToString(req.otp));
                            RegisteredDevice device = DeviceCRUD.GetDevice(req.device_id);

                            resp.name           = user.Name;
                            resp.status_code    = Ok().StatusCode;
                            resp.status_message = StatusMessage.Success;
                            resp.token          = JwtToken.GenerateJwtToken(device);
                        }
                        else
                        {
                            resp.status_code    = Unauthorized().StatusCode;
                            resp.status_message = StatusMessage.UnAuthorised;
                        }
                    }
                    else
                    {
                        resp.status_code    = BadRequest().StatusCode;
                        resp.status_message = StatusMessage.BadRequest;
                    }
                }
                else
                {
                    resp.status_code    = BadRequest().StatusCode;
                    resp.status_message = StatusMessage.BadRequest;
                }
            }
            catch (Exception es)
            {
                resp.status_code    = 500;
                resp.status_message = StatusMessage.InternalServerError;
            }

            return(Ok(resp));
        }
Пример #15
0
        public static string GenerateJwtToken(RegisteredDevice device)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.Secret));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var claims      = new[] {
                new Claim(ClaimTypes.Name, device.User.Name),
                new Claim(ClaimTypes.Authentication, device.UserId.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };
            var token = new JwtSecurityToken(issuer: "Test",
                                             audience: "Test2",
                                             claims: claims,
                                             expires: DateTime.Now.AddMinutes(60),
                                             signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Пример #16
0
 public IEnumerable<JObject> ToJsonForYdiff(RegisteredDevice device, KnowledgeGenerator knowledgeGenerator)
 {
     yield return new JObject
     {
         { "name", this.Name },
         { "autoFillCategoryId", null },
         { "isTombstone", false },
         { "madeWithKnowledge", null },
         { "entityVersion", $"{device.ShortDeviceId}-{knowledgeGenerator.GetNext()}" },
         { "enabled", true },
         { "isResolvedConflict", false },
         { "autoFillMemo", string.Empty },
         { "autoFillAmount", 0m },
         { "entityId", this.Id },
         { "entityType", "payee" },
         { "targetAccountId", null }
     };
 }
        public IActionResult GenerateOTP(GenerateOTPReq req)
        {
            BaseResponse resp = new BaseResponse();

            try
            {
                if (RequestValidator.GenerateOTP(req))
                {
                    if (UserCRUD.IsValidUser(req.user_id))
                    {
                        var device = DeviceCRUD.GetDevice(req.device_id, req.user_id, req.os_type);
                        if (device == null)
                        {
                            device = new RegisteredDevice()
                            {
                                DeviceId = req.device_id, UserId = req.user_id, OsType = req.os_type, LastUpdate = DateTime.Now, Otp = "1111"
                            };
                        }
                        DeviceCRUD.AddDeviceIfNotExist(device);

                        resp.status_code    = Ok().StatusCode;
                        resp.status_message = StatusMessage.Success;
                    }
                    else
                    {
                        resp.status_code    = Unauthorized().StatusCode;
                        resp.status_message = StatusMessage.UnAuthorised;
                    }
                }
                else
                {
                    resp.status_code    = BadRequest().StatusCode;
                    resp.status_message = StatusMessage.BadRequest;
                }
            }
            catch (Exception es)
            {
                resp.status_code    = 500;
                resp.status_message = StatusMessage.InternalServerError;
            }

            return(Ok(resp));
        }
Пример #18
0
        private void UpdateRegisteredDevices()
        {
            registeredDevices = RegisteredDevice.GetRegisteredDevices();
            lstRegisterDevices.Items.Clear();

            foreach (var item in registeredDevices)
            {
                item.Deconstruct(out var collection);
                var lstItem = new ListViewItem();
                lstItem.SubItems.AddRange(Array.ConvertAll(collection, (KeyValuePair <string, string> i) =>
                {
                    return(new ListViewItem.ListViewSubItem()
                    {
                        Text = i.Value, Name = i.Key
                    });
                }));
                lstItem.SubItems.RemoveAt(0);
                lstRegisterDevices.Items.Add(lstItem);
            }
            checker.UpdateDevices(registeredDevices);
        }
 public static long AddDeviceIfNotExist(RegisteredDevice device)
 {
     using (var db = new Entities())
     {
         db.RegisteredDevice.Attach(device);
         if (device.Id > 0)
         {
             db.Entry(device).State = EntityState.Modified;
             db.Entry(device).Property(x => x.RegisteredOn).IsModified = false;
             db.Entry(device).Property(x => x.Otp).IsModified          = false;
         }
         else
         {
             device.RegisteredOn    = DateTime.Now;
             db.Entry(device).State = EntityState.Added;
         }
         device.LastUpdate = DateTime.Now;
         db.SaveChanges();
         return(device.Id);
     }
 }
Пример #20
0
        private async void SsdpClient_DeviceFound(object sender, DeviceFoundEventArgs e)
        {
            if (e.Device.DeviceType.manufacturer == "IOESPT")
            {
                var foundDevice = devices.FirstOrDefault(D => D.DeviceDetails.ChipId == e.Device.DeviceType.serialNumber);

                Uri uri = new Uri(e.Device.URLBase);


                if (foundDevice != null)
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => {
                        foundDevice.DeviceDetails.Status = DeviceStatus.Online;

                        foundDevice.DeviceDetails.Ip = uri.Host;
                    });
                }
                else
                {
                    //We have a new device online
                    var newDevice = new RegisteredDevice();

                    newDevice.ChipId          = e.Device.DeviceType.serialNumber;
                    newDevice.FirmwareName    = e.Device.DeviceType.modelName;
                    newDevice.ModuleType      = e.Device.DeviceType.modelName;
                    newDevice.FirmwareVersion = e.Device.DeviceType.modelNumber;
                    newDevice.GivenName       = e.Device.DeviceType.friendlyName;
                    newDevice.Status          = DeviceStatus.Online;
                    newDevice.ConnectedTo     = "None";
                    newDevice.Ip = uri.Host;

                    db.InsertNewDevice(newDevice);

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => {
                        devices.Add(DeviceTypeFactory.MakeDevice(newDevice.FirmwareName, newDevice));
                    });
                }
            }
        }
        public static IDevice MakeDevice(string DeviceType, RegisteredDevice DeviceDetails)
        {
            switch (DeviceType)
            {
            case "IOESPT-Display":
                return(new DisplayDevice()
                {
                    DeviceDetails = DeviceDetails
                });

            case "IOESPT-Thermometer":
                return(new ThermometerDevice()
                {
                    DeviceDetails = DeviceDetails
                });

            default:
                return(new UnknownDevice()
                {
                    DeviceDetails = DeviceDetails
                });
            }
        }
Пример #22
0
 private async Task <IEnumerable <int> > GetPairedDeviceIds(RegisteredDevice device, AnperiDbContext dbContext)
 {
     return(await Task.Run(() =>
     {
         IEnumerable <int> pairedDeviceIds;
         if (device is Host)
         {
             pairedDeviceIds = dbContext.HostPeripherals.Where(hp => hp.HostId == device.Id)
                               .Select(hp => hp.PeripheralId);
         }
         else if (device is Peripheral)
         {
             pairedDeviceIds = dbContext.HostPeripherals.Where(hp => hp.PeripheralId == device.Id)
                               .Select(hp => hp.HostId);
         }
         else
         {
             throw new NotImplementedException(
                 $"The device type {device.GetType().AssemblyQualifiedName} is not implemented in GetPairedDeviceIds");
         }
         return pairedDeviceIds.ToList();
     }));
 }
Пример #23
0
 public async Task Update(RegisteredDevice registeredDevice)
 {
     _logger.LogDebug("Update request, update: {@registeredDevice}", registeredDevice);
     var collection = GetCollection();
     await collection.ReplaceOneAsync(doc => doc.DeviceAddress == registeredDevice.DeviceAddress, registeredDevice);
 }
Пример #24
0
 public async Task Create(RegisteredDevice registeredDevice)
 {
     _logger.LogDebug("Create request, creating: {@registeredDevice}", registeredDevice);
     var collection = GetCollection();
     await collection.InsertOneAsync(registeredDevice);
 }
Пример #25
0
        private async Task <WebSocketCloseStatus> LoginDevice(HttpContext context, WebSocket socket, byte[] buffer, RegisteredDevice device, AnperiDbContext dbContext)
        {
            await socket.SendJson(SharedJsonApiObjectFactory.CreateLoginResponse(true, device.Name));

            List <AuthenticatedWebSocketConnection> connectedPairedDevices = await GetOnlinePairedDevices(device, dbContext);

            var connection = new AuthenticatedWebSocketConnection(context, socket, buffer, device, dbContext, _logger, this, connectedPairedDevices);

            lock (_syncRootActiveConnections)
            {
                _activeConnections.Add(connection.Device.Id, connection);
            }
            WebSocketCloseStatus closeStatus;

            try
            {
                await OnDeviceLoggedIn(connection, dbContext);

                closeStatus = await connection.Run(_options.Value.RequestCancelToken);
            }
            catch (WebSocketException se)
            {
                if (!(se.InnerException is BadHttpRequestException))
                {
                    throw;
                }
                closeStatus = WebSocketCloseStatus.Empty;
                _logger.LogWarning(
                    $"BadHttpRequestException occured while handling a websocket: {se.Message} -> {se.InnerException.Message}");
            }
            finally
            {
                if (!connection.IsAborted)
                {
                    await RemoveLoggedInDevice(connection, dbContext);
                }
            }
            return(closeStatus);
        }
Пример #26
0
 public DeviceFoundEventArgs(RegisteredDevice device)
 {
     Device = device;
 }
Пример #27
0
 public void DeleteDevice(RegisteredDevice device)
 {
     db.Table <RegisteredDevice>().Delete(C => C.ChipId == device.ChipId);
 }
Пример #28
0
        private async Task HandleWebSocket(HttpContext ctx, AnperiDbContext dbContext)
        {
            WebSocket socket = await ctx.WebSockets.AcceptWebSocketAsync();

            var buffer = new byte[_options.Value.WsBufferSize];

            WebSocketApiResult apiObjectResult =
                await socket.ReceiveApiMessage(buffer, _options.Value.RequestCancelToken);

            bool authFailed = true;
            WebSocketCloseStatus closeStatus = WebSocketCloseStatus.Empty;

            if (apiObjectResult.Obj == null)
            {
                await socket.SendJson(
                    SharedJsonApiObjectFactory.CreateError(apiObjectResult.JsonException.Message),
                    _options.Value.RequestCancelToken);
            }
            else
            {
                if (apiObjectResult.Obj.context == JsonApiContextTypes.server &&
                    apiObjectResult.Obj.message_type == JsonApiMessageTypes.request)
                {
                    apiObjectResult.Obj.data.TryGetValue(nameof(JsonLoginData.device_type), out string typeString);
                    if (Enum.TryParse(typeString, out SharedJsonDeviceType type) &&
                        Enum.TryParse(apiObjectResult.Obj.message_code, out SharedJsonRequestCode code))
                    {
                        RegisteredDevice device = null;
                        switch (code)
                        {
                        case SharedJsonRequestCode.login:
                            if (!apiObjectResult.Obj.data.TryGetValue("token", out string token))
                            {
                                await socket.SendJson(
                                    SharedJsonApiObjectFactory.CreateError("Error retrieving token from request."));
                            }
                            else
                            {
                                switch (type)
                                {
                                case SharedJsonDeviceType.host:
                                    device = dbContext.Hosts.SingleOrDefault(d => d.Token == token);
                                    break;

                                case SharedJsonDeviceType.peripheral:
                                    device = dbContext.Peripherals.SingleOrDefault(d => d.Token == token);
                                    break;

                                default:
                                    await socket.SendJson(
                                        SharedJsonApiObjectFactory.CreateError(
                                            "You need to be a host or peripheral."));

                                    break;
                                }
                                if (device != null)
                                {
                                    AuthenticatedWebSocketConnection activeConn;
                                    lock (_activeConnections)
                                    {
                                        _activeConnections.TryGetValue(device.Id, out activeConn);
                                    }
                                    if (activeConn != null)
                                    {
                                        activeConn.Abort();
                                        await RemoveLoggedInDevice(activeConn, dbContext);
                                    }
                                    closeStatus = await LoginDevice(ctx, socket, buffer, device, dbContext);

                                    authFailed = false;
                                }
                            }
                            break;

                        case SharedJsonRequestCode.register:
                            switch (type)
                            {
                            case SharedJsonDeviceType.host:
                                device = new Host();
                                break;

                            case SharedJsonDeviceType.peripheral:
                                device = new Peripheral();
                                break;

                            default:
                                await socket.SendJson(
                                    SharedJsonApiObjectFactory.CreateError(
                                        "You need to be a host or peripheral."));

                                break;
                            }
                            if (device != null)
                            {
                                device.Token = Cryptography.CreateAuthToken();
                                if (apiObjectResult.Obj.data.TryGetValue("name", out string name))
                                {
                                    device.Name = name;
                                }
                                else
                                {
                                    await socket.SendJson(
                                        SharedJsonApiObjectFactory.CreateError(
                                            "A device registration requires a name!"));
                                }
                                if (string.IsNullOrWhiteSpace(device.Name))
                                {
                                    device.Name = "devices want a name :(";
                                }
                                dbContext.RegisteredDevices.Add(device);
                                await dbContext.SaveChangesAsync();

                                await socket.SendJson(
                                    SharedJsonApiObjectFactory.CreateRegisterResponse(device.Token, device.Name));

                                closeStatus = await LoginDevice(ctx, socket, buffer, device, dbContext);

                                authFailed = false;
                            }
                            break;

                        default:
                            await socket.SendJson(
                                SharedJsonApiObjectFactory.CreateError("Only login and register are valid here."));

                            break;
                        }
                    }
                    else
                    {
                        await socket.SendJson(
                            SharedJsonApiObjectFactory.CreateError(
                                "Error parsing correct login or register parameters."));
                    }
                }
            }

            if (authFailed)
            {
                await socket.SendJson(SharedJsonApiObjectFactory.CreateLoginResponse(false, null));

                CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000));
                await socket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Authentication failed.", cts.Token);
            }
            else if (_options.Value.RequestCancelToken.IsCancellationRequested)
            {
                CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000));
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Server is shutting down.", cts.Token);
            }
            else
            {
                await socket.CloseAsync(closeStatus, apiObjectResult.SocketResult.CloseStatusDescription, CancellationToken.None);
            }
        }
Пример #29
0
 public void InsertNewDevice(RegisteredDevice device)
 {
     db.Insert(device);
 }
Пример #30
0
        private void ToolBtnsForRegisteredDevices_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsWorkingBW())
                {
                    MessageBox.Show("Some of the workers are load. Please wait...");
                    return;
                }
                if (!(new object[] { addToRegisteredDeviceListToolStripMenuItem, btnAddDevice }.Any(s => s == sender)) &&
                    lstRegisterDevices.SelectedItems.Count != 1)
                {
                    MessageBox.Show("Before perform operations with devices, select one!", "Error", MessageBoxButtons.OK);
                    return;
                }

                TypeOfWork?         work      = null;
                NameValueCollection nameValue = new NameValueCollection();
                if (sender == addToRegisteredDeviceListToolStripMenuItem)
                {
                    var sel = listVAddr.SelectedItems[0];
                    nameValue.Add("IP", sel.SubItems["IP"].Text);
                    nameValue.Add("Hostname", sel.SubItems["Hostname"].Text);
                    work = TypeOfWork.FromScannedDevice;
                }
                else if (sender == btnAddDevice)
                {
                    work = TypeOfWork.AddDevice;
                }
                else if (sender == btnShowDeviceInf)
                {
                    var registeredDevicePK = int.Parse(lstRegisterDevices.SelectedItems[0].SubItems["RegisteredDevicePK"].Text);
                    var registeredDevice   = registeredDevices.Find(r => r.RegisteredDevicePK == registeredDevicePK);
                    using (var form = new ShowInfoForm(registeredDevice))
                    {
                        form.ShowDialog();
                    }
                    return;
                }
                else if (sender == btnUpdDevice)
                {
                    var sel = lstRegisterDevices.SelectedItems[0];
                    nameValue.Add("RegisteredDevicePK", sel.SubItems["RegisteredDevicePK"].Text);
                    nameValue.Add("IP", sel.SubItems["IP"].Text);
                    nameValue.Add("Hostname", sel.SubItems["Hostname"].Text);
                    nameValue.Add("Name", sel.SubItems["Name"].Text);
                    nameValue.Add("Type", sel.SubItems["Type"].Text);
                    nameValue.Add("Port", sel.SubItems["Port"].Text);
                    work = TypeOfWork.UpdateDevice;
                }
                else if (sender == btnDelDevice)
                {
                    var registeredDevicePK = int.Parse(lstRegisterDevices.SelectedItems[0].SubItems["RegisteredDevicePK"].Text);
                    var ret = RegisteredDevice.RemoveRegisteredDevice(registeredDevicePK);
                    if (ret)
                    {
                        UpdateRegisteredDevices();
                    }
                    else
                    {
                        MessageBox.Show("Internal error! Could not remove this device!");
                    }
                    return;
                }

                if (!work.HasValue)
                {
                    return;
                }

                using (var form = new RegisterForm(work.Value, nameValue))
                {
                    var ret = form.ShowDialog();
                    if (ret == DialogResult.OK)
                    {
                        UpdateRegisteredDevices();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Internal error occur! {ex.Message}");
                LoggingHelper.LogEntry(SystemCategories.GeneralError, $"{ex.Message} {ex.StackTrace}");
            }
        }
Пример #31
0
        public ShowInfoForm(RegisteredDevice device)
        {
            InitializeComponent();

            pbCPU.Maximum  = 100;
            pbCPU.Minimum  = 0;
            pbRAM.Maximum  = 100;
            pbRAM.Minimum  = 0;
            pbDisk.Maximum = 100;
            pbDisk.Minimum = 0;

            for (int i = 0; i < MAXItems; ++i)
            {
                CPUValues.Add(new ObservableValue());
                RAMValues.Add(new ObservableValue());
            }

            CPU_RAM_usage.AxisX.Add(new Axis
            {
                Title      = "Time",
                ShowLabels = false,
            });
            CPU_RAM_usage.AxisY.Add(new Axis
            {
                Title    = "%, Load",
                MaxValue = 100,
                MinValue = 0
            });
            CPU_RAM_usage.LegendLocation = LegendLocation.Right;
            CPU_RAM_usage.Series.Add(new LineSeries()
            {
                Values = RAMValues,
                Title  = "RAM",
            });
            CPU_RAM_usage.Series.Add(new LineSeries()
            {
                Values = CPUValues,
                Title  = "CPU",
            });

            chartInterfaces.AxisX.Add(new Axis
            {
                Title      = "Time",
                ShowLabels = false,
            });
            chartInterfaces.AxisY.Add(new Axis
            {
                Title    = "In/Out",
                MinValue = 0
            });
            chartInterfaces.LegendLocation = LegendLocation.Right;

            this.device = device;

            switch (device.Type)
            {
            case DeviceType.PC:
                lblPCIP.Text           = device.IP;
                lblPCHost.Text         = device.Hostname;
                tabControl.SelectedTab = tpPC;
                break;

            case DeviceType.Router:
                lblIPRouter.Text       = device.IP;
                lblHostRouter.Text     = device.Hostname;
                tabControl.SelectedTab = tpRouter;
                break;

                #region Switch
                //case DeviceType.Switch:
                //    tabControl.SelectedTab = tpSwitch;
                //    break;
                #endregion
                #region Printer
                //case DeviceType.Printer:
                //    tabControl.SelectedTab = tpPrinter;
                //    break;
                #endregion
            default:
            {
                MessageBox.Show("Incorrect device type!");
                DialogResult = DialogResult.Abort;
                break;
            }
            }
        }
 public async Task <IActionResult> RegisterDevice(string host, [FromBody] RegisteredDevice device)
 {
     throw new NotImplementedException();
 }
 public async Task <IActionResult> DeleteDevice([FromBody] RegisteredDevice deviceInterface)
 {
     throw new NotImplementedException();
 }