Beispiel #1
0
 private void FinishWizard(object sender, AeroWizard.WizardPageConfirmEventArgs e)
 {
     using (VendingEntities dc = (sqlconnstr == "") ? new VendingEntities() : new VendingEntities(entityconnstr))
     {
         using (var dbContextTransaction = dc.Database.BeginTransaction())
         {
             DateTime dt             = DateTime.Now;
             long     cdt            = Convert.ToInt64(dt.ToString("yyyyMMddHHmmss"));
             string   cdtstr         = dt.ToString("dd.MM.yyyy HH:mm:ss");
             SHA512   shaM           = new SHA512Managed();
             byte[]   HashedPsssword = shaM.ComputeHash(Encoding.UTF8.GetBytes(adminpasstextbox.Text));
             if (!SetFolderPermission(chartdirtextbox.Text))
             {
                 MessageBox.Show(@"Невозможно установить разрешения 'FULL ACCESS' для пользователя 'IIS AppPool\DefaultAppPool' на каталог '" + chartdirtextbox.Text + "'. Необходимо сделать это вручную, в противном случае на сайте не будут показываться графики.", "Установка разрешений на каталог", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             if (!EditAndSaveWebConfig())
             {
                 MessageBox.Show(@"Невозможно открыть или сохранить файл конфигурации веб-приложения", "Сохранение веб-конфигурации", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             try
             {
                 CspParameters cspParams = new CspParameters
                 {
                     ProviderType = 1,
                     Flags        = CspProviderFlags.UseArchivableKey,
                     KeyNumber    = (int)KeyNumber.Exchange
                 };
                 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
                 CryptoKeys tmpkeys = null;
                 try
                 {
                     tmpkeys = dc.CryptoKeys.First();
                     MessageBox.Show("Ключевая пара присутствует в БД, генерация ключей ОТМЕНЕНА! Для генерации новой пары ключей необходимо вручную удалить старые из базы данных.", "Генерация ключей", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 }
                 catch
                 {
                     //we will generate new keys only if no keypair exists in database
                     tmpkeys = new CryptoKeys()
                     {
                         PrivateKey = rsaProvider.ExportCspBlob(true),
                         PublicKey  = rsaProvider.ExportCspBlob(false)
                     };
                     dc.CryptoKeys.Add(tmpkeys);
                     dc.SaveChanges();
                     MessageBox.Show("Сгенерированы новые ключи. Необходимо изменить вручную открытый ключ сервера в настройках RpiVendApp. На устройствах со старыми ключами ПО должно быть обновлено для продолжения работы.", "Генерация ключей", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     File.WriteAllText("pubkey.txt", Convert.ToBase64String(tmpkeys.PublicKey));
                     System.Diagnostics.Process.Start("pubkey.txt");
                 }
                 rsaProvider.Dispose();
                 if (newsettings)
                 {
                     Accounts tmpacc = new Accounts()
                     {
                         UserID                  = adminemailtextbox.Text,
                         Valid                   = true,
                         TOTPSecret              = otpsecret,
                         DefaultContactPhone     = "",
                         DeviceCountLimit        = 999,
                         LicenseContent          = "",
                         PaidTillDateTime        = 99999999,
                         PaidTillDateTimeStr     = "99999999",
                         RegistrationDateTime    = cdt,
                         RegistrationDateTimeStr = cdtstr,
                         PasswordHash            = Convert.ToBase64String(HashedPsssword),
                         Suspended               = false
                     };
                     dc.Accounts.Add(tmpacc);
                     int         tmpport = Convert.ToInt32(smtpporttextbox.Text);
                     WebSettings tmpws   = new WebSettings()
                     {
                         AdminEmail            = adminemailtextbox.Text,
                         BingMapsAPIKey        = bingmapsapikeytextbox.Text,
                         MailFromAddress       = fromemailtextbox.Text,
                         LastSavedDateTimeStr  = cdtstr,
                         EMailDisplayName      = sendernametextbox.Text,
                         MailLogin             = smtpusernametextbox.Text,
                         MailPassword          = smtppasswordtextbox.Text,
                         MailUseSMTPAuth       = smtpusesslcheckbox.Checked,
                         RegAccountMailSubject = userregistersubjtextbox.Text,
                         RegDeviceMailSubject  = devregistersubjtextbox.Text,
                         ServerEndPoint        = serverendpointtextbox.Text,
                         SiteName   = sitenametextbox.Text,
                         SMTPHost   = smtphosttextbox.Text,
                         SMTPPort   = tmpport,
                         SMTPUseSSL = smtpusesslcheckbox.Checked
                     };
                     SystemLog tmplog = new SystemLog()
                     {
                         DateTime    = cdt,
                         DateTimeStr = cdtstr,
                         EventText   = "начальная настройка завершена",
                         Description = "",
                         UserID      = "Local administrator",
                         IPAddress   = "localhost"
                     };
                     dc.SystemLog.Add(tmplog);
                     dc.WebSettings.Add(tmpws);
                     dc.SaveChanges();
                 }
                 else
                 {
                     WebSettings extmpws  = dc.WebSettings.First();
                     Accounts    extmpacc = dc.Accounts.First(x => x.UserID == extmpws.AdminEmail);
                     extmpacc.UserID                  = adminemailtextbox.Text;
                     extmpacc.Valid                   = true;
                     extmpacc.TOTPSecret              = otpsecret;
                     extmpacc.RegistrationDateTime    = cdt;
                     extmpacc.RegistrationDateTimeStr = cdtstr;
                     extmpacc.PasswordHash            = Convert.ToBase64String(HashedPsssword);
                     int tmpport = Convert.ToInt32(smtpporttextbox.Text);
                     extmpws.AdminEmail            = adminemailtextbox.Text;
                     extmpws.BingMapsAPIKey        = bingmapsapikeytextbox.Text;
                     extmpws.MailFromAddress       = fromemailtextbox.Text;
                     extmpws.LastSavedDateTimeStr  = cdtstr;
                     extmpws.EMailDisplayName      = sendernametextbox.Text;
                     extmpws.MailLogin             = smtpusernametextbox.Text;
                     extmpws.MailPassword          = smtppasswordtextbox.Text;
                     extmpws.MailUseSMTPAuth       = smtpusesslcheckbox.Checked;
                     extmpws.RegAccountMailSubject = userregistersubjtextbox.Text;
                     extmpws.RegDeviceMailSubject  = devregistersubjtextbox.Text;
                     extmpws.ServerEndPoint        = serverendpointtextbox.Text;
                     extmpws.SiteName   = sitenametextbox.Text;
                     extmpws.SMTPHost   = smtphosttextbox.Text;
                     extmpws.SMTPPort   = tmpport;
                     extmpws.SMTPUseSSL = smtpusesslcheckbox.Checked;
                     dc.SaveChanges();
                     SystemLog tmplog = new SystemLog()
                     {
                         DateTime    = cdt,
                         DateTimeStr = cdtstr,
                         EventText   = "Настройки изменены и сохранены",
                         Description = "",
                         UserID      = "Local administrator",
                         IPAddress   = "localhost"
                     };
                     dc.SystemLog.Add(tmplog);
                     dc.SaveChanges();
                 }
                 dbContextTransaction.Commit();
                 MessageBox.Show("Настройки сохранены. Программа будет закрыта.", "ОК", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
             catch (Exception ex)
             {
                 dbContextTransaction.Rollback();
                 MessageBox.Show("Ошибка сохранения настроек. Программа будет закрыта." + Environment.NewLine + "Exception: " + ex.Message + Environment.NewLine + "Inner exception: " + ex.InnerException?.Message, "FAIL", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             shaM.Dispose();
         }
     }
 }
Beispiel #2
0
 private void FinishWizard(object sender, AeroWizard.WizardPageConfirmEventArgs e)
 {
     using (VendingEntities dc = new VendingEntities())
     {
         using (var dbContextTransaction = dc.Database.BeginTransaction())
         {
             DateTime dt             = DateTime.Now;
             long     cdt            = Convert.ToInt64(dt.ToString("yyyyMMddHHmmss"));
             string   cdtstr         = dt.ToString("dd.MM.yyyy HH:mm:ss");
             SHA512   shaM           = new SHA512Managed();
             byte[]   HashedPsssword = shaM.ComputeHash(Encoding.UTF8.GetBytes(adminpasstextbox.Text));
             if (!SetFolderPermission(@"C:\TempImageFiles"))
             {
                 MessageBox.Show(@"Unable to create or set 'FULL ACCESS' permissions for user 'IIS AppPool\DefaultAppPool' on folder 'C:\TempImageFiles'. You have to set it manually or web charts will not work.", "Folder permissions", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             try
             {
                 CspParameters cspParams = new CspParameters
                 {
                     ProviderType = 1,
                     Flags        = CspProviderFlags.UseArchivableKey,
                     KeyNumber    = (int)KeyNumber.Exchange
                 };
                 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
                 CryptoKeys tmpkeys = null;
                 try
                 {
                     tmpkeys = dc.CryptoKeys.First();
                     MessageBox.Show("KeyPair exists, no new key generation wil performed! You have to manually delete keypair from Database to generate new one.", "Key generation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 }
                 catch
                 {
                     //we will generate new keys only if no keypair exists in database
                     tmpkeys = new CryptoKeys()
                     {
                         PrivateKey = rsaProvider.ExportCspBlob(true),
                         PublicKey  = rsaProvider.ExportCspBlob(false)
                     };
                     dc.CryptoKeys.Add(tmpkeys);
                     dc.SaveChanges();
                     MessageBox.Show("New keypair generated. You have to manually add server's public key to RpiVendApp project's global variables. Devices with old server key must be updated to keep functioning.", "Key generation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     SaveFileDialog sfd = new SaveFileDialog()
                     {
                         AddExtension     = true,
                         Filter           = "Text File | *.txt",
                         FilterIndex      = 0,
                         FileName         = "pubkey.txt",
                         OverwritePrompt  = true,
                         Title            = "Select file to save server's public key",
                         InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                     };
                     if (sfd.ShowDialog() == DialogResult.OK && sfd.FileName != "")
                     {
                         File.WriteAllText(sfd.FileName, Convert.ToBase64String(tmpkeys.PublicKey));
                     }
                 }
                 if (newsettings)
                 {
                     Accounts tmpacc = new Accounts()
                     {
                         UserID                  = adminemailtextbox.Text,
                         Valid                   = true,
                         TOTPSecret              = otpsecret,
                         DefaultContactPhone     = "",
                         DeviceCountLimit        = 999,
                         LicenseContent          = "",
                         PaidTillDateTime        = 99999999,
                         PaidTillDateTimeStr     = "99999999",
                         RegistrationDateTime    = cdt,
                         RegistrationDateTimeStr = cdtstr,
                         PasswordHash            = Convert.ToBase64String(HashedPsssword),
                         Suspended               = false
                     };
                     dc.Accounts.Add(tmpacc);
                     int         tmpport = Convert.ToInt32(smtpporttextbox.Text);
                     WebSettings tmpws   = new WebSettings()
                     {
                         AdminEmail            = adminemailtextbox.Text,
                         BingMapsAPIKey        = bingmapsapikeytextbox.Text,
                         MailFromAddress       = fromemailtextbox.Text,
                         LastSavedDateTimeStr  = cdtstr,
                         EMailDisplayName      = sendernametextbox.Text,
                         MailLogin             = smtpusernametextbox.Text,
                         MailPassword          = smtppasswordtextbox.Text,
                         MailUseSMTPAuth       = smtpusesslcheckbox.Checked,
                         RegAccountMailSubject = userregistersubjtextbox.Text,
                         RegDeviceMailSubject  = devregistersubjtextbox.Text,
                         ServerEndPoint        = serverendpointtextbox.Text,
                         SiteName   = sitenametextbox.Text,
                         SMTPHost   = smtphosttextbox.Text,
                         SMTPPort   = tmpport,
                         SMTPUseSSL = smtpusesslcheckbox.Checked
                     };
                     SystemLog tmplog = new SystemLog()
                     {
                         DateTime    = cdt,
                         DateTimeStr = cdtstr,
                         EventText   = "Initial setup complete",
                         Description = "",
                         UserID      = "Local administrator",
                         IPAddress   = "localhost"
                     };
                     dc.SystemLog.Add(tmplog);
                     dc.WebSettings.Add(tmpws);
                     dc.SaveChanges();
                 }
                 else
                 {
                     WebSettings extmpws  = dc.WebSettings.First();
                     Accounts    extmpacc = dc.Accounts.First(x => x.UserID == extmpws.AdminEmail);
                     extmpacc.UserID                  = adminemailtextbox.Text;
                     extmpacc.Valid                   = true;
                     extmpacc.TOTPSecret              = otpsecret;
                     extmpacc.RegistrationDateTime    = cdt;
                     extmpacc.RegistrationDateTimeStr = cdtstr;
                     extmpacc.PasswordHash            = Convert.ToBase64String(HashedPsssword);
                     int tmpport = Convert.ToInt32(smtpporttextbox.Text);
                     extmpws.AdminEmail            = adminemailtextbox.Text;
                     extmpws.BingMapsAPIKey        = bingmapsapikeytextbox.Text;
                     extmpws.MailFromAddress       = fromemailtextbox.Text;
                     extmpws.LastSavedDateTimeStr  = cdtstr;
                     extmpws.EMailDisplayName      = sendernametextbox.Text;
                     extmpws.MailLogin             = smtpusernametextbox.Text;
                     extmpws.MailPassword          = smtppasswordtextbox.Text;
                     extmpws.MailUseSMTPAuth       = smtpusesslcheckbox.Checked;
                     extmpws.RegAccountMailSubject = userregistersubjtextbox.Text;
                     extmpws.RegDeviceMailSubject  = devregistersubjtextbox.Text;
                     extmpws.ServerEndPoint        = serverendpointtextbox.Text;
                     extmpws.SiteName   = sitenametextbox.Text;
                     extmpws.SMTPHost   = smtphosttextbox.Text;
                     extmpws.SMTPPort   = tmpport;
                     extmpws.SMTPUseSSL = smtpusesslcheckbox.Checked;
                     dc.SaveChanges();
                     SystemLog tmplog = new SystemLog()
                     {
                         DateTime    = cdt,
                         DateTimeStr = cdtstr,
                         EventText   = "System settings changed",
                         Description = "",
                         UserID      = "Local administrator",
                         IPAddress   = "localhost"
                     };
                     dc.SystemLog.Add(tmplog);
                     dc.SaveChanges();
                 }
                 dbContextTransaction.Commit();
                 MessageBox.Show("Settings updated. Program will be closed.", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
             catch (Exception ex)
             {
                 dbContextTransaction.Rollback();
                 MessageBox.Show("Settings NOT updated. Program will be closed." + Environment.NewLine + "Exception: " + ex.Message + Environment.NewLine + "Inner exception: " + ex.InnerException?.Message, "FAIL", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
 }