public async Task BackupAndRestoreSampleAsync()
        {
            var blobStorageUrl    = TestEnvironment.StorageUri;
            var blobContainerName = BlobContainerName;
            var sasToken          = "?" + SasToken;

            #region Snippet:HelloFullBackupAsync
            // Create a Uri with the storage container
            UriBuilder builder = new UriBuilder(blobStorageUrl)
            {
                Path = blobContainerName,
            };

            // Start the backup.
            BackupOperation backupOperation = await Client.StartBackupAsync(builder.Uri, sasToken);

            // Wait for completion of the BackupOperation.
            Response <BackupResult> backupResult = await backupOperation.WaitForCompletionAsync();

            // Get the Uri for the location of you backup blob.
            Uri backupFolderUri = backupResult.Value.BackupFolderUri;
            #endregion

            Assert.That(backupFolderUri, Is.Not.Null);
            Assert.That(backupOperation.HasValue, Is.True);

            await WaitForOperationAsync();

            #region Snippet:HelloFullRestoreAsync
            // Start the restore using the backupBlobUri returned from a previous BackupOperation.
            RestoreOperation restoreOperation = await Client.StartRestoreAsync(backupFolderUri, sasToken);

            // Wait for completion of the RestoreOperation.
            Response <RestoreResult> restoreResult = await restoreOperation.WaitForCompletionAsync();

            #endregion

            Assert.That(restoreOperation.HasValue, Is.True);
            Assert.That(restoreResult.Value.StartTime, Is.Not.EqualTo(default));
        public async Task BackupAndRestoreSampleAsync()
        {
            var blobStorageUrl    = TestEnvironment.StorageUri;
            var blobContainerName = BlobContainerName;
            var sasToken          = "?" + SasToken;

            // Create a Uri with the storage container.
            UriBuilder builder = new UriBuilder(blobStorageUrl)
            {
                Path = blobContainerName,
            };

            // Start the backup.
            BackupOperation backupOperation = await Client.StartBackupAsync(builder.Uri, sasToken);

            // Wait for completion of the BackupOperation.
            Response <Uri> backupResult = await backupOperation.WaitForCompletionAsync();

            // Get the Uri for the location of you backup blob.
            Uri backupFolderUri = backupResult.Value;

            Assert.That(backupFolderUri, Is.Not.Null);
            Assert.That(backupOperation.HasValue, Is.True);

            string keyName = PreviouslyBackedUpKeyName;

            #region Snippet:SelectiveRestoreAsync
            //@@ string keyName = <key name to restore>;

            // Start the restore for a specific key that was previously backed up using the backupBlobUri returned from a previous BackupOperation.
            RestoreOperation restoreOperation = await Client.StartSelectiveRestoreAsync(keyName, backupFolderUri, sasToken);

            // Wait for completion of the RestoreOperation.
            Response restoreResult = await restoreOperation.WaitForCompletionAsync();

            #endregion
            Assert.That(restoreResult, Is.Not.Null);
            Assert.That(restoreOperation.HasValue, Is.True);
        }
Esempio n. 3
0
        public void StartBackup(string backupDestinationDirectory)
        {
            var document = Get(BackupStatus.RavenBackupStatusDocumentKey, null);

            if (document != null)
            {
                var backupStatus = document.DataAsJson.JsonDeserialization <BackupStatus>();
                if (backupStatus.IsRunning)
                {
                    throw new InvalidOperationException("Backup is already running");
                }
            }
            Put(BackupStatus.RavenBackupStatusDocumentKey, null, JObject.FromObject(new BackupStatus
            {
                Started   = DateTime.Now,
                IsRunning = true,
            }), new JObject(), null);

            var backupOperation = new BackupOperation(this, Configuration.DataDirectory, backupDestinationDirectory);

            ThreadPool.QueueUserWorkItem(backupOperation.Execute);
        }
Esempio n. 4
0
        public void ScriptBackupTest()
        {
            DisasterRecoveryService service = new DisasterRecoveryService();
            string databaseName             = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);

            using (SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName))
            {
                var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
                using (DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true))
                    using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo))
                    {
                        string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);


                        BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName,
                                                                        BackupType.Full,
                                                                        new List <string>()
                        {
                            backupPath
                        },
                                                                        new Dictionary <string, int>()
                        {
                            { backupPath, (int)DeviceType.File }
                        });
                        BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn);

                        // Generate script for backup
                        service.ScriptBackup(backupOperation);
                        string script = backupOperation.ScriptContent;
                        Assert.True(!string.IsNullOrEmpty(script));

                        // Execute the script
                        testDb.RunQuery(script);

                        VerifyAndCleanBackup(sqlConn, backupPath);
                    }
            }
        }
Esempio n. 5
0
        public void Backup_and_restore_of_system_database_should_work()
        {
            using (var ravenServer = GetNewServer(runInMemory: false, requestedStorage: "esent"))
                using (var _ = NewRemoteDocumentStore(ravenDbServer: ravenServer, databaseName: "fooDB", runInMemory: false))
                {
                    using (var systemDatabaseBackupOperation = new BackupOperation
                    {
                        BackupPath = BackupDir,
                        Database = Constants.SystemDatabase,
                        ServerUrl = ravenServer.SystemDatabase.Configuration.ServerUrl
                    })
                    {
                        Assert.True(systemDatabaseBackupOperation.InitBackup());
                        WaitForBackup(ravenServer.SystemDatabase, true);
                    }
                }

            Assert.DoesNotThrow(() => MaintenanceActions.Restore(new RavenConfiguration(), new RestoreRequest
            {
                BackupLocation   = BackupDir,
                DatabaseLocation = DataDir
            }, s => { }));
        }
Esempio n. 6
0
        private string GenerateScriptForBackupType(BackupType backupType, string databaseName)
        {
            DisasterRecoveryService service = new DisasterRecoveryService();
            var liveConnection            = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
            DatabaseTaskHelper helper     = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
            SqlConnection      sqlConn    = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);
            string             backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);

            BackupInfo backupInfoLog = CreateDefaultBackupInfo(databaseName,
                                                               backupType,
                                                               new List <string>()
            {
                backupPath
            },
                                                               new Dictionary <string, int>()
            {
                { backupPath, (int)DeviceType.File }
            });

            backupInfoLog.FormatMedia      = true;
            backupInfoLog.SkipTapeHeader   = true;
            backupInfoLog.Initialize       = true;
            backupInfoLog.MediaName        = "backup test media";
            backupInfoLog.MediaDescription = "backup test";
            BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfoLog, helper.DataContainer, sqlConn);

            // Generate Script
            Console.WriteLine("Generate script for backup operation..");
            service.ScriptBackup(backupOperation);
            string script = backupOperation.ScriptContent;

            // There shouldnt be any backup file created
            Assert.True(!File.Exists(backupPath), "Backup file is not expected to be created");

            sqlConn.Close();
            return(script);
        }
Esempio n. 7
0
        public void CreateBackupTest()
        {
            DisasterRecoveryService service = new DisasterRecoveryService();
            string    databaseName          = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);

            try
            {
                var liveConnection         = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
                DatabaseTaskHelper helper  = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
                SqlConnection      sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);

                string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);

                BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName,
                                                                BackupType.Full,
                                                                new List <string>()
                {
                    backupPath
                },
                                                                new Dictionary <string, int>()
                {
                    { backupPath, (int)DeviceType.File }
                });
                BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn);

                // Backup the database
                service.PerformBackup(backupOperation);

                VerifyAndCleanBackup(backupPath);
                sqlConn.Close();
            }
            finally
            {
                testDb.Cleanup();
            }
        }
