예제 #1
0
        /// <summary>
        /// Handles the ButtonClick event of the btnOldDatabasePath control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DevExpress.XtraEditors.Controls.ButtonPressedEventArgs"/> instance containing the event data.</param>

        /// <summary>
        /// Handles the Click event of the btnFinish control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnFinish_Click(object sender, EventArgs e)
        {
            try
            {
                if (treeView1.Nodes.Count > 0)
                {
                    Cursor = Cursors.WaitCursor;

                    lstCheck.Clear();
                    foreach (TreeNode node in treeView1.Nodes)
                    {
                        GetCheckNode(node);
                    }


                    progressBar1.Visible = true;
                    progressBar1.Minimum = 0;
                    progressBar1.Maximum = lstCheck.Count;
                    int i       = 0;
                    var restore = new Restore
                    {
                        Action             = RestoreActionType.Database,
                        Database           = txtDatabaseName.Text.Trim(),
                        ReplaceDatabase    = true,
                        ContinueAfterError = true
                    };

                    if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + DatabaseTemplatePath))
                    {
                        XtraMessageBox.Show("Đường dẫn cơ sở dữ liệu mẫu không tồn tại", "Thông báo lỗi",
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    var backupDeviceItem =
                        new BackupDeviceItem(AppDomain.CurrentDomain.BaseDirectory + DatabaseTemplatePath,
                                             DeviceType.File);
                    restore.Devices.Add(backupDeviceItem);
                    var fileList = restore.ReadFileList(_server);

                    restore.RelocateFiles.Add(new RelocateFile(fileList.Rows[0][0].ToString().Trim(),
                                                               btnDatabasePath.Text + @"\" + txtDatabaseName.Text.Trim() + ".mdf"));
                    restore.RelocateFiles.Add(new RelocateFile(fileList.Rows[1][0].ToString().Trim(),
                                                               btnDatabasePath.Text + @"\" + txtDatabaseName.Text.Trim() + "_log.ldf"));

                    restore.SqlRestore(_server);
                    var database = _server.Databases[txtDatabaseName.Text.Trim()];
                    if (database != null)
                    {
                        database.SetOnline();
                    }



                    //update options
                    var message = _dbOptionsPresenter.Save();
                    if (message != null)
                    {
                        XtraMessageBox.Show(message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        progressBar1.Value = i;
                    }

                    //set connect string cho khởi tạo db mới hoặc db đang sử dụng


                    //xu ly password
                    var password = RegistryHelperTransform.GetValueByRegistryKey("Password");
                    if (!string.IsNullOrEmpty(password))
                    {
                        password = Crypto.Decrypting(password, "@bgt1me");
                    }
                    if (isNewDB)
                    {
                        //add new connection string
                        var dataProvider = ConfigurationManager.AppSettings.Get("ConnectionStringName");
                        var appConfig    =
                            ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                        var connectionString = string.Format(
                            "Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}",
                            RegistryHelper.GetValueByRegistryKey("InstanceName"),
                            txtDatabaseName.Text.Trim(),
                            RegistryHelper.GetValueByRegistryKey("UserName"),
                            password);
                        if (appConfig.ConnectionStrings.ConnectionStrings[dataProvider] == null) //AnhNT: Thêm điều kiện check nếu chưa tồn tại connection thì mới add
                        {
                            appConfig.ConnectionStrings.ConnectionStrings.Add(
                                new ConnectionStringSettings(dataProvider, connectionString));
                        }
                        else//Nếu tồn tại thì modify
                        {
                            appConfig.ConnectionStrings.ConnectionStrings[dataProvider].ConnectionString =
                                connectionString;
                        }
                        appConfig.Save(ConfigurationSaveMode.Full);
                        ConfigurationManager.RefreshSection("connectionStrings");
                    }



                    //chuyển đổi dữ liệu
                    string connectString = BuildConnectionString(cbSelectServer.Text, cboSelectSourceDB.Text);
                    foreach (var check in lstCheck)
                    {
                        var result = model.ConvertDB(connectString, check.Name.Substring(4));

                        if (result == null)
                        {
                            i = i + 1;
                            progressBar1.Value = i;
                            _result            = true;
                        }
                        else
                        {
                            _result = false;

                            XtraMessageBox.Show(check.Text + ":" + result, "Thông báo ",
                                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }

                if (_result == false)
                {
                    var databaseForDelete =
                        GlobalVariable.Server.Databases[txtDatabaseName.Text.Trim()];

                    databaseForDelete.Drop();
                }
                else
                {
                    DialogResult dialogResult = new DialogResult();
                    if (isNewDB)
                    {
                        dialogResult = XtraMessageBox.Show(
                            "Chuyển đổi cơ sở dữ liệu thành công!Bạn có muốn sử dụng cơ sở dữ liệu đã chuyển đổi",
                            "Thông báo ",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        Cursor = Cursors.Default;
                    }
                    else
                    {
                        dialogResult = XtraMessageBox.Show(
                            "Chuyển đổi cơ sở dữ liệu thành công!",
                            "Thông báo ",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Cursor = Cursors.Default;
                    }
                    if (dialogResult == DialogResult.Yes)
                    {
                        ////update registry
                        RegistryHelperTransform.RemoveConnectionString();
                        RegistryHelperTransform.SetValueForRegistry("DatabaseName", txtDatabaseName.Text);
                        var dbPathLenght = btnDatabasePath.Text.LastIndexOf(@"\", StringComparison.Ordinal);
                        var dbPath       = btnDatabasePath.Text;
                        if (dbPathLenght == -1)
                        {
                            dbPath = dbPath + @"\";
                        }
                        RegistryHelperTransform.SetValueForRegistry("DatabasePath", dbPath);
                        RegistryHelperTransform.SaveConfigFile();
                        System.Windows.Forms.Application.Restart();
                    }
                    else
                    {
                        if (isNewDB)
                        {
                            var dataProvider = ConfigurationManager.AppSettings.Get("ConnectionStringName");
                            var appConfig    =
                                ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                            //xu ly password
                            var password = RegistryHelperTransform.GetValueByRegistryKey("Password");
                            if (!string.IsNullOrEmpty(password))
                            {
                                password = Crypto.Decrypting(password, "@bgt1me");
                            }
                            var connectionString = string.Format(
                                "Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}",
                                RegistryHelperTransform.GetValueByRegistryKey("InstanceName"),
                                RegistryHelperTransform.GetValueByRegistryKey("DatabaseName"),
                                RegistryHelperTransform.GetValueByRegistryKey("UserName"),
                                password);
                            appConfig.ConnectionStrings.ConnectionStrings[dataProvider].ConnectionString =
                                connectionString;
                            appConfig.Save(ConfigurationSaveMode.Full);
                            ConfigurationManager.RefreshSection("connectionStrings");
                        }
                        Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                XtraMessageBox.Show(ex.ToString(),
                                    "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }