Exemplo n.º 1
0
        public void AddUsers(Users user)
        {
            try
            {
                if (string.IsNullOrEmpty(DBName))
                {
                    throw new Exception("Строка подключения к базе данных не должна быть пустой");
                }

                using (LiteDatabase db = new LiteDatabase(DBName))
                {
                    var users = db.GetCollection <Users>("Users");
                    users.Insert(user);
                }
                if (printMessage != null)
                {
                    printMessage.Invoke("Запись добавлена успешно");
                }

                if (sendNotification != null)
                {
                    sendNotification.Invoke(user);
                }
            }
            catch (Exception ex)
            {
                if (showError != null)
                {
                    showError.Invoke(ex);
                }
            }
        }
Exemplo n.º 2
0
 public void AddEquipment(Equipment eq)
 {
     try
     {
         if (string.IsNullOrEmpty(DBName))
         {
             throw new Exception("Строка подключения к базе данных не должна быть пустой");
         }
         using (LiteDatabase db = new LiteDatabase(DBName))
         {
             var equipments = db.GetCollection <Equipment>("Equipment");
             equipments.Insert(eq);
         }
         if (printMessage != null)
         {
             printMessage.Invoke("Запись добавлена успешно");
         }
     }
     catch (Exception ex)
     {
         if (showError != null)
         {
             showError.Invoke(ex);
         }
     }
 }
Exemplo n.º 3
0
 private void WriteToFile(string message)
 {
     try
     {
         using (var file = new StreamWriter(filePath, true, Encoding.Default))
             file.WriteLine(message);
     }
     catch (UnauthorizedAccessException)
     {
         ShowError?.Invoke("Отказано в доступе");
     }
     catch (ArgumentException)
     {
         ShowError?.Invoke("Пустой путь файла");
     }
     catch (DirectoryNotFoundException)
     {
         ShowError?.Invoke("Указан недопустимый путь к файлу");
     }
     catch (IOException)
     {
         ShowError?.Invoke("Неверный или недопустимый синтаксис имени файла, каталога или диска");
     }
     catch (SecurityException)
     {
         ShowError?.Invoke("У вызывающего кода отсутствуют необходимые разрешения");
     }
 }
Exemplo n.º 4
0
        public static void UnhandledExceptionHandler(object sender, ThreadExceptionEventArgs e)
        {
            try
            {
                // Create Error Message
                string message = $"An Application Error has occurred.\r\n\r\nEXCEPTION:\r\nSource: {e.Exception.Source}\r\nMessage: {e.Exception.Message}\r\n";
                if (e.Exception.InnerException != null)
                {
                    message += $"\r\nINNER EXCEPTION:\r\nSource: {e.Exception.InnerException.Source}\r\nMessage: {e.Exception.InnerException.Message}\r\n";
                }
                message += $"\r\nSTACK TRACE:\r\n{e.Exception.StackTrace}";

                SendErrorMessage(message);
                ErrorForm?.Invoke(message);


                Environment.Exit(0);
            }
            catch
            {
                Environment.Exit(0);
            }
        }
Exemplo n.º 5
0
        private static void CurrentDomainOnUnhandledException(
            object sender, UnhandledExceptionEventArgs e)
        {
            var now         = DateTime.UtcNow;
            var logFileName = $"ErrorReport-{now.Year}-{now.Month}-{now.Day}-{now.Hour}-{now.Minute}-{now.Second}-{now.Millisecond}.txt";
            var logFilePath = Path.GetFullPath(Path.Combine(LogDirectory, logFileName));

            try
            {
                Directory.CreateDirectory(LogDirectory);
                using (var file = File.OpenWrite(logFilePath))
                    using (var writer = new StreamWriter(file))
                    {
                        var fileVersionInfo = FileVersionInfo;
                        writer.WriteLine("======================================================");
                        writer.WriteLine("==================== Error Report ====================");
                        writer.WriteLine("======================================================");
                        writer.WriteLine();
                        writer.WriteLine("========== Product Information ==========");
                        writer.WriteLine($"Product Name     {fileVersionInfo.ProductName}");
                        writer.WriteLine($"Company Name     {fileVersionInfo.CompanyName}");
                        writer.WriteLine($"Product Version  {fileVersionInfo.ProductVersion}");
                        writer.WriteLine($"File Version     {fileVersionInfo.FileVersion}");
                        writer.WriteLine();
                        writer.WriteLine("========== Environment Information ==========");
                        writer.WriteLine($"Opering System   {Environment.OSVersion}");
                        writer.WriteLine($"Version          {Environment.Version}");
                        writer.WriteLine($"Current Date     {now.ToString(CultureInfo.InvariantCulture)}");
                        writer.WriteLine();
                        writer.WriteLine("========== Exception ==========");
                        writer.WriteLine((Exception)e.ExceptionObject);
                    }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                ShowError?.Invoke(null, new MessageEventArgs(
                                      "An error has occurred and the application must now close.\n" +
                                      "\n" +
                                      "An error report could not created. The application will now close."));
                return;
            }

            ShowError?.Invoke(null, new MessageEventArgs(
                                  "An error has occurred and the application must now close.\n" +
                                  "\n" +
                                  "A report of this error has been created at the following location:\n\n" +
                                  $"{logFilePath}"));
        }