Esempio n. 8
0
        /// <summary>
        ///  Sets relay commands ( Relay commands provide communication between UI events and ViewModels )
        /// </summary>
        public void InitRelayCommands()
        {
            //BackOps.CollectionChanged += UpdateBackupListUI;
            // On Delete Backup Operation command, do the following :
            DeleteCommand = new RelayCommand(() =>
            {
                int toBeDeleted = BackOps.IndexOf(SelectedBackup);
                BackOps.Remove(SelectedBackup);
                if (BackOps.Count > 0)
                {
                    SelectedBackup = BackOps.ElementAt((toBeDeleted == 0) ? 0 : (toBeDeleted - 1));
                }
                else
                {
                    SelectedBackup = null;
                }
                SaveConfiguration();
                RaisePropertyChanged("BackOps");
            }, () =>
            {
                return(selectedBackup_ != null);
            });

            // On Add new Backup Operation command, do the following :
            AddCommand = new RelayCommand(() =>
            {
                var newId     = BackOps?.Count > 0 ? BackOps.Max(x => x.Id) + 1 : 1;
                var newBackOp = new BackupOperation()
                {
                    Alias = "New Backup", Id = newId, Enabled = true
                };
                newBackOp.Source.AbsolutePath = MainWindow.PathPlaceholder.Replace("path", "source");
                BackOps.Add(newBackOp);
                SelectedBackup = newBackOp;
            }, () =>
            {
                //return BackOps.LastOrDefault() != null ? BackOps.LastOrDefault().IsValid : false;
                return(true);
            });

            // On Add new Backup Destinaion command, do the following :
            AddDestinationCommand = new RelayCommand(() =>
            {
                DestinationInfo di = new DestinationInfo()
                {
                    Path = new SilentBackupService.Path()
                    {
                        AbsolutePath = MainWindow.PathPlaceholder.Replace("path", "destination")
                    }
                };
                SelectedBackup.Destinations.Add(di);
                DestInfos.Add(di);
            }, () => { return(SelectedBackup != null); });

            // On Toggle Enables/Disabled command, do the following :
            SwitchEnabledCommand = new RelayCommand(() =>
            {
                SelectedBackup.Enabled = !SelectedBackup.Enabled;
            }, () => { return(SelectedBackup != null); });

            SaveCommand = new RelayCommand(() =>
            {
                configuration_.BackupOperations = BackOps;
                SaveConfiguration();
                RaisePropertyChanged("BackOps");
            }, () => { return(true); });

            DiscardCommand = new RelayCommand <BackupOperation>((rollback) =>
            {
                if (rollback != null)
                {
                    var backup = BackOps.SingleOrDefault(x => x.Id == rollback.Id);
                    BackOps.Insert(BackOps.IndexOf(backup), rollback);
                    BackOps.Remove(backup);
                    SelectedBackup = rollback;
                }
                else
                {
                    if (DeleteCommand.CanExecute(null))
                    {
                        DeleteCommand.Execute(null);
                    }
                }
            }, (rollback) => { return(true); });
        }
        public async Task ResumeBackupRestore()
        {
            var blobStorageUrl    = TestEnvironment.StorageUri;
            var blobContainerName = BlobContainerName;
            var sasToken          = "?" + SasToken;
            var client            = GetClient(false);

            // Create a Uri with the storage container
            UriBuilder builder = new UriBuilder(blobStorageUrl)
            {
                Path = blobContainerName,
            };

            // Start the backup.
            BackupOperation originalBackupOperation = await Client.StartBackupAsync(builder.Uri, sasToken);

            var backupOperationId = originalBackupOperation.Id;

            #region Snippet:ResumeBackupAsync
#if SNIPPET
            // Construct a new KeyVaultBackupClient or use an existing one.
            KeyVaultBackupClient client = new KeyVaultBackupClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
#endif

            // Construct a BackupOperation using a KeyVaultBackupClient and the Id from a previously started operation.
            BackupOperation backupOperation = new BackupOperation(client, backupOperationId);
#if !SNIPPET
            backupOperation._retryAfterSeconds = (int)PollingInterval.TotalSeconds;
#endif

            // Wait for completion of the BackupOperation.
            Response <BackupResult> backupResult = await backupOperation.WaitForCompletionAsync();

            // Get the Uri for the location of you backup blob.
            Uri folderUri = backupResult.Value.FolderUri;
            #endregion

            Assert.That(folderUri, Is.Not.Null);
            Assert.That(backupOperation.HasValue, Is.True);

            await WaitForOperationAsync();

            // Start the restore using the backupBlobUri returned from a previous BackupOperation.
            RestoreOperation originalRestoreOperation = await Client.StartRestoreAsync(folderUri, sasToken);

            var restoreOperationId = originalRestoreOperation.Id;

            #region Snippet:ResumeRestoreAsync
#if SNIPPET
            // Construct a new KeyVaultBackupClient or use an existing one.
            KeyVaultBackupClient Client = new KeyVaultBackupClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
#endif

            // Construct a RestoreOperation using a KeyVaultBackupClient and the Id from a previously started operation.
            RestoreOperation restoreOperation = new RestoreOperation(client, restoreOperationId);
#if !SNIPPET
            restoreOperation._operationInternal._retryAfterSeconds = (int)PollingInterval.TotalSeconds;
#endif

            // Wait for completion of the RestoreOperation.
            RestoreResult restoreResult = await restoreOperation.WaitForCompletionAsync();

            #endregion

            Assert.That(restoreOperation.HasValue, Is.True);
            Assert.That(restoreResult.StartTime, Is.Not.EqualTo(default));
Esempio n. 10
0
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int k = e.ColumnIndex;
            int l = e.RowIndex;

            if (l >= 0)
            {
                currentrow = l;
                dataGridView1.Rows[currentrow].Selected = true;
                currentpos = dataGridView1.FirstDisplayedScrollingRowIndex;
                DataRowView temprow = (DataRowView)dataGridView1.Rows[l].DataBoundItem;
                //  string liushui = temprow[5].ToString();
                bool manager = Program.ManagerActived;

                switch (k)
                {
                case 0:
                    if (checkBox1.Checked == false)
                    {
                        //产品
                        listBox2.SelectedItem = temprow[2].ToString();
                        textBox1.Text         = temprow[3].ToString();
                        string startdatestr    = temprow[4].ToString();
                        string enddatestr      = temprow[5].ToString();
                        string transferdatestr = temprow[6].ToString();

                        if (startdatestr != "" && !startdatestr.Contains("0000"))
                        {
                            dateTimePicker1.Value = DateTime.Parse(startdatestr);
                            checkBox4.Checked     = false;
                        }
                        else
                        {
                            checkBox4.Checked = false;
                        }
                        if (enddatestr != "" && !enddatestr.Contains("0000"))
                        {
                            dateTimePicker2.Value = DateTime.Parse(enddatestr);
                            checkBox3.Checked     = false;
                        }
                        else
                        {
                            checkBox3.Checked = true;
                        }


                        if (transferdatestr != "" && !transferdatestr.Contains("0000"))
                        {
                            dateTimePicker3.Value = DateTime.Parse(transferdatestr);
                            checkBox2.Checked     = false;
                        }
                        else
                        {
                            checkBox2.Checked = true;
                        }
                        comboBox1.Text = temprow[7].ToString();
                        textBox3.Text  = temprow[8].ToString();
                        textBox2.Text  = temprow[10].ToString();
                    }

                    label8.Text = temprow[9].ToString();
                    // startdate = true;
                    //  enddate = true;
                    // transferdate = true;


                    break;

                case 1:
                    RNC f = new RNC();
                    f.Show();
                    f.product_filter = temprow["产品名称"].ToString() + "_" + temprow["产品架次"].ToString();

                    //  f.rncrf(temprow[2].ToString(), temprow[3].ToString());


                    break;

                case 2:

                    //Get the NC program
                    //Auto-copy it to G:\

                    //System.IO.DriveInfo[] allDrivess = System.IO.DriveInfo.GetDrives();
                    //Console.Write(allDrivess.First().VolumeLabel);

                    if (Program.userID.Split('_')[0] == "192.168.13.68" || Program.ManagerActived == true)
                    {
                        string proname = temprow[0].ToString();

                        //     proname = proname + "process";

                        string folderpath = Program.InfoPath + temprow["产品名称"].ToString() + "_" + proname + "\\NC\\";

                        string progname = Program.prodTable.Select("图号='" + proname + "'").First()["程序编号"].ToString();
                        string filepath = folderpath + "\\" + progname;



                        if (System.IO.Directory.Exists(folderpath) && File.Exists(filepath))

                        {
                            //校验MD5

                            string curMD5 = localMethod.GetMD5HashFromFile(filepath);
                            Dictionary <string, string> p1 = new Dictionary <string, string>();
                            string preMD5;
                            try
                            {
                                string preJson = DbHelperSQL.getlist("select 备注 from 产品数模 where 产品名称='" + temprow["产品名称"].ToString() + "' and 文件类型='Process'").First();

                                JsonSerializer serializer = new JsonSerializer();
                                // JsonReader reader = new JsonTextReader(new StringReader(preJson));
                                StringReader sr = new StringReader(preJson);
                                p1     = (Dictionary <string, string>)serializer.Deserialize(new JsonTextReader(sr), typeof(Dictionary <string, string>));
                                preMD5 = p1["MD5"];
                            }
                            catch (Exception ke)
                            {
                                MessageBox.Show("编程者未正确输出程序,请联系编程者!\r额外信息:\r" + ke.Message);
                                return;
                            }
                            if (preMD5 == curMD5)
                            {
                                //Copy all files into the CF card
                                System.IO.DriveInfo[] allDrives = System.IO.DriveInfo.GetDrives();
                                var targetDri = allDrives.Where(x => x.DriveType.ToString().ToUpper() != "CDROM" && x.VolumeLabel == "NC_PROGRAM");


                                if (targetDri.Count() > 0)
                                {
                                    string newfoldername = targetDri.First().RootDirectory.FullName;


                                    BackupOperation.backupfolder(newfoldername);

                                    localMethod.creatDir(newfoldername);

                                    List <FileInfo> files = new List <FileInfo>();
                                    files.WalkTree(folderpath, false);
                                    files.copyto(newfoldername);
                                    if (p1.ContainsKey("COPYTIME"))
                                    {
                                        p1["COPYTIME"] = DateTime.Now.ToString();
                                    }
                                    else
                                    {
                                        p1.Add("COPYTIME", DateTime.Now.ToString());
                                    }


                                    DbHelperSQL.ExecuteSql("update 产品数模 set 备注='" + localMethod.ToJson(p1) + "' where 产品名称='" + temprow["产品名称"].ToString() + "' and 文件类型='Process'");

                                    MessageBox.Show("请在操作记录或相关文件上记录MD5值:\r" + curMD5 + "\r\t该程序的生成时间为:\r" + p1["TIME"]);
                                    System.Diagnostics.Process.Start("explorer.exe", newfoldername);
                                }

                                else
                                {
                                    MessageBox.Show("未连接到CF卡(NC_PROGRAM),请确保你在我的电脑中已看到CF卡的盘符!");
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show("MD5校验未通过,联系编程者重新输出!");
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("NC程序不存在,联系工艺员或编程者!");
                            return;
                        }

                        //  if (manager)
                        //   {



                        //f1.inputValue = proname;
                        //f1.Show();
                    }
                    else
                    {
                        MessageBox.Show("必须在自动钻铆现场工作站上使用,并插入CF卡!");
                    }
                    break;

                case 3:

                    paperWork paperf = new paperWork();
                    paperf.Show();
                    paperf.ppworkrf(temprow[2].ToString(), temprow[3].ToString());
                    break;


                case 4:



                    //查看试片列表

                    string prodname   = temprow["图号"].ToString();
                    string chnname    = temprow["产品名称"].ToString();
                    string fuseno     = temprow["产品架次"].ToString();
                    string foldername = Program.InfoPath + chnname + "_" + prodname + "\\" + fuseno + "\\Inspection\\";

                    //刷新试片编号

                    DbHelperSQL.ExecuteSqlTran(AutorivetDB.rfcouponno(prodname));


                    localMethod.creatDir(foldername);


                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(foldername);
                    int fileNum = dir.GetFiles().Length;

                    if (fileNum > 2)
                    {
                        System.Diagnostics.Process.Start("explorer.exe", foldername);
                        return;
                    }

                    //               Microsoft.Office.Interop.Excel.Application app =
                    //  new Microsoft.Office.Interop.Excel.ApplicationClass();


                    //app.Visible = false;
                    string    processtb    = prodname.Replace("-001", "Process");
                    DataTable coupon_table = DbHelperSQL.Query("select * from (select * from 试片列表 where 产品图号='" + prodname + "') aa inner join " + processtb + " bb  on aa.程序段编号=bb.UUID").Tables[0];
                    //查询程序编号

                    string programno = AutorivetDB.queryno(prodname, "程序编号");


                    foreach (DataRow pp in coupon_table.Rows)
                    {
                        string progpart = pp["程序段编号"].ToString();


                        //取回程序段的ID号
                        string progid = pp["ID"].ToString();



                        string couponno = "T" + pp["编号"].ToString();
                        string fstname  = progpart.Split('_')[1];

                        string skinthk = pp["蒙皮厚度"].ToString();
                        string secmat  = pp["二层材料"].ToString();
                        string secthk  = pp["二层厚度"].ToString();
                        if (skinthk.Length < 3)
                        {
                            skinthk = "0" + skinthk;
                        }
                        if (secthk.Length < 3)
                        {
                            secthk = "0" + secthk;
                        }

                        if (fstname.Contains("B0206002"))
                        {
                            var    wBook    = new excelMethod(Program.InfoPath + "SAMPLE\\COUPON\\HI_LITE.xls");
                            string filename = foldername + progid + "_" + couponno + "_" + progpart + "_" + secthk + ".xls";
                            if (File.Exists(filename))
                            {
                                continue;
                            }


                            wBook.SaveAs(filename);

                            wBook.Set_CellValue(2, 8, (programno + "/" + progid + "/" + progpart));
                            wBook.Set_CellValue(5, 8, prodname);
                            //  wBook.Set_CellValue(7, 8, fuseno);
                            wBook.Set_CellValue(9, 8, couponno);
                            wBook.Set_CellValue(11, 4, fstname);
                            //蒙皮试片


                            wBook.Set_CellValue(9, 5, "C1-SKIN-" + skinthk);



                            //二层材料


                            wBook.Set_CellValue(9, 6, "C1-" + secmat + "-" + secthk);



                            wBook.Save();
                            wBook.Quit();
                        }

                        else
                        {
                            var wBook = new excelMethod(Program.InfoPath + "SAMPLE\\COUPON\\RIVET.xls");
                            //   progid = pp["ID"].ToString();
                            string filename = foldername + progid + "_" + couponno + "_" + progpart + "_" + secthk + "_BEFORE.xls";

                            if (File.Exists(filename))
                            {
                                continue;
                            }

                            wBook.SaveAs(filename);
                            //  Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
                            wBook.Set_CellValue(2, 10, programno + "/" + progid + "/" + progpart);
                            wBook.Set_CellValue(5, 10, prodname);
                            //wBook.Set_CellValue(7, 10, fuseno);
                            wBook.Set_CellValue(12, 10, couponno + "_BEFORE");
                            wBook.Set_CellValue(14, 6, fstname);
                            //蒙皮试片

                            wBook.Set_CellValue(12, 7, "C1-SKIN-" + skinthk);



                            //二层材料


                            wBook.Set_CellValue(12, 8, "C1-" + secmat + "-" + secthk);



                            wBook.Save();

                            wBook.Set_CellValue(12, 10, couponno + "_AFTER");

                            filename = foldername + progid + "_" + couponno + "_" + progpart + "_" + secthk + "_AFTER.xls";
                            if (File.Exists(filename))
                            {
                                continue;
                            }

                            wBook.SaveAs(filename);

                            wBook.Quit();
                        }
                    }

                    //生成产品检查单

                    string newpath = foldername + prodname + "_INSPECTION.doc";
                    File.Copy(Program.InfoPath + "SAMPLE\\PRODUCT_INSPECTION.docx", newpath, true);
                    var myAO = wordMethod.opendoc(newpath);

                    wordMethod.SearchReplace(myAO, "[1]", prodname);
                    // wordMethod.SearchReplace(myAO, "[2]", fuseno);
                    wordMethod.SearchReplace(myAO, "[3]", chnname);
                    myAO.Save();

                    myAO.Application.Quit();

                    //生成参数检查单
                    newpath = foldername + prodname + "_PARA_INSPECTION.xlsx";
                    var tianchong = new Dictionary <string, DataTable>();

                    // List<string> tianchongname=new List<string> ();


                    tianchong.Add(prodname, AutorivetDB.getparatable(prodname));
                    //  tianchongname.Add(productnametrim);

                    OfficeMethod.excelMethod.SaveDataTableToExcelTran(tianchong, newpath);


                    System.Diagnostics.Process.Start("explorer.exe", foldername);


                    break;



                    //case 3:



                    //     Dictionary<string, string> tmp = new Dictionary<string, string>();
                    //     tmp.Add("类型", "补铆");
                    //     //建立补铆文件夹
                    //     string rootdir =Program.InfoPath  + temprow[2].ToString() + "_" + temprow[0].ToString() + "\\" + temprow[3].ToString() + "\\补铆\\" ;


                    //     if (!System.IO.Directory.Exists(rootdir))
                    //     {
                    //         localMethod.creatDir(rootdir);

                    //     }
                    //     System.Diagnostics.Process.Start("explorer.exe", rootdir);
                    //     tmp.Add("目录地址", rootdir);
                    //     //用于信息传递


                    //     //名称
                    // string prodname = temprow[2].ToString();

                    // tmp.Add("中文名称", prodname+"壁板");
                    // tmp.Add("名称", prodname );



                    ////架次
                    //string jiaci = temprow[3].ToString();
                    //tmp.Add("架次", jiaci);



                    //     tmp.Add("保存地址", rootdir  + temprow[0].ToString() +"_"+ temprow[1].ToString() + "_补铆.doc");


                    //     AO f2=new AO();

                    //     f2.rncaao=tmp;
                    //     f2.tianchong();
                    //     f2.Show();



                    //     break;
                }
            }
        }
        public static void creatPACR(Dictionary <string, string> rncaao, bool overcover = false, bool closeword = true)
        {
            BackupOperation.backupfile(rncaao["PACR保存地址"]);
            if (!rncaao.Keys.Contains("图纸名称"))
            {
                rncaao.Add("图纸名称", AutorivetDB.queryno(rncaao["图号"], "图纸名称"));
            }



            var wordApp = new Microsoft.Office.Interop.Word.Application();

            wordApp.Visible = !closeword;
            var myAO = new Document();

            if (File.Exists(rncaao["PACR保存地址"]) && (!overcover))
            {
                myAO = wordApp.Documents.Open(rncaao["PACR保存地址"]);
            }
            else
            {
                try
                {
                    File.Copy(Program.InfoPath + "SAMPLE\\AOI\\PACR.doc", rncaao["PACR保存地址"], true);
                }
                catch
                {
                    MessageBox.Show("生成文件" + rncaao["图号"] + "PACR未成功,请关闭所有打开的word,运行kill word!");
                    return;
                }


                myAO = wordApp.Documents.Open(rncaao["PACR保存地址"]);
            }



            //控制记录编号
            wordMethod.SearchReplace(wordApp, myAO, "[1]", rncaao["AOI编号"] + "-PACR");
            //      myAO.Tables[1].Cell(2, 6).Range.Text = rncaao["AOI编号"] + "-PACR";
            //myAO.Tables[2].Cell(2, 6).Range.Text = rncaao["AOI编号"] + "-PACR";
            //myAO.Tables[3].Cell(2, 6).Range.Text = rncaao["AOI编号"] + "-PACR";
            //myAO.Tables[4].Cell(2, 6).Range.Text = rncaao["AOI编号"] + "-PACR";

            //控制记录名称


            myAO.Tables[1].Cell(4, 3).Range.Text = "自动钻铆\rAUTO-RIVETING";

            //装配图号
            //myAO.Tables[1].Cell(4, 2).Range.Text = rncaao["装配图号"];
            myAO.Tables[1].Cell(10, 1).Range.Text = "1";
            myAO.Tables[1].Cell(10, 2).Range.Text = rncaao["装配图号"];
            myAO.Tables[1].Cell(10, 3).Range.Text = rncaao["中文名称"] + "壁板组件\r" + rncaao["图纸名称"];
            // myAO.Tables[1].Cell(10, 5).Range.Text = rncaao["图纸版次"];
            //程序编号

            myAO.Tables[1].Cell(16, 1).Range.Text = "1";
            myAO.Tables[1].Cell(16, 2).Range.Text = rncaao["程序编号"];
            //2015.8.13不再需要状态编号
            //   myAO.Tables[1].Cell(16, 6).Range.Text = rncaao["状态编号"];
            //  myAO.Tables[1].Cell(16, 7).Range.Text = rncaao["中文名称"] + "壁板装配交付状态\rCOS OF " + rncaao["图纸名称"];



            //进入零件表填写


            //第一条


            myAO.Tables[4].Cell(5, 1).Range.Text = "1";
            //     myAO.Tables[2].Cell(3, 1).Height=
            myAO.Tables[4].Cell(5, 2).Range.Text = rncaao["图号"];
            myAO.Tables[4].Cell(5, 3).Range.Text = rncaao["中文名称"] + "壁板组件\r" + rncaao["图纸名称"];
            myAO.Tables[4].Cell(5, 4).Range.Text = "A";
            myAO.Tables[4].Cell(5, 5).Range.Text = "1";
            //    myAO.Tables[4].Cell(5, 6).Range.Text = rncaao["装配图号"];

            // myAO.Tables[1].Cell(7, 10).Range.Text = rncaao["架次"];
            // myAO.Tables[1].Cell(7, 1).Range.Text = dataGridView1.Rows[0].

            //开始统计紧固件

            System.Data.DataTable fsttable = AutorivetDB.allqtytable(rncaao["图号"]);;

            int fstcount = fsttable.Rows.Count;
            int nut5     = 0;
            int nut6     = 0;

            if (fstcount != 0)
            {
                for (int i = 0; i < fstcount; i++)
                {
                    string fstno = fsttable.Rows[i][0].ToString();
                    myAO.Tables[4].Cell(6 + i, 1).Range.Text = (i + 2).ToString();
                    myAO.Tables[4].Cell(6 + i, 2).Range.Text = fstno;
                    //string fstname = "";


                    if (fstno.Contains("B020600"))
                    {
                        myAO.Tables[4].Cell(6 + i, 3).Range.Text = "高锁\rHI-LITE";
                        int hiqty = System.Convert.ToInt16(fsttable.Rows[i][1].ToString());

                        if (fstno.Contains("AG5"))
                        {
                            nut5 = nut5 + hiqty;
                        }
                        else
                        {
                            nut6 = nut6 + hiqty;
                        }
                    }
                    else
                    {
                        myAO.Tables[4].Cell(6 + i, 3).Range.Text = "铆钉\rRIVET";
                    }
                    myAO.Tables[4].Cell(6 + i, 4).Range.Text = "U";
                    myAO.Tables[4].Cell(6 + i, 5).Range.Text = fsttable.Rows[i][1].ToString();
                    //   myAO.Tables[4].Cell(6 + i, 6).Range.Text = rncaao["装配图号"];
                }



                fstcount = 6 + fstcount;
                if (nut5 != 0)
                {
                    myAO.Tables[4].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                    myAO.Tables[4].Cell(fstcount, 2).Range.Text = "B0203013-08";
                    myAO.Tables[4].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                    myAO.Tables[4].Cell(fstcount, 4).Range.Text = "U";
                    myAO.Tables[4].Cell(fstcount, 5).Range.Text = nut5.ToString();
                    // myAO.Tables[4].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    if (nut6 != 0)
                    {
                        fstcount = fstcount + 1;
                        myAO.Tables[4].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                        myAO.Tables[4].Cell(fstcount, 2).Range.Text = "B0203013-3";
                        myAO.Tables[4].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                        myAO.Tables[4].Cell(fstcount, 4).Range.Text = "U";
                        myAO.Tables[4].Cell(fstcount, 5).Range.Text = nut6.ToString();
                        //  myAO.Tables[4].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    }
                }
                else
                {
                    if (nut6 != 0)
                    {
                        //fstcount = fstcount + 1;
                        myAO.Tables[4].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                        myAO.Tables[4].Cell(fstcount, 2).Range.Text = "B0203013-3";
                        myAO.Tables[4].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                        myAO.Tables[4].Cell(fstcount, 4).Range.Text = "U";
                        myAO.Tables[4].Cell(fstcount, 5).Range.Text = nut6.ToString();
                        myAO.Tables[4].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    }
                }
                //添加密封胶
                if ((nut5 + nut6) == 0)
                {
                }
                else
                {
                    fstcount = fstcount + 1;
                }

                myAO.Tables[4].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                myAO.Tables[4].Cell(fstcount, 3).Range.Text = "密封剂\rSEALANT";
                myAO.Tables[4].Cell(fstcount, 2).Range.Text = "MIL-PRF-81733 Type IV";
                myAO.Tables[4].Cell(fstcount, 4).Range.Text = "M";
                myAO.Tables[4].Cell(fstcount, 5).Range.Text = "340g";
                //  myAO.Tables[4].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];


                fstcount = fstcount + 1;
            }



            myAO.Save();
            FormMethod.scanfiledoc(rncaao["PACR保存地址"], myAO, closeword);
            //  MessageBox.Show("生成完毕,请补全其他信息");



            // return myAO;
        }
        public static Document creatAOI(Dictionary <string, string> rncaao, bool overcover = false, bool closeword = true)
        {
            BackupOperation.backupfile(rncaao["AOI保存地址"]);
            if (!rncaao.Keys.Contains("图纸名称"))
            {
                rncaao.Add("图纸名称", AutorivetDB.queryno(rncaao["图号"], "图纸名称"));
            }



            var wordApp = new Microsoft.Office.Interop.Word.Application();



            wordApp.Visible = !closeword;

            Document myAO;


            if (File.Exists(rncaao["AOI保存地址"]) && (!overcover))
            {
                myAO = wordApp.Documents.Open(rncaao["AOI保存地址"]);
            }
            else
            {
                try
                {
                    File.Copy(Program.InfoPath + "SAMPLE\\AOI\\AOI.docx", rncaao["AOI保存地址"], true);
                }
                catch
                {
                    MessageBox.Show("生成文件" + rncaao["图号"] + "AOI未成功,请关闭所有打开的word,运行kill word!");
                    return(null);
                }


                myAO = wordApp.Documents.Open(rncaao["AOI保存地址"]);
                Thread.Sleep(100);
                // myAO.SaveAs2(rncaao["AOI保存地址"]);
            }



            //替换所有编号
            wordMethod.SearchReplace(wordApp, myAO, "[2]", rncaao["AOI编号"]);


            //上下工序

            //     myAO.Tables[1].Cell(4, 4).Range.Text =

            string prezhanwei = AutorivetDB.queryno(rncaao["图号"], "预铆编号");

            myAO.Tables[1].Cell(4, 4).Range.Text = "C1-" + prezhanwei + "-020";

            myAO.Tables[1].Cell(4, 6).Range.Text = "C1-" + prezhanwei + "-030";
            //标题



            myAO.Tables[1].Cell(3, 4).Range.Text = "自动钻铆\rAUTO-RIVETING";
            //替换所有装配图号

            wordMethod.SearchReplace(wordApp, myAO, "[1]", rncaao["装配图号"]);



            //进入零件表填写


            //第一条


            myAO.Tables[2].Cell(3, 1).Range.Text = "1";
            //     myAO.Tables[2].Cell(3, 1).Height=
            myAO.Tables[2].Cell(3, 2).Range.Text = rncaao["图号"] + "P1";
            myAO.Tables[2].Cell(3, 3).Range.Text = rncaao["中文名称"] + "壁板组件\r" + rncaao["图纸名称"];
            myAO.Tables[2].Cell(3, 4).Range.Text = "A";
            myAO.Tables[2].Cell(3, 5).Range.Text = "1";
            myAO.Tables[2].Cell(3, 6).Range.Text = rncaao["装配图号"];
            if (rncaao["图号"].Contains("C017"))
            {
                myAO.Tables[1].Cell(3, 6).Range.Text = "☒CS100☑CS300";
            }


            // myAO.Tables[1].Cell(7, 10).Range.Text = rncaao["架次"];
            // myAO.Tables[1].Cell(7, 1).Range.Text = dataGridView1.Rows[0].

            //开始统计紧固件

            // System.Data.DataTable fsttable = autorivet_op.spfsttable(rncaao["图号"]);
            //2015.7.28改为统计加入试片耗损后的紧固件数量
            System.Data.DataTable fsttable = AutorivetDB.allqtytable(rncaao["图号"]);

            int fstcount = fsttable.Rows.Count;
            int nut5     = 0;
            int nut6     = 0;

            if (fstcount != 0)
            {
                for (int i = 0; i < fstcount; i++)
                {
                    string fstno = fsttable.Rows[i][0].ToString();
                    myAO.Tables[2].Cell(4 + i, 1).Range.Text = (i + 2).ToString();
                    myAO.Tables[2].Cell(4 + i, 2).Range.Text = fstno;
                    //string fstname = "";


                    if (fstno.Contains("B020600"))
                    {
                        myAO.Tables[2].Cell(4 + i, 3).Range.Text = "高锁\rHI-LITE";
                        int hiqty = System.Convert.ToInt16(fsttable.Rows[i][1].ToString());

                        if (fstno.Contains("AG5"))
                        {
                            nut5 = nut5 + hiqty;
                        }
                        else
                        {
                            nut6 = nut6 + hiqty;
                        }
                    }
                    else
                    {
                        myAO.Tables[2].Cell(4 + i, 3).Range.Text = "铆钉\rRIVET";
                    }
                    myAO.Tables[2].Cell(4 + i, 4).Range.Text = "U";
                    myAO.Tables[2].Cell(4 + i, 5).Range.Text = fsttable.Rows[i][1].ToString();
                    myAO.Tables[2].Cell(4 + i, 6).Range.Text = rncaao["装配图号"];
                }



                fstcount = 4 + fstcount;
                if (nut5 != 0)
                {
                    myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                    myAO.Tables[2].Cell(fstcount, 2).Range.Text = "B0203013-08";
                    myAO.Tables[2].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                    myAO.Tables[2].Cell(fstcount, 4).Range.Text = "U";
                    myAO.Tables[2].Cell(fstcount, 5).Range.Text = nut5.ToString();
                    myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    if (nut6 != 0)
                    {
                        fstcount = fstcount + 1;
                        myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                        myAO.Tables[2].Cell(fstcount, 2).Range.Text = "B0203013-3";
                        myAO.Tables[2].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                        myAO.Tables[2].Cell(fstcount, 4).Range.Text = "U";
                        myAO.Tables[2].Cell(fstcount, 5).Range.Text = nut6.ToString();
                        myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    }
                }
                else
                {
                    if (nut6 != 0)
                    {
                        //fstcount = fstcount + 1;
                        myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                        myAO.Tables[2].Cell(fstcount, 2).Range.Text = "B0203013-3";
                        myAO.Tables[2].Cell(fstcount, 3).Range.Text = "高锁帽\rNUT";
                        myAO.Tables[2].Cell(fstcount, 4).Range.Text = "U";
                        myAO.Tables[2].Cell(fstcount, 5).Range.Text = nut6.ToString();
                        myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];
                    }
                }
                //添加密封胶
                if ((nut5 + nut6) == 0)
                {
                }
                else
                {
                    fstcount = fstcount + 1;
                }

                myAO.Tables[2].Cell(fstcount, 1).Range.Text = (fstcount - 2).ToString();
                myAO.Tables[2].Cell(fstcount, 3).Range.Text = "密封剂\rSEALANT";
                myAO.Tables[2].Cell(fstcount, 2).Range.Text = "MIL-PRF-81733 Type IV";
                myAO.Tables[2].Cell(fstcount, 4).Range.Text = "M";
                myAO.Tables[2].Cell(fstcount, 5).Range.Text = "340g";
                myAO.Tables[2].Cell(fstcount, 6).Range.Text = rncaao["装配图号"];

                //添加胶嘴
                //fstcount = fstcount + 1;
                //List<string> tipls = autorivet_op.processitemlist(rncaao["装配图号"], "胶嘴Sealant_Tip");
                //for (int k=0;k<tipls.Count();k++)
                //{

                //    myAO.Tables[2].Cell(fstcount+k, 1).Range.Text = (fstcount+k - 2).ToString();
                //    myAO.Tables[2].Cell(fstcount + k, 2).Range.Text = tipls[k];
                //    myAO.Tables[2].Cell(fstcount + k, 3).Range.Text = "胶嘴\rSealant Tip";
                //    myAO.Tables[2].Cell(fstcount + k, 4).Range.Text = "M";
                //    myAO.Tables[2].Cell(fstcount + k, 5).Range.Text = "1";
                //    myAO.Tables[2].Cell(fstcount + k, 6).Range.Text = rncaao["装配图号"];

                //}

                //添加下铆头

                fstcount = fstcount + 1;


                while (!myAO.Tables[2].Cell(fstcount, 1).Range.Text.Contains("专用工具"))
                {
                    fstcount = fstcount + 1;
                }

                //定位到要输入专用工具的行
                fstcount = fstcount + 2;



                List <string> lals = AutorivetDB.processitemlist(rncaao["装配图号"], "下铆头Lower_Anvil");
                //最多只能放下三行
                //用于记录行尾,指示下一行数据的索引;
                int rear = fstcount;

                for (int k = 0; k < lals.Count(); k++)
                {
                    myAO.Tables[2].Cell(rear, 1).Range.Text = (k + 1).ToString();
                    myAO.Tables[2].Cell(rear, 2).Range.Text = "下铆头\rLower Anvil";
                    myAO.Tables[2].Cell(rear, 3).Range.Text = "1";
                    myAO.Tables[2].Cell(rear, 4).Range.Text = lals[k];

                    rear = rear + 1;
                }
                //高锁限力枪
                int toolindex = lals.Count();
                if (nut5 > 0)
                {
                    toolindex = toolindex + 1;
                    myAO.Tables[2].Cell(rear, 1).Range.Text = toolindex.ToString();
                    myAO.Tables[2].Cell(rear, 2).Range.Text = "高锁限力枪\rHI-LITE Istallation Tool";
                    myAO.Tables[2].Cell(rear, 3).Range.Text = "1";
                    myAO.Tables[2].Cell(rear, 4).Range.Text = "KTL1408A218B062";
                    toolindex += 1;
                    rear      += 1;
                }

                if (nut6 > 0)
                {
                    toolindex = toolindex + 1;
                    myAO.Tables[2].Cell(rear, 1).Range.Text = toolindex.ToString();
                    myAO.Tables[2].Cell(rear, 2).Range.Text = "高锁限力枪\rHI-LITE Istallation Tool";
                    myAO.Tables[2].Cell(rear, 3).Range.Text = "1";
                    myAO.Tables[2].Cell(rear, 4).Range.Text = "KTL1439A249C078";
                    rear += 1;
                }


                //寻找图纸列表
                while (!myAO.Tables[2].Cell(rear, 1).Range.Text.Contains("图纸列表"))
                {
                    rear = rear + 1;
                }

                rear = rear + 2;



                //添加图纸

                myAO.Tables[2].Cell(rear, 1).Range.Text = "1";
                myAO.Tables[2].Cell(rear, 2).Range.Text = rncaao["装配图号"];
                myAO.Tables[2].Cell(rear, 3).Range.Text = rncaao["中文名称"] + "壁板组件\r" + rncaao["图纸名称"];



                //寻找程序列表
                while (!myAO.Tables[2].Cell(rear, 1).Range.Text.Contains("程序列表"))
                {
                    rear = rear + 1;
                }

                rear = rear + 2;

                //myAO.Tables[2].Cell(rear, 1).Range.Text = "1";
                //myAO.Tables[2].Cell(rear, 2).Range.Text = rncaao["程序编号"];

                //替换所有程序编号
                wordMethod.SearchReplace(wordApp, myAO, "[3]", rncaao["程序编号"]);


                rear = rear + 1;



                //寻找参考文件列表
                while (!myAO.Tables[2].Cell(rear, 1).Range.Text.Contains("参考文件列表"))
                {
                    rear = rear + 1;
                }

                rear = rear + 8;

                //判断并修改工装编号

                if (rncaao["中文名称"].Contains("下"))
                {
                    wordMethod.SearchReplace(wordApp, myAO, "C1-RIT-C01329000-001", "C1-RIT-C01333400-001");

                    wordMethod.SearchReplace(wordApp, myAO, "中中机身上半壳卡板", "中后机身下半壳卡板");

                    wordMethod.SearchReplace(wordApp, myAO, "Auto riveting framework of upper lobe MID fuselage CTR", "Auto riveting framework of lower lobe MID fuselage AFT");


                    wordMethod.SearchReplace(wordApp, myAO, "C1-RIT-C01322000-001", "C1-RIT-C01332300-001");
                    wordMethod.SearchReplace(wordApp, myAO, "中前机身上半壳卡板", "中前机身下半壳卡板");

                    wordMethod.SearchReplace(wordApp, myAO, "Auto riveting framework of upper lobe MID fuselage FWD", "Auto riveting framework of lower lobe MID fuselage FWD");
                }



                //2015.8.13不再需要状态编号
                //  myAO.Tables[2].Cell(rear, 2).Range.Text = rncaao["状态编号"];

                //替换所有状态编号
                //   wordMethod.SearchReplace(wordApp, myAO, "C1-S22100-33", rncaao["状态编号"]);



                //     myAO.Tables[2].Cell(rear, 3).Range.Text = rncaao["中文名称"] + "壁板装配交付状态\rCOS OF " + rncaao["图纸名称"];
            }



            myAO.Save();
            //   wordApp.Quit();
            FormMethod.scanfiledoc(rncaao["AOI保存地址"], myAO, closeword);
            //  MessageBox.Show("生成完毕,请补全其他信息");



            return(myAO);
        }
Esempio n. 13
0
        public void CreateBackupWithAdvancedOptionsTest()
        {
            string    databaseName            = "testbackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb testDb                  = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);
            string    certificateName         = "backupcertificate" + new Random().Next(10000000, 99999999);
            string    masterkeyPassword       = Guid.NewGuid().ToString();
            string    createCertificateQuery  = string.Format(CreateCertificateQueryFormat, masterkeyPassword, certificateName);
            string    cleanupCertificateQuery = string.Format(CleanupCertificateQueryFormat, certificateName);

            // create master key and certificate
            Console.WriteLine("Create master key and certificate..");
            testDb.RunQuery(createCertificateQuery);

            var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);

            // Initialize backup service
            DatabaseTaskHelper helper  = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
            SqlConnection      sqlConn = DisasterRecoveryService.GetSqlConnection(liveConnection.ConnectionInfo);

            // Get default backup path
            Console.WriteLine("Get default backup path..");
            BackupConfigInfo backupConfigInfo = DisasterRecoveryService.Instance.GetBackupConfigInfo(helper.DataContainer, sqlConn, sqlConn.Database);
            string           backupPath       = Path.Combine(backupConfigInfo.DefaultBackupFolder, databaseName + ".bak");

            BackupInfo backupInfo = CreateBackupInfo(databaseName,
                                                     BackupType.Full,
                                                     new List <string>()
            {
                backupPath
            },
                                                     new Dictionary <string, int>()
            {
                { backupPath, (int)DeviceType.File }
            });

            // Set advanced options
            backupInfo.ContinueAfterError = true;
            backupInfo.FormatMedia        = true;
            backupInfo.SkipTapeHeader     = true;
            backupInfo.Initialize         = true;
            backupInfo.MediaName          = "backup test media";
            backupInfo.MediaDescription   = "backup test";
            backupInfo.RetainDays         = 90;
            backupInfo.CompressionOption  = (int)BackupCompressionOptions.On;

            // Set encryption
            backupInfo.EncryptionAlgorithm = (int)BackupEncryptionAlgorithm.Aes128;
            backupInfo.EncryptorType       = (int)BackupEncryptorType.ServerCertificate;
            backupInfo.EncryptorName       = certificateName;

            var backupParams = new BackupParams
            {
                OwnerUri   = liveConnection.ConnectionInfo.OwnerUri,
                BackupInfo = backupInfo
            };

            // Backup the database
            Console.WriteLine("Perform backup operation..");
            BackupOperation backupOperation = DisasterRecoveryService.Instance.SetBackupInput(helper.DataContainer, sqlConn, backupParams.BackupInfo);

            DisasterRecoveryService.Instance.PerformBackup(backupOperation);

            // Verify backup file is created
            Assert.True(File.Exists(backupPath));

            // Remove the backup file
            Console.WriteLine("Remove backup file..");
            if (File.Exists(backupPath))
            {
                File.Delete(backupPath);
            }

            // Delete certificate and master key
            Console.WriteLine("Remove certificate and master key..");
            testDb.RunQuery(cleanupCertificateQuery);

            // Clean up the database
            Console.WriteLine("Clean up database..");
            testDb.Cleanup();
        }
Esempio n. 14
0
        public void StartBackupOperation(DocumentDatabase database, string backupDestinationDirectory, bool incrementalBackup)
        {
            var backupOperation = new BackupOperation(database, persistenceSource, database.Configuration.DataDirectory, backupDestinationDirectory);

            ThreadPool.QueueUserWorkItem(backupOperation.Execute);
        }
Esempio n. 15
0
 //build object specifying file name, operation type & error message
 public BackupLog(string filename, BackupOperation operation, string error)
 {
     Filename = filename ;
     Operation = operation ;
     Error = error ;
 }
Esempio n. 16
0
		public void StartBackupOperation(DocumentDatabase docDb, string backupDestinationDirectory, bool incrementalBackup, DatabaseDocument documentDatabase)
		{
			if (new InstanceParameters(instance).Recovery == false)
				throw new InvalidOperationException("Cannot start backup operation since the recovery option is disabled. In order to enable the recovery please set the RunInUnreliableYetFastModeThatIsNotSuitableForProduction configuration parameter value to false.");

			var backupOperation = new BackupOperation(docDb, docDb.Configuration.DataDirectory, backupDestinationDirectory, incrementalBackup, documentDatabase);
			Task.Factory.StartNew(backupOperation.Execute);
		}
Esempio n. 17
0
        public void ScriptBackupWithAdvancedOptionsTest()
        {
            DisasterRecoveryService service = new DisasterRecoveryService();
            string    databaseName          = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999);
            SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName);

            try
            {
                var liveConnection            = LiveConnectionHelper.InitLiveConnectionInfo(databaseName);
                DatabaseTaskHelper helper     = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true);
                SqlConnection      sqlConn    = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo);
                string             backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn);

                string certificateName         = CreateCertificate(testDb);
                string cleanupCertificateQuery = string.Format(CleanupCertificateQueryFormat, certificateName);

                BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName,
                                                                BackupType.Full,
                                                                new List <string>()
                {
                    backupPath
                },
                                                                new Dictionary <string, int>()
                {
                    { backupPath, (int)DeviceType.File }
                });
                backupInfo.FormatMedia         = true;
                backupInfo.SkipTapeHeader      = true;
                backupInfo.Initialize          = true;
                backupInfo.MediaName           = "backup test media";
                backupInfo.MediaDescription    = "backup test";
                backupInfo.EncryptionAlgorithm = (int)BackupEncryptionAlgorithm.Aes128;
                backupInfo.EncryptorType       = (int)BackupEncryptorType.ServerCertificate;
                backupInfo.EncryptorName       = certificateName;

                BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn);

                // Backup the database
                Console.WriteLine("Generate script for backup operation..");
                service.ScriptBackup(backupOperation);
                string script = backupOperation.ScriptContent;

                // Run the script
                Console.WriteLine("Execute the script..");
                testDb.RunQuery(script);

                // Remove the backup file
                Console.WriteLine("Verify the backup file exists and remove..");
                VerifyAndCleanBackup(backupPath);

                // Delete certificate and master key
                Console.WriteLine("Remove certificate and master key..");
                testDb.RunQuery(cleanupCertificateQuery);
                sqlConn.Close();
            }
            finally
            {
                // Clean up the database
                Console.WriteLine("Clean up database..");
                testDb.Cleanup();
            }
        }
