예제 #1
0
        internal static void ProcessValidationReport(IOutputWindow outputWindow, ValidationReporter validationReporter, bool showWarnings)
        {
            // Enumerate all validation messages and write to the output window.
            foreach (ValidationItem item in validationReporter.ValidationItemsList)
            {
                if (item.Severity == Severity.Error)
                {
                    outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, GetErrorId(item.ValidationCode), GetValidationReporterMessage(item), item.FilePath, item.Line, item.Offset);
                }
                else if (item.Severity == Severity.Warning)
                {
                    outputWindow.ReportStatusError(OutputWindowErrorSeverity.Warning, GetErrorId(item.ValidationCode), GetValidationReporterMessage(item), item.FilePath, item.Line, item.Offset);
                }
                else
                {
                    outputWindow.ReportStatusMessage(GetValidationReporterMessage(item));
                }
            }

            if (validationReporter.HasErrors || (showWarnings && validationReporter.HasWarnings))
            {
                // Display the modal form as well
                var form = new BimlValidationListForm(validationReporter, showWarnings);
                form.ShowDialog();
            }
        }
예제 #2
0
        internal static void ProcessValidationReport(IOutputWindow outputWindow, ValidationReporter validationReporter, bool showWarnings)
        {
            // Enumerate all validation messages and write to the output window.
            foreach (ValidationItem item in validationReporter.ValidationItemsList)
            {
                if (item.Severity == Severity.Error)
                {
                    outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, GetErrorId(item.ValidationCode), GetValidationReporterMessage(item), item.FilePath, item.Line, item.Offset);
                }
                else if (item.Severity == Severity.Warning)
                {
                    outputWindow.ReportStatusError(OutputWindowErrorSeverity.Warning, GetErrorId(item.ValidationCode), GetValidationReporterMessage(item), item.FilePath, item.Line, item.Offset);
                }
                else
                {
                    outputWindow.ReportStatusMessage(GetValidationReporterMessage(item));
                }
            }

            if (validationReporter.HasErrors || (showWarnings && validationReporter.HasWarnings))
            {
                // Display the modal form as well
                var form = new BimlValidationListForm(validationReporter, showWarnings);
                form.ShowDialog();
            }
        }
        private void ShowValidationItems(List <string> bimlScriptPaths, Project project, string projectDirectory)
        {
            var tempTargetDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                Directory.CreateDirectory(tempTargetDirectory);

                // Get the General output window, we use it to write out our BIML "compilation" messages
                this.ApplicationObject.ToolWindows.OutputWindow.Parent.SetFocus();
                IOutputWindowFactory service      = ((System.IServiceProvider)project).GetService(typeof(IOutputWindowFactory)) as IOutputWindowFactory;
                IOutputWindow        outputWindow = service.GetStandardOutputWindow(StandardOutputWindow.Build);
                outputWindow.Clear();
                outputWindow.ReportStatusMessage("Validating BIML");

                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Checking Biml for Errors", 1, 2);

                ValidationReporter validationReporter = BimlUtility.GetValidationReporter(bimlScriptPaths, project, projectDirectory, tempTargetDirectory);

                ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(false, "Checking Biml for Errors", 2, 2);

                // If we have no errors and no warnings, say so
                if (!validationReporter.HasErrors && !validationReporter.HasWarnings)
                {
                    // Write a closing message to the output window
                    outputWindow.ReportStatusMessage("No errors or warnings were found.");
                    outputWindow.ReportStatusMessage("BIML validation completed.");

                    // Show message to user
                    MessageBox.Show("No errors or warnings were found.", DefaultMessageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    // We have errors and/or warnings. Show both.
                    BimlUtility.ProcessValidationReport(outputWindow, validationReporter, true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                // Clean up the temporary directory and files, but supress any errors encountered
                try
                {
                    if (Directory.Exists(tempTargetDirectory))
                    {
                        Directory.Delete(tempTargetDirectory);
                    }
                }
                catch (Exception)
                {
                }

                try
                {
                    ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                    ApplicationObject.StatusBar.Progress(false, "Checking Biml for Errors", 2, 2);
                }
                catch { }
            }
        }
예제 #4
0
        public override void Exec()
        {
            if (MessageBox.Show("Are you sure you want to change any hardcoded paths pointing to files in the packages directory to relative paths?\r\n\r\nThis command impacts configurations and connection managers.", "BIDS Helper - Fix Relative Paths", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }

            try
            {
                this.ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationFind);
                this.ApplicationObject.StatusBar.Text = "Fixing relative paths...";

                EnvDTE.Project proj = GetSelectedProjectReference();
                Microsoft.DataWarehouse.Interfaces.IConfigurationSettings settings = (Microsoft.DataWarehouse.Interfaces.IConfigurationSettings)((System.IServiceProvider)proj).GetService(typeof(Microsoft.DataWarehouse.Interfaces.IConfigurationSettings));
                DataWarehouseProjectManager projectManager = (DataWarehouseProjectManager)settings.GetType().InvokeMember("ProjectManager", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.FlattenHierarchy, null, settings, null);

                this.ApplicationObject.ToolWindows.OutputWindow.Parent.SetFocus();
                IOutputWindowFactory service      = ((System.IServiceProvider)proj).GetService(typeof(IOutputWindowFactory)) as IOutputWindowFactory;
                IOutputWindow        outputWindow = service.GetStandardOutputWindow(StandardOutputWindow.Deploy);
                outputWindow.Activate();
                outputWindow.Clear();
                outputWindow.ReportStatusMessage("BIDS Helper is fixing relative paths in all open packages...\r\n");

                bool          bFoundOpenPackage = false;
                StringBuilder sb = new StringBuilder();
                string        sPackageDirectory = string.Empty;
                foreach (ProjectItem item in proj.ProjectItems)
                {
                    try
                    {
                        if (!item.get_IsOpen(BIDSViewKinds.Designer))
                        {
                            continue;
                        }
                    }
                    catch
                    {
                        continue;
                    }
                    if (!bFoundOpenPackage)
                    {
                        bFoundOpenPackage = true;

                        sPackageDirectory = System.IO.Path.GetDirectoryName(item.get_FileNames(0));
                        outputWindow.ReportStatusMessage("The current working directory is:");
                        outputWindow.ReportStatusMessage(System.IO.Directory.GetCurrentDirectory());
                        outputWindow.ReportStatusMessage(string.Empty);
                        outputWindow.ReportStatusMessage("The directory for the packages is:");
                        outputWindow.ReportStatusMessage(sPackageDirectory);
                        outputWindow.ReportStatusMessage(string.Empty);

                        if (string.Compare(sPackageDirectory, System.IO.Directory.GetCurrentDirectory(), true) != 0)
                        {
                            outputWindow.ReportStatusMessage("PROBLEM:");
                            outputWindow.ReportStatusMessage("Since the packages are not in the current working directory, no changes to configurations will be made. Please start Visual Studio by double clicking on the .sln file for the project, and make sure the .sln file is in the same directory as the packages.");
                            return;
                        }
                    }

                    Window w = item.Open(BIDSViewKinds.Designer); //opens the designer
                    w.Activate();

                    IDesignerHost designer = w.Object as IDesignerHost;
                    if (designer == null)
                    {
                        continue;
                    }
                    EditorWindow win     = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator));
                    Package      package = win.PropertiesLinkComponent as Package;
                    if (package == null)
                    {
                        continue;
                    }

                    outputWindow.ReportStatusMessage("Package " + item.Name);

                    #if DENALI || SQL2014
                    Cud.Transaction trans = Cud.BeginTransaction(package);
                    #endif

                    bool bChanged = false;
                    foreach (Microsoft.SqlServer.Dts.Runtime.Configuration config in package.Configurations)
                    {
                        if (config.ConfigurationType == DTSConfigurationType.ConfigFile)
                        {
                            if (string.Compare(System.IO.Path.GetDirectoryName(config.ConfigurationString), System.IO.Directory.GetCurrentDirectory(), true) == 0)
                            {
                                config.ConfigurationString = System.IO.Path.GetFileName(config.ConfigurationString);
                                outputWindow.ReportStatusMessage("  Configuration " + config.Name + " changed to relative path");
                                bChanged = true;

                                #if DENALI || SQL2014
                                trans.ChangeProperty(config, "ConfigurationString");
                                #endif
                            }
                        }
                    }
                    foreach (ConnectionManager conn in package.Connections)
                    {
                        if (string.IsNullOrEmpty(conn.GetExpression("ConnectionString")) && string.Compare(System.IO.Path.GetDirectoryName(conn.ConnectionString), System.IO.Directory.GetCurrentDirectory(), true) == 0)
                        {
                            conn.ConnectionString = System.IO.Path.GetFileName(conn.ConnectionString);
                            outputWindow.ReportStatusMessage("  Connection " + conn.Name + " changed to relative path");
                            bChanged = true;

                            #if DENALI || SQL2014
                            trans.ChangeProperty(conn, "ConnectionString");
                            #endif
                        }
                    }
                    if (bChanged)
                    {
                        SSISHelpers.MarkPackageDirty(package);
                    }
                    else
                    {
                        outputWindow.ReportStatusMessage("  No changes");
                    }
                }

                if (!bFoundOpenPackage)
                {
                    outputWindow.ReportStatusMessage("PROBLEM:");
                    outputWindow.ReportStatusMessage("No packages in this project were open.");
                    return;
                }

                outputWindow.Activate();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
            }
            finally
            {
                this.ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationFind);
                this.ApplicationObject.StatusBar.Text = string.Empty;
            }
        }
