public static bool SaveCodeReview(ref SqlSyncBuildData buildData, ref SqlSyncBuildData.ScriptRow scriptRow, string scriptText, string comment, string reviewBy, DateTime reviewDate, string reviewNumber, int reviewStatus)
        {
            try
            {
                SqlSyncBuildData.CodeReviewRow newRow = buildData.CodeReview.NewCodeReviewRow();
                newRow.CodeReviewId = Guid.NewGuid();
                newRow.Comment      = comment;
                newRow.ReviewBy     = reviewBy;
                newRow.ReviewDate   = reviewDate;
                newRow.ReviewNumber = reviewNumber;
                newRow.ReviewStatus = (short)reviewStatus;
                newRow.CheckSum     = CodeReviewManager.CalculateReviewCheckSum(newRow.CodeReviewId,
                                                                                newRow.ReviewBy,
                                                                                newRow.ReviewDate,
                                                                                newRow.Comment,
                                                                                newRow.ReviewNumber,
                                                                                newRow.ReviewStatus,
                                                                                scriptText);

                newRow.SetParentRow(scriptRow);
                CodeReviewManager.SetValidationKey(ref newRow);
                buildData.CodeReview.AddCodeReviewRow(newRow);
                buildData.CodeReview.AcceptChanges();

                CodeReviewManager.SaveCodeReviewToDatabase(newRow);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public void AddPreRunScript(ref SqlSyncBuildData data, bool multipleRun)
        {
            SqlSyncBuildData.ScriptRow row = data.Script.NewScriptRow();
            row.AllowMultipleRuns  = multipleRun;
            row.BuildOrder         = 1;
            row.CausesBuildFailure = true;
            row.Database           = testDatabaseNames[0];
            row.DateAdded          = testTimeStamp;
            string fileName = this.GetTrulyUniqueFile();

            row.FileName             = fileName;
            row.RollBackOnError      = true;
            row.StripTransactionText = true;
            row.Description          = "Test Script to be skipped";
            row.AddedBy  = "UnitTest";
            row.ScriptId = PreRunScriptGuid;
            row.SetParentRow(data.Scripts[0]);
            data.Script.AddScriptRow(row);
            data.Script.AcceptChanges();
            string script = "INSERT INTO TransactionTest (Message, Guid, DateTimeStamp) VALUES ('INSERT TEST','" + testGuid + "','" + testTimeStamp.ToString() + "')";

            File.WriteAllText(fileName, script);

            InsertPreRunScriptEntry();
        }
Esempio n. 3
0
 public PolicyMessage(string scriptName, string policyType, bool passed, string message, SqlSyncBuildData.ScriptRow scriptRow)
 {
     this.ScriptName = scriptName;
     this.PolicyType = policyType;
     this.Passed     = passed;
     this.Message    = message;
     this.ScriptRow  = scriptRow;
 }
        public void CalculateBuildPackageSHA1_CompareMethodologyTest()
        {
            //Set up directory and files...
            string projectFileExtractionPath = Path.GetTempPath() + Guid.NewGuid().ToString() + "\\";

            if (!Directory.Exists(projectFileExtractionPath))
            {
                Directory.CreateDirectory(projectFileExtractionPath);
            }

            string file1 = "File1.sql";

            File.WriteAllText(projectFileExtractionPath + file1, Properties.Resources.CreateDatabaseScript);

            string file2 = "File2.sql";

            File.WriteAllText(projectFileExtractionPath + file2, Properties.Resources.CreateTestTablesScript);

            string file3 = "File3.sql";

            File.WriteAllText(projectFileExtractionPath + file3, Properties.Resources.LoggingTable);


            SqlSyncBuildData buildData = SqlBuildFileHelper.CreateShellSqlSyncBuildDataObject();

            SqlSyncBuildData.ScriptRow row1 = buildData.Script.NewScriptRow();
            row1.BuildOrder           = 1;
            row1.FileName             = file1;
            row1.StripTransactionText = true;

            SqlSyncBuildData.ScriptRow row2 = buildData.Script.NewScriptRow();
            row2.BuildOrder           = 2;
            row2.FileName             = file2;
            row2.StripTransactionText = true;

            SqlSyncBuildData.ScriptRow row3 = buildData.Script.NewScriptRow();
            row3.BuildOrder           = 3;
            row3.FileName             = file3;
            row3.StripTransactionText = true;

            buildData.Script.Rows.Add(row1);
            buildData.Script.Rows.Add(row2);
            buildData.Script.Rows.Add(row3);


            string fromPath = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);


            ScriptBatchCollection batch = SqlBuildHelper.LoadAndBatchSqlScripts(buildData, projectFileExtractionPath);
            string fromBatch            = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromBatchCollection(batch);

            if (Directory.Exists(projectFileExtractionPath))
            {
                Directory.Delete(projectFileExtractionPath, true);
            }

            Assert.AreEqual(fromPath, fromBatch);
        }
        public void CalculateBuildPackageSHA1SignatureFromPathTest_GetHashSuccessfully()
        {
            //Set up directory and files...
            string projectFileExtractionPath = Path.GetTempPath() + Guid.NewGuid().ToString() + "\\";

            if (!Directory.Exists(projectFileExtractionPath))
            {
                Directory.CreateDirectory(projectFileExtractionPath);
            }

            string file1 = "File1.sql";

            File.WriteAllText(projectFileExtractionPath + file1, Properties.Resources.CreateDatabaseScript);

            string file2 = "File2.sql";

            File.WriteAllText(projectFileExtractionPath + file2, Properties.Resources.CreateTestTablesScript);

            string file3 = "File3.sql";

            File.WriteAllText(projectFileExtractionPath + file3, Properties.Resources.LoggingTable);


            SqlSyncBuildData buildData = SqlBuildFileHelper.CreateShellSqlSyncBuildDataObject();

            SqlSyncBuildData.ScriptRow row1 = buildData.Script.NewScriptRow();
            row1.BuildOrder = 1;
            row1.FileName   = file1;

            SqlSyncBuildData.ScriptRow row2 = buildData.Script.NewScriptRow();
            row2.BuildOrder = 2;
            row2.FileName   = file2;

            SqlSyncBuildData.ScriptRow row3 = buildData.Script.NewScriptRow();
            row3.BuildOrder = 3;
            row3.FileName   = file3;

            buildData.Script.Rows.Add(row1);
            buildData.Script.Rows.Add(row2);
            buildData.Script.Rows.Add(row3);

            string expected = "4E0F54A4BA40DC62A78822B20C7D83713CE4F766";
            string actual;

            actual = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            if (Directory.Exists(projectFileExtractionPath))
            {
                Directory.Delete(projectFileExtractionPath, true);
            }

            Assert.AreEqual(expected, actual);
        }
Esempio n. 6
0
        private void removeSelectedScriptsFromTheLeftFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TODO: finish real delete!
            if (lstFiles.SelectedItems.Count == 0)
            {
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            StringBuilder sb = new StringBuilder("Are you sure you want to remove the follow file(s)?\r\n\r\n");;

            for (int i = 0; i < lstFiles.SelectedItems.Count; i++)
            {
                sb.Append("  " + ((FileCompareResults)lstFiles.SelectedItems[i].Tag).LeftScriptRow.FileName + "\r\n");
            }


            if (DialogResult.No == MessageBox.Show(sb.ToString(), "Delete Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                this.Cursor = Cursors.Default;
                return;
            }


            //Get list of rows to remove then remove them.
            SqlSyncBuildData.ScriptRow[] rows = new SqlSyncBuildData.ScriptRow[lstFiles.SelectedItems.Count];
            for (int i = 0; i < lstFiles.SelectedItems.Count; i++)
            {
                FileCompareResults results = (FileCompareResults)lstFiles.SelectedItems[i].Tag;
                rows[i] = results.LeftScriptRow;
            }
            //TODO: Check for delete from an SBX file
            if (!SqlBuildFileHelper.RemoveScriptFilesFromBuild(ref this.buildData, Path.Combine(this.leftTempFilePath, XmlFileNames.MainProjectFile), this.leftZipFilePath, rows, true))
            {
                MessageBox.Show("Unable to remove file from list. Please try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            if (lstFiles.SelectedItems.Count > 0)
            {
                this.refreshProjectList = true;
            }


            btnCompare_Click(null, EventArgs.Empty);

            this.Cursor = Cursors.Default;
        }
Esempio n. 7
0
        internal void BindData(ref SqlSyncBuildData buildData, ref SqlSyncBuildData.ScriptRow scriptRow, string scriptText, string lastEditor)
        {
            this.startingScriptText = scriptText;

            //Can't create a new review for yourself unless you are a "SelfReviewer"
            var isSelfReviewer = from s in EnterpriseConfigHelper.EnterpriseConfig.CodeReviewConfig.SelfReviewer
                                 where s.LoginId.ToLower() == lastEditor.ToLower()
                                 select s.LoginId;

            if ((lastEditor.Length == 0 || lastEditor.Trim().ToLower() == System.Environment.UserName.ToLower().Trim()) && !isSelfReviewer.Any())
            {
                this.Height = collapsedHeight;
                this.tblPanel.Controls.Clear();
                if (lastEditor.Length > 0)
                {
                    lblLastEditor.Visible = true;
                }
            }


            this.scriptRow = scriptRow;
            this.buildData = buildData;

            SqlSyncBuildData.CodeReviewRow[] rows = scriptRow.GetCodeReviewRows();
            if (rows != null && rows.Length > 0)
            {
                var sorted = from r in rows
                             orderby r.ReviewDate descending
                             select r;

                foreach (SqlSyncBuildData.CodeReviewRow row in sorted)
                {
                    if (!CodeReviewManager.ValidateReviewCheckSum(row, scriptText))
                    {
                        row.ReviewStatus = (short)CodeReviewStatus.OutOfDate;;
                        this.buildData.AcceptChanges();
                    }

                    CodeReviewItemControl itemCtrl = new CodeReviewItemControl(row);
                    itemCtrl.Dock = DockStyle.Fill;
                    this.tblPanel.Controls.Add(itemCtrl);
                    this.Height = this.Height + itemCtrl.Height + 7;
                }
            }
            this.fullHeight = this.Height;
        }
        public void AddScriptWithBadDatabase(ref SqlSyncBuildData data)
        {
            SqlSyncBuildData.ScriptRow row = data.Script.NewScriptRow();
            row.AllowMultipleRuns  = true;
            row.BuildOrder         = 1;
            row.CausesBuildFailure = true;
            row.Database           = "REALLY_BAD_DATABASE";
            row.DateAdded          = testTimeStamp;
            string fileName = this.GetTrulyUniqueFile();

            row.FileName             = fileName;
            row.RollBackOnError      = true;
            row.StripTransactionText = true;
            row.Description          = "Test Script that has an invalid database name";
            row.AddedBy  = "UnitTest";
            row.ScriptId = Guid.NewGuid().ToString();
            row.SetParentRow(data.Scripts[0]);
            data.Script.AddScriptRow(row);
            data.Script.AcceptChanges();
            string script = "INSERT INTO TransactionTest (Message, Guid, DateTimeStamp) VALUES ('INSERT TEST','" + testGuid + "','" + testTimeStamp.ToString() + "')";

            File.WriteAllText(fileName, script);
        }
        public void AddFailureScript(ref SqlSyncBuildData data, bool rollBackOnError, bool causeBuildFailure)
        {
            SqlSyncBuildData.ScriptRow row = data.Script.NewScriptRow();
            row.AllowMultipleRuns  = true;
            row.BuildOrder         = 10;
            row.CausesBuildFailure = causeBuildFailure;
            row.Database           = testDatabaseNames[0];
            row.DateAdded          = testTimeStamp;
            string fileName = this.GetTrulyUniqueFile();

            row.FileName             = fileName;
            row.RollBackOnError      = rollBackOnError;
            row.StripTransactionText = true;
            row.Description          = "Test Script to cause a failure when inserting into TransactionTest table";
            row.AddedBy  = "UnitTest";
            row.ScriptId = Guid.NewGuid().ToString();
            row.SetParentRow(data.Scripts[0]);
            data.Script.AddScriptRow(row);
            data.Script.AcceptChanges();
            string script = "INSERT INTO TransactionTest (INVALID, Guid, DateTimeStamp) VALUES ('INSERT TEST','" + testGuid + "','" + testTimeStamp.ToString() + "')";

            File.WriteAllText(fileName, script);
        }
Esempio n. 10
0
        public void AddSelectScript(ref SqlSyncBuildData data)
        {
            SqlSyncBuildData.ScriptRow row = data.Script.NewScriptRow();
            row.AllowMultipleRuns  = true;
            row.BuildOrder         = 1;
            row.CausesBuildFailure = true;
            row.Database           = testDatabaseNames[0];
            row.DateAdded          = testTimeStamp;
            string fileName = this.GetTrulyUniqueFile();

            row.FileName             = fileName;
            row.RollBackOnError      = true;
            row.StripTransactionText = true;
            row.Description          = "Test Script to successfully select from TransactionTest table";
            row.AddedBy  = "UnitTest";
            row.ScriptId = Guid.NewGuid().ToString();
            row.SetParentRow(data.Scripts[0]);
            data.Script.AddScriptRow(row);
            data.Script.AcceptChanges();
            string script = "SELECT * FROM TransactionTest";

            File.WriteAllText(fileName, script);
        }
Esempio n. 11
0
        public void AddScriptForProcessBuild(ref SqlSyncBuildData data, bool multipleRun, int scriptTimeout)
        {
            SqlSyncBuildData.ScriptRow row = data.Script.NewScriptRow();
            row.AllowMultipleRuns  = multipleRun;
            row.BuildOrder         = 1;
            row.CausesBuildFailure = true;
            row.Database           = testDatabaseNames[0];
            row.DateAdded          = testTimeStamp;
            row.ScriptTimeOut      = scriptTimeout;
            string fileName = this.GetTrulyUniqueFile();

            row.FileName             = fileName;
            row.RollBackOnError      = true;
            row.StripTransactionText = true;
            row.Description          = "Test Script to successfully insert into TransactionTest table";
            row.AddedBy  = "UnitTest";
            row.ScriptId = "59F8CBCA-3FE5-4142-ACB0-3D1D2C25184D"; //Must match GUID from GetScriptBatchCollectionForProcessBuild()
            row.SetParentRow(data.Scripts[0]);
            data.Script.AddScriptRow(row);
            data.Script.AcceptChanges();
            string script = "INSERT INTO TransactionTest (Message, Guid, DateTimeStamp) VALUES ('INSERT TEST','" + testGuid + "','" + testTimeStamp.ToString() + "')";

            File.WriteAllText(fileName, script);
        }
Esempio n. 12
0
        public static ScriptStatusType DetermineScriptRunStatus(SqlSyncBuildData.ScriptRow row, ConnectionData connData, string projectFilePath, bool checkForChanges, List <DatabaseOverride> overrides, out DateTime commitDate, out DateTime serverChangeDate)
        {
            string targetDatabase = ConnectionHelper.GetTargetDatabase(row.Database, overrides);

            //Update the routine (sp and functions) change date cache
            if (DatabaseObjectChangeDates.Servers[connData.SQLServerName][targetDatabase].LastRefreshTime < DateTime.Now.AddSeconds(-30))
            {
                //InfoHelper.DatabaseRoutineChangeDates = InfoHelper.GetRoutineChangeDates(connData, this.targetDatabaseOverrideCtrl1.GetOverrideData());
                InfoHelper.UpdateRoutineAndViewChangeDates(connData, overrides);
            }
            bool preRun      = false;
            bool hashChanged = false;
            //Determine icon
            string scriptHash     = string.Empty;
            string scriptTextHash = string.Empty;

            commitDate       = DateTime.MinValue;
            serverChangeDate = DateTime.MinValue;
            // preRun = (committedScriptView.Find(row.ScriptId) > -1 || helper.HasBlockingSqlLog(new Guid(row.ScriptId), this.data, targetDatabase, out scriptHash, out scriptTextHash) == true);
            preRun = (SqlBuildHelper.HasBlockingSqlLog(new Guid(row.ScriptId), connData, targetDatabase, out scriptHash, out scriptTextHash, out commitDate) == true);
            //Check that the file exists
            if (!File.Exists(Path.Combine(projectFilePath, row.FileName)))
            {
                return(ScriptStatusType.FileMissing);
            }

            //Get the latest hash from the Db only (don't care if the build file is out of date!)
            if (preRun && checkForChanges)
            {
                if (scriptHash == string.Empty || scriptTextHash == string.Empty)
                {
                    SqlBuildHelper.HasBlockingSqlLog(new Guid(row.ScriptId), connData, targetDatabase, out scriptHash, out scriptTextHash, out commitDate);
                }

                /*If the scriptHash is STILL empty, then the file and the Db are out of sync.
                 *	This could be due to a Db refresh, in which case we'll mark it as changed
                 *	by default
                 */
                if (scriptHash != string.Empty || scriptTextHash != string.Empty)
                {
                    string fileTextHash;
                    string fileHash;
                    SqlBuildFileHelper.GetSHA1Hash(Path.Combine(projectFilePath, row.FileName), out fileHash, out fileTextHash, row.StripTransactionText);
                    if (fileHash != scriptHash && fileTextHash != scriptHash && fileHash != scriptTextHash && fileTextHash != scriptTextHash)
                    {
                        if (fileHash == SqlBuildFileHelper.FileMissing)
                        {
                            return(ScriptStatusType.FileMissing);
                        }
                        hashChanged = true;
                    }
                }
                else
                {
                    hashChanged = true;
                }
            }
            string routineName = row.FileName.Substring(0, row.FileName.Length - 4).ToLower();

            if (row.FileName.EndsWith(DbObjectType.Trigger, StringComparison.CurrentCultureIgnoreCase) && routineName.IndexOf(" - ") > -1)
            {
                routineName = routineName.Split(new char[] { '-' })[1].Trim();
            }

            if (!preRun) //not run at all
            {
                commitDate = (row.IsDateModifiedNull() || row.DateModified < new DateTime(1980, 1, 1)) ? row.DateAdded : row.DateModified;

                if (row.FileName.EndsWith(DbObjectType.StoredProcedure, StringComparison.CurrentCultureIgnoreCase) ||
                    row.FileName.EndsWith(DbObjectType.UserDefinedFunction, StringComparison.CurrentCultureIgnoreCase) ||
                    row.FileName.EndsWith(DbObjectType.View, StringComparison.CurrentCultureIgnoreCase) ||
                    row.FileName.EndsWith(DbObjectType.Table, StringComparison.CurrentCultureIgnoreCase) ||
                    row.FileName.EndsWith(DbObjectType.Trigger, StringComparison.CurrentCultureIgnoreCase))
                {
                    serverChangeDate = DatabaseObjectChangeDates.Servers[connData.SQLServerName][targetDatabase][routineName];

                    if (commitDate < serverChangeDate)
                    {
                        return(ScriptStatusType.NotRunButOlderVersion); // question mark
                    }
                }

                return(ScriptStatusType.NotRun);
            }
            else
            {
                if (row.AllowMultipleRuns == false) //(committedScriptView.Find(row.ScriptId) > -1 || helper.HasBlockingSqlLog(new Guid(row.ScriptId),this.data,row.Database) == true))
                {
                    if (!hashChanged)
                    {
                        return(ScriptStatusType.Locked); // "locked"
                    }
                    else
                    {
                        return(ScriptStatusType.ChangedSinceCommit); //the caution icon!
                    }
                }
                else
                {
                    if (!hashChanged) //if "OK" from a SBM status, need to check the DB next for SP's and Functions
                    {
                        if (row.FileName.EndsWith(DbObjectType.StoredProcedure, StringComparison.CurrentCultureIgnoreCase) ||
                            row.FileName.EndsWith(DbObjectType.UserDefinedFunction, StringComparison.CurrentCultureIgnoreCase) ||
                            row.FileName.EndsWith(DbObjectType.View, StringComparison.CurrentCultureIgnoreCase) ||
                            row.FileName.EndsWith(DbObjectType.Table, StringComparison.CurrentCultureIgnoreCase) ||
                            row.FileName.EndsWith(DbObjectType.Trigger, StringComparison.CurrentCultureIgnoreCase))
                        {
                            serverChangeDate = DatabaseObjectChangeDates.Servers[connData.SQLServerName][targetDatabase][routineName];

                            //Add in 5 second threshold
                            if (commitDate.Ticks + 50000000 < serverChangeDate.Ticks)
                            {
                                return(ScriptStatusType.ServerChange); // magnifying glass
                            }
                            //if the serverChangeDate here is MinValue, it means that the routine is not in this DB, therefore, we need to set as not run.
                            if (serverChangeDate == DateTime.MinValue)
                            {
                                return(ScriptStatusType.NotRun); //"gray server icon"
                            }
                        }
                        return(ScriptStatusType.UpToDate); //green "OK"
                    }
                    else
                    {
                        return(ScriptStatusType.ChangedSinceCommit); //the caution icon!
                    }
                }
            }
        }
        public void CalculateBuildPackageSHA1_CompareMethodologyTest_OrderCheckingWithTransactionsToRemove()
        {
            //Set up directory and files...
            string projectFileExtractionPath = Path.GetTempPath() + Guid.NewGuid().ToString() + "\\";

            if (!Directory.Exists(projectFileExtractionPath))
            {
                Directory.CreateDirectory(projectFileExtractionPath);
            }

            string file1 = "File1.sql";

            File.WriteAllText(projectFileExtractionPath + file1, @"This is My script
with my 
COMMIT TRANS
test");

            string file2 = "File2.sql";

            File.WriteAllText(projectFileExtractionPath + file2, Properties.Resources.CreateTestTablesScript);

            string file3 = "File3.sql";

            File.WriteAllText(projectFileExtractionPath + file3, @"This is another test that has
--ROLLBACK TRANSACTION
where the 
BEGIN TRAN
needs to be removed");


            SqlSyncBuildData buildData = SqlBuildFileHelper.CreateShellSqlSyncBuildDataObject();

            SqlSyncBuildData.ScriptRow row1 = buildData.Script.NewScriptRow();
            row1.BuildOrder           = 1;
            row1.FileName             = file1;
            row1.StripTransactionText = true;

            SqlSyncBuildData.ScriptRow row2 = buildData.Script.NewScriptRow();
            row2.BuildOrder           = 2;
            row2.FileName             = file2;
            row2.StripTransactionText = true;

            SqlSyncBuildData.ScriptRow row3 = buildData.Script.NewScriptRow();
            row3.BuildOrder           = 3;
            row3.FileName             = file3;
            row3.StripTransactionText = true;

            buildData.Script.Rows.Add(row1);
            buildData.Script.Rows.Add(row2);
            buildData.Script.Rows.Add(row3);


            string fromPath123 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            ScriptBatchCollection batch = SqlBuildHelper.LoadAndBatchSqlScripts(buildData, projectFileExtractionPath);
            string fromBatch123         = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromBatchCollection(batch);

            buildData.Script[0].BuildOrder = 2;
            buildData.Script[1].BuildOrder = 1;
            buildData.Script[2].BuildOrder = 3;
            buildData.AcceptChanges();

            string fromPath213 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            batch = SqlBuildHelper.LoadAndBatchSqlScripts(buildData, projectFileExtractionPath);
            string fromBatch213 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromBatchCollection(batch);


            if (Directory.Exists(projectFileExtractionPath))
            {
                Directory.Delete(projectFileExtractionPath, true);
            }

            Assert.AreEqual(fromPath123, fromBatch123);
            Assert.AreEqual(fromPath213, fromBatch213);
            Assert.AreNotEqual(fromPath123, fromBatch213);
            Assert.AreNotEqual(fromPath213, fromBatch123);
        }
        public void CalculateBuildPackageSHA1SignatureFromPathTest_BuildOrderSwitch()
        {
            //Set up directory and files...
            string projectFileExtractionPath = Path.GetTempPath() + Guid.NewGuid().ToString() + "\\";

            if (!Directory.Exists(projectFileExtractionPath))
            {
                Directory.CreateDirectory(projectFileExtractionPath);
            }

            string file1 = "File1.sql";

            File.WriteAllText(projectFileExtractionPath + file1, Properties.Resources.CreateDatabaseScript);

            string file2 = "File2.sql";

            File.WriteAllText(projectFileExtractionPath + file2, Properties.Resources.CreateTestTablesScript);

            string file3 = "File3.sql";

            File.WriteAllText(projectFileExtractionPath + file3, Properties.Resources.LoggingTable);


            SqlSyncBuildData buildData = SqlBuildFileHelper.CreateShellSqlSyncBuildDataObject();

            SqlSyncBuildData.ScriptRow row1 = buildData.Script.NewScriptRow();
            row1.BuildOrder = 1;
            row1.FileName   = file1;

            SqlSyncBuildData.ScriptRow row2 = buildData.Script.NewScriptRow();
            row2.BuildOrder = 2;
            row2.FileName   = file2;

            SqlSyncBuildData.ScriptRow row3 = buildData.Script.NewScriptRow();
            row3.BuildOrder = 3;
            row3.FileName   = file3;

            buildData.Script.Rows.Add(row1);
            buildData.Script.Rows.Add(row2);
            buildData.Script.Rows.Add(row3);

            string order123 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            buildData.Script[0].BuildOrder = 1;
            buildData.Script[1].BuildOrder = 3;
            buildData.Script[2].BuildOrder = 2;
            buildData.AcceptChanges();

            string order132 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            buildData.Script[0].BuildOrder = 2;
            buildData.Script[1].BuildOrder = 1;
            buildData.Script[2].BuildOrder = 3;
            buildData.AcceptChanges();

            string order213 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            buildData.Script[0].BuildOrder = 2;
            buildData.Script[1].BuildOrder = 3;
            buildData.Script[2].BuildOrder = 1;
            buildData.AcceptChanges();

            string order231 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            buildData.Script[0].BuildOrder = 3;
            buildData.Script[1].BuildOrder = 1;
            buildData.Script[2].BuildOrder = 2;
            buildData.AcceptChanges();

            string order312 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            buildData.Script[0].BuildOrder = 3;
            buildData.Script[1].BuildOrder = 2;
            buildData.Script[2].BuildOrder = 1;
            buildData.AcceptChanges();

            string order321 = SqlBuildFileHelper.CalculateBuildPackageSHA1SignatureFromPath(projectFileExtractionPath, buildData);

            if (Directory.Exists(projectFileExtractionPath))
            {
                Directory.Delete(projectFileExtractionPath, true);
            }

            Assert.AreNotEqual(order123, order132);
            Assert.AreNotEqual(order123, order213);
            Assert.AreNotEqual(order123, order231);
            Assert.AreNotEqual(order123, order312);
            Assert.AreNotEqual(order312, order321);

            Assert.AreNotEqual(order132, order213);
            Assert.AreNotEqual(order132, order231);
            Assert.AreNotEqual(order132, order312);
            Assert.AreNotEqual(order132, order321);

            Assert.AreNotEqual(order213, order231);
            Assert.AreNotEqual(order213, order312);
            Assert.AreNotEqual(order213, order321);

            Assert.AreNotEqual(order231, order312);
            Assert.AreNotEqual(order231, order321);

            Assert.AreNotEqual(order231, order321);
        }
Esempio n. 15
0
 public ScriptSelectedEventArgs(SqlSyncBuildData.ScriptRow selectedRow)
 {
     this.SelectedRow = selectedRow;
 }
Esempio n. 16
0
        public static bool CreateBackoutPackage(ConnectionData connData,
                                                List <SqlBuild.Objects.ObjectUpdates> objectUpdates,
                                                List <SqlBuild.Objects.ObjectUpdates> dontUpdate,
                                                List <string> manualScriptsCanNotUpdate, string sourceBuildZipFileName,
                                                string destinationBuildZipFileName, string sourceServer, string sourceDb,
                                                bool removeNewObjectsFromPackage, bool markManualScriptsAsRunOnce,
                                                bool dropNewRoutines, ref BackgroundWorker bg)
        {
            //Copy the source straight over...
            bool reportProgress = false;

            if (bg != null && bg.WorkerReportsProgress)
            {
                reportProgress = true;
                bg.ReportProgress(-1, "Copying package to destination...");
            }

            if (!CopyOriginalToBackout(sourceBuildZipFileName, destinationBuildZipFileName))
            {
                return(false);
            }

            //init working location for destination backout package
            string workingDir      = string.Empty;
            string projectPath     = string.Empty;
            string projectFileName = string.Empty;

            SqlBuildFileHelper.InitilizeWorkingDirectory(ref workingDir, ref projectPath, ref projectFileName);
            string message = $"Initialized working directory {workingDir}";

            log.LogDebug(message);
            if (reportProgress)
            {
                bg.ReportProgress(-1, "Initialized working directory");
            }


            //Extract destination package into working folder
            string result;
            bool   success = SqlBuildFileHelper.ExtractSqlBuildZipFile(destinationBuildZipFileName, ref workingDir,
                                                                       ref projectPath, ref projectFileName, out result);

            if (success)
            {
                log.LogDebug($"Successfully extracted build file {destinationBuildZipFileName} to {workingDir}");
            }
            else
            {
                log.LogError("Unable to proceed with Backout package. See previous errors");
                return(false);
            }

            //Load the build data
            SqlSyncBuildData buildData;

            if (reportProgress)
            {
                bg.ReportProgress(-1, "Loading project file for modification.");
            }
            bool successfulLoad = SqlBuildFileHelper.LoadSqlBuildProjectFile(out buildData, projectFileName, false);

            if (!successfulLoad)
            {
                log.LogError("Unable to load SBM project data");
                return(false);
            }

            ConnectionData tmpData = new ConnectionData();

            tmpData.DatabaseName       = sourceDb;
            tmpData.SQLServerName      = sourceServer;
            tmpData.Password           = connData.Password;
            tmpData.UserId             = connData.UserId;
            tmpData.AuthenticationType = connData.AuthenticationType;
            ObjectScriptHelper helper = new ObjectScriptHelper(tmpData);


            //Get the updated scripts...
            if (reportProgress)
            {
                bg.ReportProgress(-1, "Generating updated scripts.");
            }
            List <UpdatedObject> lstScripts = ObjectScriptHelper.ScriptDatabaseObjects(objectUpdates, tmpData, ref bg);

            //Log if some scripts were not updated properly...
            var notUpdated = from s in objectUpdates
                             where !(from u in lstScripts select s.ShortFileName).Contains(s.ShortFileName)
                             select s.ShortFileName;

            if (notUpdated.Any())
            {
                foreach (string file in notUpdated)
                {
                    log.LogError($"Unable to create new script for {file}");
                }

                return(false);
            }

            if (lstScripts.Count() != objectUpdates.Count())
            {
                log.LogError($"Not all scripts were updated. Expected {lstScripts.Count().ToString()}, only {objectUpdates.Count().ToString()} were updated");
                return(false);
            }

            //Save the updated scripts...
            DateTime updateTime   = DateTime.Now;
            bool     errorWriting = false;

            if (lstScripts != null)
            {
                foreach (UpdatedObject obj in lstScripts)
                {
                    try
                    {
                        File.WriteAllText(projectPath + obj.ScriptName, obj.ScriptContents);

                        //Update the buildData object with the update date/time and user;
                        var sr = from r in buildData.Script
                                 where r.FileName == obj.ScriptName
                                 select r;

                        if (sr.Any())
                        {
                            SqlSyncBuildData.ScriptRow row = sr.First();
                            row.DateModified = updateTime;
                            row.ModifiedBy   = System.Environment.UserName;
                        }
                    }
                    catch (Exception exe)
                    {
                        errorWriting = true;
                        log.LogError(exe, $"Unable to save updated script file to {obj.ScriptName}");
                    }
                }
            }

            //Update new object scripts: either remove or mark as run once
            if (dontUpdate != null)
            {
                foreach (SqlBuild.Objects.ObjectUpdates obj in dontUpdate)
                {
                    try
                    {
                        //Update the buildData object with the update date/time and user;
                        var sr = from r in buildData.Script
                                 where r.FileName == obj.ShortFileName
                                 select r;

                        if (sr.Any())
                        {
                            SqlSyncBuildData.ScriptRow row = sr.First();
                            if (obj.ObjectType == DbScriptDescription.StoredProcedure ||
                                obj.ObjectType == DbScriptDescription.UserDefinedFunction ||
                                obj.ObjectType == DbScriptDescription.Trigger ||
                                obj.ObjectType == DbScriptDescription.View)
                            {
                                if (dropNewRoutines)
                                {
                                    string   schema, objName;
                                    string[] arr = obj.SourceObject.Split(new char[] { '.' });
                                    schema  = arr[0];
                                    objName = arr[1];

                                    string str = CreateRoutineDropScript(schema, objName, obj.ObjectType);
                                    File.WriteAllText(projectPath + "DROP " + row.FileName, str);
                                    row.FileName     = "DROP " + row.FileName;
                                    row.DateModified = updateTime;
                                    row.ModifiedBy   = System.Environment.UserName;
                                }
                                else
                                {
                                    row.AllowMultipleRuns = false;
                                    row.DateModified      = updateTime;
                                    row.ModifiedBy        = System.Environment.UserName;
                                }
                            }
                            else if (removeNewObjectsFromPackage)
                            {
                                buildData.Script.RemoveScriptRow(row);
                            }
                            else
                            {
                                row.AllowMultipleRuns = false;
                                row.DateModified      = updateTime;
                                row.ModifiedBy        = System.Environment.UserName;
                            }
                        }
                    }
                    catch (Exception exe)
                    {
                        errorWriting = true;
                        if (removeNewObjectsFromPackage)
                        {
                            log.LogError(exe, $"Unable to remove new object script '{obj.ShortFileName}' from package");
                        }
                        else
                        {
                            log.LogError(exe, $"Unable to mark new object script {obj.ShortFileName} as run once");
                        }
                    }
                }
            }

            //Mark non-updated scripts as run-once
            if (manualScriptsCanNotUpdate != null)
            {
                foreach (string scr in manualScriptsCanNotUpdate)
                {
                    try
                    {
                        //Update the buildData object with the update date/time and user;
                        var sr = from r in buildData.Script
                                 where r.FileName == scr
                                 select r;

                        if (sr.Any())
                        {
                            if (markManualScriptsAsRunOnce)
                            {
                                SqlSyncBuildData.ScriptRow row = sr.First();
                                if (row.BuildOrder < 1000)
                                {
                                    row.AllowMultipleRuns = false;
                                    row.DateModified      = updateTime;
                                    row.ModifiedBy        = System.Environment.UserName;
                                }
                            }
                        }
                    }
                    catch (Exception exe)
                    {
                        errorWriting = true;
                        log.LogError(exe, $"Unable to mark script {scr} as run once");
                    }
                }
            }


            if (errorWriting)
            {
                return(false);
            }
            if (reportProgress)
            {
                bg.ReportProgress(-1, "Saving backout package.");
            }

            buildData.AcceptChanges();
            SqlBuildFileHelper.SaveSqlBuildProjectFile(ref buildData, projectFileName, destinationBuildZipFileName);


            return(true);
        }