private void DoImport()

in sqlnexus/fmImport.cs [633:1057]


        private void DoImport()
        {
            if (CheckAndStop())
                return;
            if (!tlpFiles.Visible)
            {
                this.Left = 400;
                this.Top = 200;
                this.Height = 650;
                this.Width = 1100;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                tlpFiles.Visible = true;
                ssStatus.Visible = true;
            }

            MainForm.LogMessage("Starting import...");


            if (tsiDropDBBeforeImporting.Checked == true || ImportOptions.IsEnabled("DropDbBeforeImporting") || Globals.DropExistingDb == true)
            {

                if (Globals.ConsoleMode == false)
                {
                    DialogResult dr = MainForm.LogMessage(String.Format(Properties.Resources.Warning_ToDropDB, Globals.credentialMgr.Database), "Danger", MessageBoxButtons.YesNo);
                    MainForm.LogMessage("dialog result = " + dr.ToString());
                    if (dr == DialogResult.No)
                    {
                        return;
                    }
                    else if (dr == DialogResult.Yes && Globals.credentialMgr.Database.ToLower() != "sqlnexus")
                    {

                        DialogResult reconfirm = MainForm.LogMessage(String.Format("Are you sure you really want to drop database {0}?", Globals.credentialMgr.Database), "Danger", MessageBoxButtons.YesNo);
                        if (DialogResult.No == reconfirm)
                            return;

                    }
                }

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.ConnectionString = Globals.credentialMgr.ConnectionString;
                builder.InitialCatalog = "master";
                SqlConnection conn = new SqlConnection(builder.ConnectionString);
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = String.Format(Properties.Resources.CreateDropDB, Globals.credentialMgr.Database);
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    MainForm.LogMessage("Dropped and created a new database: " + Globals.credentialMgr.Database);
                }
                catch (SqlException sqlex)
                {
                    MainForm.LogMessage("Create Db failed with exception " + sqlex.Message, MessageOptions.Dialog);
                    return;
                }
                finally
                {
                    conn.Close();
                }


            }

            RunScript("SqlNexus_PreProcessing.sql");
            MainForm.LogMessage("Adding Nexus Importer Version" + Globals.credentialMgr.ConnectionString);
            NexusInfo nInfo = new NexusInfo(Globals.credentialMgr.ConnectionString, this.MainForm);
            nInfo.SetAttribute("Nexus Importer Version", Application.ProductVersion);



            int startTicks = Environment.TickCount;
            MainForm.StartStopSpinner(true, MainForm.spnImporter);

            //Switch button/modes to Stop mode
            EnableButtons(false);
            tsbGo.Image = sqlnexus.Properties.Resources.RecordHS1;
            tsbGo.Text = "Stop";
            Application.DoEvents();

            // Close any open reports based on the data that we're about to overwrite
            fmNexus.singleton.CloseAll();

            string srcPath = Path.GetFullPath(cbPath.Text.Trim());
            /*
            string pathFromCmd = Globals.PathsToImport.Dequeue();
            if (pathFromCmd != null)
                srcPath = pathFromCmd;
            else
              srcPath=  Path.GetFullPath(cbPath.Text);
            */

            sqlnexus.Properties.Settings.Default.ImportPath = srcPath;
            if (srcPath[srcPath.Length - 1] != '\\')
                srcPath += '\\';

            //find the instance name by locating it inside ##SQLDIAG.LOG
            instances = new SqlInstances(srcPath);

            if (instances.Count > 1 && Globals.QuietNonInteractiveMode)
            {
                //get first instance for quiet mode (list already sorted;
                MainForm.LogMessage("Quiet mode. Silently selecting the first instance found in a sorted list. Instance name: " + instances.InstanceList()[0], MessageOptions.Silent);
                instances.InstanceToImport = instances.InstanceList()[0];
            }
            else if (instances.Count > 1)
            {
                fmSelectInstance chooseInstancefm = new fmSelectInstance();
                chooseInstancefm.Tag = instances;
                chooseInstancefm.ShowDialog();
            }

            DiagConfig config = new DiagConfig(srcPath);

            nInfo.SetAttribute("SQLVersion", config.SQLVersion);

            //enumerate the files to process and add them to list for processing
            EnumFiles();

            //add individual rows for each of these so they show up as progress bars in the summary window listview
            string rawFileImprtStr = "RawFileImport";
            AddFileRow((tlpFiles.RowCount - 1), "Raw file import", null, rawFileImprtStr);

            string postProcessStr = "PostProcess";
            AddFileRow((tlpFiles.RowCount - 1), "Post-Import processing ", null, postProcessStr);

            string perfStatsAnalysisStr = "PerfStatsAnalysis";
            AddFileRow((tlpFiles.RowCount - 1), "Running perfstats analysis", null, perfStatsAnalysisStr);

            string runtimeCountStr = "RuntimeCount";
            AddFileRow((tlpFiles.RowCount - 1), "Counting unique runtime snapshots", null, runtimeCountStr);

            string enumReportsStr = "EnumReports";
            AddFileRow((tlpFiles.RowCount - 1), "Enumerating reports", null, enumReportsStr);


            //AddLabel();
            bool RunScripts = true;
            bool Success = false;

            CustomXELImporter CI = new CustomXELImporter();
            CI.SQLBaseImport(Globals.credentialMgr.ConnectionString, Globals.credentialMgr.Server,
                                                    Globals.credentialMgr.WindowsAuth,
                                                    Globals.credentialMgr.User,
                                                    Globals.credentialMgr.Password,
                                                    Globals.credentialMgr.Database, srcPath);



            try
            {
                int j = 0;

                for (int i = 0; i < tlpFiles.Controls.Count; i++)
                {
                    //if (tlpFiles.Controls[i] is LinkLabel)
                    if (tlpFiles.Controls[i] is Label && tlpFiles.Controls[i].Name == "FileNameLabel")
                    {
                        System.Diagnostics.Debug.Assert((null != tlpFiles.Controls[i + 1]) && (null != tlpFiles.Controls[i + 2]));
                        //LinkLabel ll = (LinkLabel)tlpFiles.Controls[i];
                        Label ll = (Label)tlpFiles.Controls[i];
                        currBar = (ProgressBar)tlpFiles.Controls[i + 1];
                        currBar.Value = 0;
                        currLabel = (Label)tlpFiles.Controls[i + 2];

                        int ticks = Environment.TickCount;

                        ri = (ll.Tag as INexusImporter);
                        MainForm.LogMessage(ri.Name + " is a INexusImporter");

                        try
                        {
                            ri.Initialize(srcPath + (tlpFiles.Controls[i] as /*LinkLabel*/ Label).Text,
                                                    Globals.credentialMgr.ConnectionString,
                                                    Globals.credentialMgr.Server,
                                                    Globals.credentialMgr.WindowsAuth,
                                                    Globals.credentialMgr.User,
                                                    Globals.credentialMgr.Password,
                                                    Globals.credentialMgr.Database,
                                                    MainForm);

                            //Run pre-scripts and cache post scripts for later use
                            if (!PostScripts.ContainsKey(ri.GetType().Name))
                            {
                                PostScripts.Add(ri.GetType().Name, ri.PostScripts);
                                foreach (string s in ri.PreScripts)
                                {
                                    RunScript(s);
                                }
                            }

                            if (!(ri is INexusFileSizeReporter))
                            {
                                currBar.Style = ProgressBarStyle.Marquee;
                            }

                            //Import the data
                            Success = ri.DoImport();



                            if (ri.Name.ToLower().Contains("rowset"))
                            {
                                RunPostScripts();
                            }
                            Globals.IsNexusCoreImporterSuccessful = true;
                            //ll.LinkBehavior = LinkBehavior.HoverUnderline;
                        }
                        catch (Exception ex)
                        {
                            if (ri.Name == "Rowset Importer")
                            {
                                Globals.IsNexusCoreImporterSuccessful = false;
                            }
                            Success = false;
                            Globals.HandleException(ex, this, MainForm);
                        }

                        currBar.Style = ProgressBarStyle.Blocks;
                        string msg;
                        msg = "(Importer:" + ri.Name + ") ";
                        if (ri.Cancelled)	// different msg if import was canceled.
                        {
                            RunScripts = false;
                            msg += "Cancelled. (" + (Environment.TickCount - ticks) / 1000 + " sec, ";
                            if (ri is INexusFileImporter)
                            {
                                msg += this.currBar.Value.ToString() + "% complete)";
                            }
                            else
                            {
                                msg += ri.TotalLinesProcessed + " rows inserted)";
                            }
                            MainForm.LogMessage(msg);
                            currLabel.Text = msg;
                            break;
                        }
                        else if (!Success)	// set summary msg if import failed
                        {
                            RunScripts = false;
                            msg += "Import failed. (" + (Environment.TickCount - ticks) / 1000 + " sec, ";
                            if (ri is INexusFileImporter)
                            {
                                msg += this.currBar.Value.ToString() + "% complete)";
                            }
                            else
                            {
                                msg += ri.TotalLinesProcessed + " rows inserted)";
                            }
                            MainForm.LogMessage(msg);
                            currLabel.Text = msg;
                        }
                        else					// different msg if success
                        {
                            currBar.Value = currBar.Maximum;

                            msg += "Done. (" + (Environment.TickCount - ticks) / 1000 + " sec";
                            if (ri is INexusFileImporter)
                            {
                                msg += ", " + ((ri as INexusFileImporter).FileSize / 1000 / 1000) + "MB), ";
                            }
                            else
                            {
                                msg += "), ";
                            }
                            msg += msg = string.Format("{0} lines processed; {1} rows inserted.", ri.TotalLinesProcessed, ri.TotalRowsInserted);
                            MainForm.LogMessage(msg);
                            currLabel.Text = msg;
                        }
                        ri = null;
                        j++;

                    } //end of if (Name == "FileNameLabel")

                    else if (tlpFiles.Controls[i].Name == rawFileImprtStr)
                    {
                        int rawfileStartTicks = Environment.TickCount;

                        currBar = (ProgressBar)tlpFiles.Controls[i + 1];
                        currBar.Value = 20;

                        currLabel = (Label)tlpFiles.Controls[i + 2];
                        currLabel.Text = "Please wait for raw file import to complete...";


                        //raw file importer
                        MainForm.LogMessage("RawFileImporter starting");
                        Application.DoEvents();

                        RawFileImporter rawfileimporter = new RawFileImporter(Globals.credentialMgr.Server, Globals.credentialMgr.Database, srcPath);

                        //do the raw file import
                        string statusStr = rawfileimporter.DoImport();

                        currBar.Value = 100;
                        MainForm.LogMessage("RawFileImporter completed");

                        string rawfileMsg = "(Importer:" + rawFileImprtStr + ") " + "Done. (" + (Environment.TickCount - rawfileStartTicks) / 1000 + " sec), " + statusStr + ".";
                        currLabel.Text = rawfileMsg;
                        Application.DoEvents();
                    }

                    else if (tlpFiles.Controls[i].Name == postProcessStr)
                    {
                        Application.DoEvents();
                        //run Perfstats Analysis script just once
                        currBar = (ProgressBar)tlpFiles.Controls[i + 1];
                        currBar.Value = 20;

                        currLabel = (Label)tlpFiles.Controls[i + 2];
                        currLabel.Text = "Please wait for post-import process step to complete...";

                        MainForm.LogMessage("Running Post-Import processing...");
                        Application.DoEvents();

                        //run Post-processing
                        RunPostProcessing(srcPath);

                        currBar.Value = 100;
                        currLabel.Text = "(Post-import Processing) Done.";
                        MainForm.LogMessage("End of Post-Import processing");

                        Application.DoEvents();
                    }

                    else if (tlpFiles.Controls[i].Name == perfStatsAnalysisStr)
                    {
                        Application.DoEvents();
                        //run Perfstats Analysis script just once
                        currBar = (ProgressBar)tlpFiles.Controls[i + 1];
                        currBar.Value = 20;

                        currLabel = (Label)tlpFiles.Controls[i + 2];
                        currLabel.Text = "Please wait for PerfStats analysis step to complete...";

                        MainForm.LogMessage("Running Perfstats Analysis");
                        Application.DoEvents();

                        //do the analysis
                        RunScript("PerfStatsAnalysis.sql");

                        currBar.Value = 100;
                        currLabel.Text = "(PerfStatsAnalysis) Done.";
                        MainForm.LogMessage("End of Perfstats Analysis");

                        Application.DoEvents();
                    }

                    else if (tlpFiles.Controls[i].Name == runtimeCountStr)
                    {
                        Application.DoEvents();
                        int runtimeStartTicks = Environment.TickCount;
                        //run Perfstats Analysis script just once
                        currBar = (ProgressBar)tlpFiles.Controls[i + 1];
                        currBar.Value = 20;

                        currLabel = (Label)tlpFiles.Controls[i + 2];
                        currLabel.Text = "Please wait for this step to complete...";

                        MainForm.LogMessage("Running count of runtimes captured in the data");
                        Application.DoEvents();

                        //do the runtime count
                        string runtimesRet = RuntimeCount(startTicks);

                        currBar.Value = 100;

                        string runtimeMsg = "(" + runtimeCountStr + ") " + "Done. (" + (Environment.TickCount - runtimeStartTicks) / 1000 + " sec), " + runtimesRet + ".";
                        currLabel.Text = runtimeMsg;
                        MainForm.LogMessage("End of counting runtimes");

                        Application.DoEvents();
                    }

                    else if (tlpFiles.Controls[i].Name == enumReportsStr)
                    {
                        int enumReportsStartTicks = Environment.TickCount;
                        //run Perfstats Analysis script just once
                        currBar = (ProgressBar)tlpFiles.Controls[i + 1];
                        currBar.Value = 10;

                        currLabel = (Label)tlpFiles.Controls[i + 2];
                        currLabel.Text = "Please wait reports enumeration step to complete...";

                        MainForm.LogMessage("Enumerating reports");
                        Application.DoEvents();


                        //Refresh reports list in case provider changed it
                        MainForm.EnumReports();

                        currBar.Value = 100;

                        string runtimeMsg = "(" + enumReportsStr + ") " + "Done. (" + (Environment.TickCount - enumReportsStartTicks) / 1000 + " sec). Import Complete!";
                        currLabel.Text = runtimeMsg;
                        MainForm.LogMessage("End of report enumeration");

                        Application.DoEvents();

                    }

                } //end of for loop

            }//try block

            catch (Exception ex)
            {
                MainForm.LogMessage("Import failed.");
                Globals.HandleException(ex, this, MainForm);
            }
            finally
            {
                MainForm.StartStopSpinner(false, MainForm.spnImporter);
                tsbGo.Image = sqlnexus.Properties.Resources.PlayHS1;
                tsbGo.Text = "Import";
                EnableButtons(true);
                this.Cursor = Cursors.Default;
                Application.DoEvents();

                if (Globals.QuietNonInteractiveMode == true)
                {
                    Application.Exit();
                }
            }
        }