Esempio n. 18
0
        public void StartBackupOperation(DocumentDatabase docDb, string backupDestinationDirectory)
        {
            var backupOperation = new BackupOperation(docDb, docDb.Configuration.DataDirectory, backupDestinationDirectory);

            ThreadPool.QueueUserWorkItem(backupOperation.Execute);
        }
        public static void creatVERI(Dictionary <string, string> rncaao, bool overcover = false, bool closeword = true)
        {
            BackupOperation.backupfile(rncaao["鉴定表保存地址"]);
            if (!rncaao.Keys.Contains("图纸名称"))
            {
                rncaao.Add("图纸名称", AutorivetDB.queryno(rncaao["图号"], "图纸名称"));
            }



            var wordApp = new Microsoft.Office.Interop.Word.Application();

            wordApp.Visible = !closeword;
            var myAO = new Document();

            if (File.Exists(rncaao["鉴定表保存地址"]) && (!overcover))
            {
                myAO = wordApp.Documents.Open(rncaao["鉴定表保存地址"]);
            }
            else
            {
                try
                {
                    File.Copy(Program.InfoPath + "SAMPLE\\RULE\\VERI_SH.doc", rncaao["鉴定表保存地址"], true);
                }
                catch
                {
                    MessageBox.Show("生成文件" + rncaao["图号"] + "鉴定表未成功,请关闭所有打开的word,运行kill word!");
                    return;
                }


                myAO = wordApp.Documents.Open(rncaao["鉴定表保存地址"]);
            }

            //处理程序编号
            int progno = System.Convert.ToInt32(rncaao["程序编号"].Substring(5, 2));



            //鉴定表编号

            myAO.Tables[1].Cell(1, 5).Range.Text = "S2B-NCH-22100-" + progno.ToString();

            wordMethod.SearchReplace(wordApp, myAO, "[5]", rncaao["图号"]);
            wordMethod.SearchReplace(wordApp, myAO, "[6]", rncaao["中文名称"] + "壁板组件");
            wordMethod.SearchReplace(wordApp, myAO, "[7]", rncaao["图纸版次"]);
            wordMethod.SearchReplace(wordApp, myAO, "[11]", rncaao["程序编号"]);
            //开始处理试片编号
            //  DbHelperSQL.ExecuteSqlTran(autorivet_op.rfcouponno(rncaao["图号"]));

            //List< string> cplist=   DbHelperSQL.getlist("select CONCAT('T',编号) from 试片列表 where 产品图号='"+rncaao["图号"] + "' group by 编号 order by 编号;");

            //    string couponstr = rncaao["图号"].Replace("-001", cplist.First());

            //    for(int i=1;i<cplist.Count();i++)
            //    {
            //        couponstr = couponstr + "," + cplist[i];
            //    }

            //    wordMethod.SearchReplace(wordApp, myAO, "[8]", couponstr);
            myAO.Save();
            FormMethod.scanfiledoc(rncaao["鉴定表保存地址"], myAO, closeword);
            //  MessageBox.Show("生成完毕,请补全其他信息");



            // return myAO;
        }