예제 #5
0
        private void DeployProject(Project proj, IOutputWindow outputWindow, System.Array selectedItems, bool bCreateBat)
        {
            Microsoft.DataWarehouse.Interfaces.IConfigurationSettings settings = (Microsoft.DataWarehouse.Interfaces.IConfigurationSettings)((System.IServiceProvider)proj).GetService(typeof(Microsoft.DataWarehouse.Interfaces.IConfigurationSettings));
            DataWarehouseProjectManager projectManager = (DataWarehouseProjectManager)settings.GetType().InvokeMember("ProjectManager", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.FlattenHierarchy, null, settings, null);

            StringBuilder sBatFileContents = new StringBuilder();
            try
            {
                string sConfigFileName = ((Microsoft.DataWarehouse.VsIntegration.Shell.Project.Extensibility.ProjectExt)proj).FullName + ".bidsHelper.user";
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                if (System.IO.File.Exists(sConfigFileName))
                {
                    doc.Load(sConfigFileName);
                }

#if SQL2014
                //refreshes the cached target version which is needed in GetPathToDtsExecutable below
                SSISHelpers.ProjectTargetVersion? projectTargetVersion = SSISHelpers.GetProjectTargetVersion(proj);
#endif

                IProjectConfiguration config = projectManager.ConfigurationManager.CurrentConfiguration;
                DtsProjectExtendedConfigurationOptions newOptions = new DtsProjectExtendedConfigurationOptions();
                LoadFromBidsHelperConfiguration(doc, config.DisplayName, newOptions);

                //print out header in output window
                if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                {
                    if (string.IsNullOrEmpty(newOptions.FilePath))
                    {
                        outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, "Deployment FilePath is not set. Right click on the project node and set the FilePath property.");
                        return;
                    }
                    outputWindow.ReportStatusMessage("Deploying to file path " + newOptions.FilePath + "\r\n");
                }
                else
                {
                    if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreMsdbDestination)
                    {
                        outputWindow.ReportStatusMessage("Deploying to SSIS Package Store MSDB on server " + newOptions.DestinationServer);
                    }
                    else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreFileSystemDestination)
                    {
                        outputWindow.ReportStatusMessage("Deploying to SSIS Package Store File System on server " + newOptions.DestinationServer);
                    }
                    else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SqlServerDestination)
                    {
                        outputWindow.ReportStatusMessage("Deploying to SQL Server MSDB on server: " + newOptions.DestinationServer);
                    }
                    if (!string.IsNullOrEmpty(newOptions.DestinationFolder))
                        outputWindow.ReportStatusMessage("Deploying to folder: " + newOptions.DestinationFolder);
                    outputWindow.ReportStatusMessage(string.Empty);
                }
                System.Windows.Forms.Application.DoEvents();

                //determine destination types and folders
                string sDestFolder = newOptions.DestinationFolder;
                sDestFolder = sDestFolder.Replace("/", "\\");
                if (!string.IsNullOrEmpty(sDestFolder) && !sDestFolder.EndsWith("\\")) sDestFolder += "\\";
                while (sDestFolder.StartsWith("\\"))
                    sDestFolder = sDestFolder.Substring(1);

                string sDestType = "SQL";
                if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreFileSystemDestination)
                {
                    sDestFolder = "File System\\" + sDestFolder;
                    sDestType = "DTS";
                }
                else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreMsdbDestination)
                {
                    sDestFolder = "MSDB\\" + sDestFolder;
                    sDestType = "DTS";
                }
                else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                {
                    string sDestinationPath = newOptions.FilePath;
                    if (!sDestinationPath.EndsWith("\\")) sDestinationPath += "\\";
                    if (!System.IO.Directory.Exists(sDestinationPath))
                        System.IO.Directory.CreateDirectory(sDestinationPath);
                    sDestFolder = sDestinationPath;
                    sBatFileContents.Append("mkdir \"").Append(sDestFolder).AppendLine("\"");
                }

                //setup Process object to call the dtutil EXE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = SSIS.PerformanceVisualization.PerformanceTab.GetPathToDtsExecutable("dtutil.exe", false); //makes the bat file less portable, but does workaround the problem if SSIS2005 and SSIS2008 are both installed... issue 21074

                if (newOptions.DeploymentType != DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                {
                    //create the directories
                    string sAccumulatingDir = "";
                    try
                    {
                        foreach (string dir in sDestFolder.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (!(string.IsNullOrEmpty(sAccumulatingDir) && sDestType == "DTS"))
                            {
                                process.StartInfo.Arguments = string.Format("/FCreate {0};{1};\"{2}\" /SourceServer {3} ", sDestType, (sAccumulatingDir == "" ? "\\" : "\"" + sAccumulatingDir + "\""), dir, newOptions.DestinationServer);
                                sBatFileContents.Append("\"").Append(process.StartInfo.FileName).Append("\" ").AppendLine(process.StartInfo.Arguments);
                                process.Start();
                                process.WaitForExit();
                            }
                            if (!string.IsNullOrEmpty(sAccumulatingDir))
                                sAccumulatingDir += "\\";
                            sAccumulatingDir += dir;
                        }
                    }
                    catch { }
                }

                //loop through each package to deploy
                foreach (object selected in selectedItems)
                {
                    ProjectItem pi;
                    string sFileName;
                    string sFilePath;
                    if (selected is ProjectItem)
                    {
                        pi = (ProjectItem)selected;
                    }
                    else if (selected is UIHierarchyItem && ((UIHierarchyItem)selected).Object is ProjectItem)
                    {
                        pi = ((ProjectItem)((UIHierarchyItem)selected).Object);
                    }
                    else
                    {
                        continue;
                    }
                    sFileName = pi.Name;
                    sFilePath = pi.get_FileNames(0);
                    if (!sFileName.ToLower().EndsWith(".dtsx")) continue;

                    if (pi.Document != null && !pi.Document.Saved)
                    {
                        pi.Save("");
                    }

                    if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                    {
                        string sDestinationPath = sDestFolder + sFileName;
                        if (System.IO.File.Exists(sDestinationPath))
                        {
                            System.IO.File.SetAttributes(sDestinationPath, System.IO.FileAttributes.Normal);
                        }
                        sBatFileContents.Append("xcopy \"").Append(sFilePath).Append("\" \"").Append(sDestFolder).AppendLine("\" /Y /R");
                        System.IO.File.Copy(sFilePath, sDestinationPath, true);
                        outputWindow.ReportStatusMessage("Deployed " + sFileName);
                    }
                    else
                    {
                        process.Refresh();
                        process.StartInfo.Arguments = string.Format("/FILE \"{0}\" /DestServer {1} /COPY {2};\"{3}\" /Q", sFilePath, newOptions.DestinationServer, sDestType, sDestFolder + sFileName.Substring(0, sFileName.Length - ".dtsx".Length));
                        sBatFileContents.Append("\"").Append(process.StartInfo.FileName).Append("\" ").AppendLine(process.StartInfo.Arguments);
                        process.Start();
                        string sError = process.StandardError.ReadToEnd();
                        string sStandardOutput = process.StandardOutput.ReadToEnd();
                        process.WaitForExit();
                        if (process.ExitCode > 0)
                        {
                            outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, "BIDS Helper encountered an error when deploying package " + sFileName + "!\r\n\"" + process.StartInfo.FileName + "\" " + process.StartInfo.Arguments + "\r\nexit code = " + process.ExitCode + "\r\n" + sStandardOutput);
                            this.ApplicationObject.ToolWindows.OutputWindow.Parent.AutoHides = false; //pin the window open so you can see the problem
                            return;
                        }
                        outputWindow.ReportStatusMessage("Deployed " + sFileName);
                        System.Windows.Forms.Application.DoEvents();
                    }
                }
                outputWindow.ReportStatusMessage("BIDS Helper completed deploying packages successfully.");

                if (bCreateBat)
                {
                    string sBatFilename = System.IO.Path.GetDirectoryName(((Microsoft.DataWarehouse.VsIntegration.Shell.Project.Extensibility.ProjectExt)proj).FullName);
                    sBatFilename += "\\" + newOptions.OutputPath;
                    if (!System.IO.Directory.Exists(sBatFilename))
                        System.IO.Directory.CreateDirectory(sBatFilename);
                    sBatFilename += "\\bidsHelperDeployPackages.bat";
                    if (System.IO.File.Exists(sBatFilename))
                    {
                        System.IO.File.SetAttributes(sBatFilename, System.IO.FileAttributes.Normal);
                    }
                    System.IO.File.WriteAllText(sBatFilename, sBatFileContents.ToString());
                    outputWindow.ReportStatusMessage("Deployment commands saved to: " + sBatFilename + "\r\n\r\n");
                }
            }
            catch (Exception ex)
            {
                outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, "BIDS Helper encountered an error when deploying packages:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                this.ApplicationObject.ToolWindows.OutputWindow.Parent.AutoHides = false; //pin the window open so you can see the problem
            }
        }