Exemplo n.º 6
0
        public static void UnhandledExceptionHandler(Exception e)
        {
            try
            {
                // Create Error Message
                string message = string.Format("An Application Error has occurred.\r\n\r\nEXCEPTION:\r\nSource: {0}\r\nMessage: {1}\r\n", e.Source, e.Message);
                if (e.InnerException != null)
                {
                    message += string.Format("\r\nINNER EXCEPTION:\r\nSource: {0}\r\nMessage: {1}\r\n", e.InnerException.Source, e.InnerException.Message);
                }
                message += string.Format("\r\nSTACK TRACE:\r\n{0}", e.StackTrace);


                ErrorForm?.Invoke(message);
            }
            catch
            {
            }
        }
Exemplo n.º 7
0
 public static void SendShowError(Exception ex)
 {
     ShowError?.Invoke(null, ex);
 }
Exemplo n.º 8
0
 public static void SendShowError(Exception ex)
 {
     Debug.WriteLine(ex.ToString());
     ShowError?.Invoke(null, ex);
 }
Exemplo n.º 9
0
        public static List <AzureIoTHub> GetIotHubList(
            ShowProgress progressCallback,
            ShowError errorCallback,
            RunPSCommand PSCallback)
        {
            List <AzureIoTHub> hubList = new List <AzureIoTHub>();

            try
            {
                if (MSAHelper.Subscriptions.Count == 0)
                {
                    // no subscritions means no IoT Hubs
                    return(hubList);
                }

                double progressPerSubscription = 85.0f / MSAHelper.Subscriptions.Count;
                for (int k = 0; k < MSAHelper.Subscriptions.Count; k++)
                {
                    List <Task> tasks            = new List <Task>();
                    string      subscriptionName = MSAHelper.Subscriptions[k];

                    PSCallback?.Invoke("az account set --subscription '" + subscriptionName + "'");

                    Collection <string> hubListResults = PSCallback?.Invoke("az iot hub list");
                    if (hubListResults != null && hubListResults.Count != 0)
                    {
                        for (int i = 0; i < hubListResults.Count; i++)
                        {
                            string hubName = hubListResults[i];
                            if (hubName.Contains("\"name\""))
                            {
                                hubName = hubName.Substring(hubName.IndexOf(":"));
                                hubName = hubName.Substring(hubName.IndexOf("\"") + 1);
                                hubName = hubName.Substring(0, hubName.IndexOf("\""));

                                // filter
                                if (hubName == "$fallback" || hubName == "S1" || hubName == "F1" || hubName == "B1")
                                {
                                    continue;
                                }

                                tasks.Add(Task.Run(() =>
                                {
                                    Collection <string> results2 = PSCallback("az iot hub show-connection-string --name '" + hubName + "'");
                                    if (results2 != null && results2.Count != 0)
                                    {
                                        for (int j = 0; j < results2.Count; j++)
                                        {
                                            string connectionString = results2[j];
                                            if (connectionString.Contains("\"connectionString\""))
                                            {
                                                // we have access
                                                lock (hubListLock)
                                                {
                                                    hubList.Add(new AzureIoTHub(hubName, subscriptionName));
                                                }
                                            }
                                        }
                                    }
                                }));
                            }
                        }
                    }

                    Task.WhenAll(tasks).Wait();
                    tasks.Clear();
                    progressCallback?.Invoke(progressPerSubscription, false);
                }
            }
            catch (Exception ex)
            {
                errorCallback?.Invoke(ex.Message);
            }

            return(hubList);
        }
        public static bool SignIn(
            ShowProgress progressCallback,
            ShowError errorCallback,
            RunPSCommand PSCallback)
        {
            if (CurrentState == SigninStates.SignedIn)
            {
                return(true);
            }

            try
            {
                Collection <string> results = PSCallback?.Invoke("az");
                if (results == null || results.Count == 0)
                {
                    errorCallback?.Invoke(Strings.AzureCLI);
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        Process.Start(new ProcessStartInfo("https://aka.ms/installazurecliwindows"));
                    }
                    else if (Environment.OSVersion.Platform == PlatformID.Unix)
                    {
                        "sudo apt-get update".Bash();
                        "sudo apt --assume-yes install curl".Bash();
                        "curl -sL -N https://aka.ms/InstallAzureCLIDeb | sudo bash".Bash();
                    }
                    else
                    {
                        errorCallback?.Invoke(Strings.OSNotSupported);
                    }

                    return(false);
                }

                progressCallback?.Invoke(5, true);

                results = PSCallback?.Invoke("az login");
                if (results == null || results.Count == 0)
                {
                    errorCallback?.Invoke(Strings.LoginFailedAlertMessage);
                    return(false);
                }

                // enumerate subscriptions
                Subscriptions.Clear();
                for (int i = 0; i < results.Count; i++)
                {
                    string json = results[i].ToString();
                    if (json.Contains("\"name\""))
                    {
                        json = json.Substring(json.IndexOf(":"));
                        json = json.Substring(json.IndexOf("\"") + 1);
                        json = json.Substring(0, json.IndexOf("\""));
                        if (!json.Contains("@"))
                        {
                            Subscriptions.Add(json);
                        }
                    }
                }

                progressCallback?.Invoke(10, true);

                // install iot extension, if required
                PSCallback?.Invoke("az extension add --name azure-cli-iot-ext");

                progressCallback?.Invoke(15, true);

                CurrentState = SigninStates.SignedIn;

                return(true);
            }
            catch (Exception ex)
            {
                errorCallback?.Invoke(Strings.LoginFailedAlertMessage + ": " + ex.Message);
                return(false);
            }
        }
Exemplo n.º 11
0
 void ErrorToShow(TErrorMessage error)
 {
     ShowError?.Invoke(this, new TErrorEventArgs(error));
 }