Esempio n. 20
0
        private void BackupUpdateStatsInfo(BackupOperationStatus status, TransferStatus xferStatus)
        {
            if (RunningOperation == null)
            {
                return;
            }

            Models.BackupPlan     plan      = Model as Models.BackupPlan;
            BackupOperation       operation = RunningOperation as BackupOperation;
            BackupOperationReport report    = operation.Report;

            switch (status)
            {
            default: throw new ArgumentException("Unhandled status", "status");

            case BackupOperationStatus.Unknown:
            {
                break;
            }

            case BackupOperationStatus.Started:
            case BackupOperationStatus.Resumed:
            {
                logger.Info("{0} backup", status == BackupOperationStatus.Resumed ? "Resuming" : "Starting");

                // Update timestamps.
                plan.LastRunAt = DateTime.UtcNow;
                _daoBackupPlan.Update(plan);

                // Report
                Commands.OperationStatus cmdStatus = status == BackupOperationStatus.Started
                                                                ? Commands.OperationStatus.STARTED
                                                                : Commands.OperationStatus.RESUMED;
                Commands.GuiReportPlanStatus cmdData = BuildGuiReportPlanStatus(cmdStatus);
                string cmd = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }

            case BackupOperationStatus.ScanningFilesStarted:
            {
                logger.Info("Scanning files...");

                // Report
                Commands.OperationStatus     cmdStatus = Commands.OperationStatus.SCANNING_FILES_STARTED;
                Commands.GuiReportPlanStatus cmdData   = BuildGuiReportPlanStatus(cmdStatus);
                string cmd = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }

            case BackupOperationStatus.ScanningFilesFinished:
            {
                logger.Info("Scanning files finished.");

                // Report
                Commands.OperationStatus     cmdStatus = Commands.OperationStatus.SCANNING_FILES_FINISHED;
                Commands.GuiReportPlanStatus cmdData   = BuildGuiReportPlanStatus(cmdStatus);
                string cmd = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }

            case BackupOperationStatus.ProcessingFilesStarted:
            {
                logger.Info("Processing files...");

                // Report
                Commands.OperationStatus     cmdStatus = Commands.OperationStatus.PROCESSING_FILES_STARTED;
                Commands.GuiReportPlanStatus cmdData   = BuildGuiReportPlanStatus(cmdStatus);
                string cmd = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }

            case BackupOperationStatus.ProcessingFilesFinished:
            {
                logger.Info("Processing files finished.");
                logger.Info("Completed: {0} of {1}", report.TransferResults.Stats.Completed, report.TransferResults.Stats.Total);

                // Report
                Commands.OperationStatus cmdStatus = Commands.OperationStatus.PROCESSING_FILES_FINISHED;
                // Report sources
                Commands.GuiReportPlanStatus cmdData1 = BuildGuiReportPlanStatus(cmdStatus);
                string cmd1 = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData1);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd1);
                // Report counts
                Commands.GuiReportPlanProgress cmdData2 = BuildGuiReportPlanProgress(cmdStatus);
                string cmd2 = Commands.GuiReportOperationProgress("backup", plan.Id.Value, cmdData2);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd2);
                break;
            }

            case BackupOperationStatus.Finished:
            {
                //var message = string.Format(
                //	"Backup {0}! Stats: {1} completed, {2} failed, {3} canceled, {4} pending, {5} running",
                //	"finished",
                //	TransferResults.Stats.Completed, TransferResults.Stats.Failed,
                //	TransferResults.Stats.Canceled, TransferResults.Stats.Pending,
                //	TransferResults.Stats.Running);
                //logger.Info(message);

                // Update success timestamp.
                plan.LastSuccessfulRunAt = DateTime.UtcNow;
                _daoBackupPlan.Update(plan);

                // Signal to the other thread it may terminate.
                RunningOperationEndedEvent.Set();

                // Report
                Commands.OperationStatus     cmdStatus = Commands.OperationStatus.FINISHED;
                Commands.GuiReportPlanStatus cmdData   = BuildGuiReportPlanStatus(cmdStatus);
                string cmd = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }

            case BackupOperationStatus.Updated:
            {
                if (xferStatus == TransferStatus.COMPLETED || xferStatus == TransferStatus.CANCELED || xferStatus == TransferStatus.FAILED)
                {
                    logger.Info("Completed: {0} of {1}", report.TransferResults.Stats.Completed, report.TransferResults.Stats.Total);
                }

                // Report
                Commands.OperationStatus       cmdStatus = Commands.OperationStatus.UPDATED;
                Commands.GuiReportPlanProgress cmdData   = BuildGuiReportPlanProgress(cmdStatus);
                string cmd = Commands.GuiReportOperationProgress("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }

            case BackupOperationStatus.Failed:
            case BackupOperationStatus.Canceled:
            {
                //var message = string.Format(
                //	"Backup {0}! Stats: {1} completed, {2} failed, {3} canceled, {4} pending, {5} running",
                //	status == BackupOperationStatus.Failed ? "failed" : "was canceled",
                //	TransferResults.Stats.Completed, TransferResults.Stats.Failed,
                //	TransferResults.Stats.Canceled, TransferResults.Stats.Pending,
                //	TransferResults.Stats.Running);
                //logger.Info(message);

                // Signal to the other thread it may terminate.
                RunningOperationEndedEvent.Set();

                // Report
                Commands.OperationStatus cmdStatus = status == BackupOperationStatus.Failed
                                                        ? Commands.OperationStatus.FAILED : Commands.OperationStatus.CANCELED;
                Commands.GuiReportPlanStatus cmdData = BuildGuiReportPlanStatus(cmdStatus);
                string cmd = Commands.GuiReportOperationStatus("backup", plan.Id.Value, cmdData);
                Handler.Route(Commands.IPC_DEFAULT_GUI_CLIENT_NAME, cmd);
                break;
            }
            }
        }
 public static int CleanBackup()
 {
     return(BackupOperation.CleanBackup(Program.InfoPath));
 }