예제 #6
0
        private void Expand(List <string> bimlScriptPaths, Project project, string projectDirectory)
        {
            var tempTargetDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                Directory.CreateDirectory(tempTargetDirectory);

                // Get the General output window, and use that to write out our BIML "compilation" messages
                this.ApplicationObject.ToolWindows.OutputWindow.Parent.SetFocus();
                IOutputWindowFactory service      = ((System.IServiceProvider)project).GetService(typeof(IOutputWindowFactory)) as IOutputWindowFactory;
                IOutputWindow        outputWindow = service.GetStandardOutputWindow(StandardOutputWindow.Build);
                outputWindow.Clear();
                outputWindow.ReportStatusMessage("Expanding BIML");

                // Set status here as well as calling method, as that wasn't showing - Check and cleanup later
                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Generating SSIS Packages", 1, 3);

                ValidationReporter validationReporter = BimlUtility.GetValidationReporter(bimlScriptPaths, project, projectDirectory, tempTargetDirectory);

                // If we have errors show them, and finish
                if (validationReporter.HasErrors)
                {
                    ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                    ApplicationObject.StatusBar.Progress(false, "Generating SSIS Packages", 3, 3);
                    BimlUtility.ProcessValidationReport(outputWindow, validationReporter, false);
                }
                else
                {
                    // We can compile OK, but show warnings if we have them
                    if (validationReporter.HasWarnings)
                    {
                        BimlUtility.ProcessValidationReport(outputWindow, validationReporter, true);
                    }

                    // Write a closing message to the output window, since we have completed OK
                    outputWindow.ReportStatusMessage("BIML expansion completed.");
                    ApplicationObject.StatusBar.Progress(true, "Generating SSIS Packages", 2, 3);


                    List <string> newProjectFiles = new List <string>();
                    string[]      newPackageFiles = Directory.GetFiles(tempTargetDirectory, "*.dtsx", SearchOption.AllDirectories);
                    newProjectFiles.AddRange(newPackageFiles);

#if (!YUKON && !KATMAI)
                    //IF DENALI or later...
                    // Read packages AND project connection managers
                    string[] newConnFiles = Directory.GetFiles(tempTargetDirectory, "*.conmgr", SearchOption.AllDirectories);
                    newProjectFiles.AddRange(newConnFiles);
#endif
                    var safePackageFilePaths        = new List <string>();
                    var conflictingPackageFilePaths = new List <string>();
                    foreach (var tempFilePath in newProjectFiles)
                    {
                        string tempFileName        = Path.GetFileName(tempFilePath);
                        string projectItemFileName = Path.Combine(projectDirectory, tempFileName);
                        if (File.Exists(projectItemFileName))
                        {
                            conflictingPackageFilePaths.Add(tempFilePath);
                        }
                        else
                        {
                            safePackageFilePaths.Add(tempFilePath);
                        }
                    }

                    if (conflictingPackageFilePaths.Count > 0)
                    {
                        var dialog = new MultipleSelectionConfirmationDialog(conflictingPackageFilePaths, projectDirectory, safePackageFilePaths.Count);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            foreach (var filePath in dialog.SelectedFilePaths)
                            {
                                safePackageFilePaths.Add(filePath);
                            }
                        }
                        else
                        {
                            return;
                        }
                    }

#if (DENALI || SQL2014)
                    /*
                     * Make sure that the package correctly references the Project connection manager, if used
                     */
                    List <ProjectConnectionManagerInfo> prjConnInfoList = new List <ProjectConnectionManagerInfo>();

                    // STEP 1 - Store all existing Project Connection Managers
                    foreach (ProjectItem item in project.ProjectItems)
                    {
                        if (item.Name.EndsWith(".conmgr"))
                        {
                            string fileFullPath = item.FileNames[0];

                            XmlReader   r   = new XmlTextReader(fileFullPath);
                            XmlDocument doc = new XmlDocument();
                            doc.Load(r);

                            //XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
                            //xmlnsManager.AddNamespace("DTS", "www.microsoft.com/SqlServer/Dts");

                            XmlElement node = doc.DocumentElement;

                            string prefix = node.GetPrefixOfNamespace("www.microsoft.com/SqlServer/Dts");

                            XmlAttribute xaObjectName = node.Attributes[prefix + ":ObjectName"];
                            XmlAttribute xaDTSID      = node.Attributes[prefix + ":DTSID"];

                            if (xaObjectName == null)
                            {
                                throw new ApplicationException("ObjectName attribute cannot found.");
                            }
                            if (xaDTSID == null)
                            {
                                throw new ApplicationException("DTSID attribute cannot found.");
                            }

                            prjConnInfoList.Add(new ProjectConnectionManagerInfo(fileFullPath, xaObjectName.Value, xaDTSID.Value));

                            r.Close();
                        }
                    }

                    // STEP 2 - For all the Connection Managers that have to be inserted in the solution,
                    //          if a connection manager with the same name alread exists, use the existing GUID
                    //          to avoid corrupting the package that will be inserted
                    foreach (var tempFilePath in safePackageFilePaths)
                    {
                        if (tempFilePath.EndsWith(".conmgr"))
                        {
                            string fileFullPath = tempFilePath;

                            XmlReader   r   = new XmlTextReader(fileFullPath);
                            XmlDocument doc = new XmlDocument();
                            doc.Load(r);

                            //XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
                            //xmlnsManager.AddNamespace("DTS", "www.microsoft.com/SqlServer/Dts");

                            XmlElement node = doc.DocumentElement;

                            string prefix = node.GetPrefixOfNamespace("www.microsoft.com/SqlServer/Dts");

                            bool saveRequired = false;
                            ProjectConnectionManagerInfo pcmi = prjConnInfoList.Find(x => System.IO.Path.GetFileName(x.FileFullPath) == System.IO.Path.GetFileName(fileFullPath));
                            if (pcmi != null)
                            {
                                XmlAttribute xaDTSID = node.Attributes[prefix + ":DTSID"];
                                if (xaDTSID == null)
                                {
                                    throw new ApplicationException("DTSID attribute cannot found.");
                                }

                                xaDTSID.Value = pcmi.DTSID;
                                saveRequired  = true;
                            }
                            else
                            {
                                XmlAttribute xaObjectName = node.Attributes[prefix + ":ObjectName"];
                                XmlAttribute xaDTSID      = node.Attributes[prefix + ":DTSID"];

                                if (xaObjectName == null)
                                {
                                    throw new ApplicationException("ObjectName attribute cannot found.");
                                }
                                if (xaDTSID == null)
                                {
                                    throw new ApplicationException("DTSID attribute cannot found.");
                                }

                                prjConnInfoList.Add(new ProjectConnectionManagerInfo(fileFullPath, xaObjectName.Value, xaDTSID.Value));
                            }

                            r.Close();

                            if (saveRequired)
                            {
                                doc.Save(fileFullPath);
                            }
                        }
                    }

                    // STEP 3 - For Each NEW package make sure that the Project Connection Manager
                    //          points to the correct GUID
                    foreach (var tempFilePath in safePackageFilePaths)
                    {
                        if (tempFilePath.EndsWith(".dtsx"))
                        {
                            string fileFullPath = tempFilePath;

                            XmlReader   r   = new XmlTextReader(fileFullPath);
                            XmlDocument doc = new XmlDocument();
                            doc.Load(r);

                            XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
                            xmlnsManager.AddNamespace("DTS", "www.microsoft.com/SqlServer/Dts");

                            XmlElement root = doc.DocumentElement;

                            XmlNodeList nodes = root.SelectNodes("//connection", xmlnsManager);
                            foreach (XmlNode n in nodes)
                            {
                                string refID = n.Attributes["connectionManagerRefId"].Value;
                                ProjectConnectionManagerInfo pcmi = prjConnInfoList.Find(x => "Package.ConnectionManagers[" + x.ObjectName + "]" == refID);
                                if (pcmi == null)
                                {
                                    pcmi = prjConnInfoList.Find(x => "Project.ConnectionManagers[" + x.ObjectName + "]" == refID);
                                }

                                if (pcmi != null)
                                {
                                    // If a local connection manager does NOT exists, then point to the project connection manager
                                    XmlNode node = root.SelectSingleNode("/DTS:Executable/DTS:ConnectionManagers/DTS:ConnectionManager[@DTS:refId=\"" + pcmi.ObjectName + "\"]", xmlnsManager);
                                    if (node == null)
                                    {
                                        n.Attributes["connectionManagerID"].Value    = pcmi.DTSID + ":external";
                                        n.Attributes["connectionManagerRefId"].Value = "Project.ConnectionManagers[" + pcmi.ObjectName + "]";
                                    }
                                }
                            }

                            r.Close();

                            doc.Save(fileFullPath);
                        }
                    }
#endif

                    // Add files to VS Project
                    foreach (var tempFilePath in safePackageFilePaths)
                    {
                        string projectItemFilePath = Path.Combine(projectDirectory, Path.GetFileName(tempFilePath));
                        File.Copy(tempFilePath, projectItemFilePath, true);
                        project.ProjectItems.AddFromFile(projectItemFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                try
                {
                    if (Directory.Exists(tempTargetDirectory))
                    {
                        Directory.Delete(tempTargetDirectory);
                    }
                }
                catch (Exception)
                {
                }
            }
        }