Beispiel #1
0
        public static DataSet GetObjectPermissions(
            ObjectTag tag,
            bool isExplicit
            )
        {
            DataSet ds = null;

            try
            {
                using (SqlConnection connection = new SqlConnection(Program.gController.Repository.ConnectionString))
                {
                    // Open the connection.
                    connection.Open();

                    // Setup the params.
                    SqlParameter paramSnapshotId     = new SqlParameter(ParamSnapshotId, tag.SnapshotId);
                    SqlParameter paramDbId           = new SqlParameter(ParamDbId, tag.DatabaseId);
                    SqlParameter paramClassId        = new SqlParameter(ParamClassId, tag.ClassId);
                    SqlParameter paramParentObjectId = new SqlParameter(ParamParentObjectId, tag.ParentObjectId);
                    SqlParameter paramObjectId       = new SqlParameter(ParamObjectId, tag.ObjectId);
                    SqlParameter paramPermissionType = new SqlParameter(ParamPermissionType, (isExplicit ? "X" : "E"));

                    // Create command object, and fill the dataset.
                    using (SqlCommand cmd = new SqlCommand(QueryObjectPermissions, connection))
                    {
                        // Set the command object.
                        cmd.CommandType    = CommandType.StoredProcedure;
                        cmd.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                        cmd.Parameters.Add(paramSnapshotId);
                        cmd.Parameters.Add(paramDbId);
                        cmd.Parameters.Add(paramClassId);
                        cmd.Parameters.Add(paramObjectId);
                        cmd.Parameters.Add(paramPermissionType);

                        // Create the data adapter object.
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            // Fill the dataset.
                            ds = new DataSet();
                            da.Fill(ds);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ds != null)
                {
                    ds.Dispose();
                }
                ds = null;

                MsgBox.ShowError(ErrorMsgs.CantGetServerObjectPermissions, ex);
            }

            return(ds);
        }
        protected internal override void runReport()
        {
            try
            {
                if (_comboBox_Server.SelectedValue == null || _comboBox_Server.Text.Length == 0)
                {
                    return;
                }

                if (ultraCombo_Assessment1.SelectedItem == null || ultraCombo_Assessment1.SelectedItem.Tag == null)
                {
                    return;
                }

                if (ultraCombo_Assessment2.SelectedItem == null || ultraCombo_Assessment2.SelectedItem.Tag == null)
                {
                    return;
                }

                m_ServerId      = (int)_comboBox_Server.SelectedValue;
                m_ServerName    = _comboBox_Server.Text;
                m_assessmentid1 = ((Sql.Policy)ultraCombo_Assessment1.SelectedItem.Tag).AssessmentId;
                m_assessmentid2 = ((Sql.Policy)ultraCombo_Assessment2.SelectedItem.Tag).AssessmentId;

                base.runReport();

                logX.loggerX.Info(@"Retrieve data for report Compare Assessments");

                using (SqlConnection connection = new SqlConnection(Program.gController.Repository.ConnectionString))
                {
                    // Open the connection.
                    connection.Open();

                    // Setup stored procedures
                    SqlCommand cmd  = new SqlCommand(QueryDataSource1, connection);
                    SqlCommand cmd2 = new SqlCommand(QueryDataSource2, connection);
                    SqlCommand cmd3 = new SqlCommand(QueryDataSource3, connection);
                    SqlCommand cmd4 = new SqlCommand(QueryDataSource4, connection);
                    SqlCommand cmd5 = new SqlCommand(QueryDataSource5, connection);
                    cmd.CommandType     = CommandType.StoredProcedure;
                    cmd2.CommandType    = CommandType.StoredProcedure;
                    cmd3.CommandType    = CommandType.StoredProcedure;
                    cmd4.CommandType    = CommandType.StoredProcedure;
                    cmd5.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandTimeout  = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                    cmd2.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                    cmd3.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                    cmd4.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                    cmd5.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();

                    // Build parameters
                    SqlParameter paramPolicyId           = new SqlParameter(SqlParamPolicyid, m_policyid);
                    SqlParameter paramAssessmentId1      = new SqlParameter(SqlParamAssessmentid1, m_assessmentid1);
                    SqlParameter paramAssessmentId2      = new SqlParameter(SqlParamAssessmentid2, m_assessmentid2);
                    SqlParameter paramRegisteredServerId = new SqlParameter(SqlParamServerid, m_ServerId);
                    SqlParameter paramDiffsOnly          = new SqlParameter(SqlParamDiffsOnly, _checkbox_showDiffsOnly.Checked);

                    cmd.Parameters.Add(paramPolicyId);
                    cmd.Parameters.Add(paramAssessmentId1);
                    cmd.Parameters.Add(paramAssessmentId2);
                    cmd.Parameters.Add(paramRegisteredServerId);
                    cmd.Parameters.Add(paramDiffsOnly);

                    SqlParameter paramPolicyid2           = new SqlParameter(SqlParamPolicyid, m_policyid);
                    SqlParameter paramAssessmentid2       = new SqlParameter(SqlParamAssessmentid, m_assessmentid1);
                    SqlParameter paramRegisteredServerId2 = new SqlParameter(SqlParamServerid, m_ServerId);
                    SqlParameter paramUsebaseline2        = new SqlParameter(SqlParamUsebaseline, m_useBaseline);
                    SqlParameter paramRunDate2            = new SqlParameter(SqlParamRunDate, m_reportDate);
                    cmd2.Parameters.Add(paramPolicyid2);
                    cmd2.Parameters.Add(paramAssessmentid2);
                    cmd2.Parameters.Add(paramRegisteredServerId2);
                    cmd2.Parameters.Add(paramUsebaseline2);
                    cmd2.Parameters.Add(paramRunDate2);

                    SqlParameter paramPolicyid5           = new SqlParameter(SqlParamPolicyid, m_policyid);
                    SqlParameter paramAssessmentid5       = new SqlParameter(SqlParamAssessmentid, m_assessmentid2);
                    SqlParameter paramRegisteredServerId5 = new SqlParameter(SqlParamServerid, m_ServerId);
                    SqlParameter paramUsebaseline5        = new SqlParameter(SqlParamUsebaseline, m_useBaseline);
                    SqlParameter paramRunDate5            = new SqlParameter(SqlParamRunDate, m_reportDate);
                    cmd5.Parameters.Add(paramPolicyid5);
                    cmd5.Parameters.Add(paramAssessmentid5);
                    cmd5.Parameters.Add(paramRegisteredServerId5);
                    cmd5.Parameters.Add(paramUsebaseline5);
                    cmd5.Parameters.Add(paramRunDate5);


                    SqlParameter paramPolicyid3     = new SqlParameter(SqlParamPolicyid, m_policyid);
                    SqlParameter paramAssessmentid3 = new SqlParameter(SqlParamAssessmentid, m_assessmentid1);
                    cmd3.Parameters.Add(paramPolicyid3);
                    cmd3.Parameters.Add(paramAssessmentid3);

                    SqlParameter paramPolicyid4     = new SqlParameter(SqlParamPolicyid, m_policyid);
                    SqlParameter paramAssessmentid4 = new SqlParameter(SqlParamAssessmentid, m_assessmentid2);
                    cmd4.Parameters.Add(paramPolicyid4);
                    cmd4.Parameters.Add(paramAssessmentid4);


                    // Get data for first dataset
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet        ds = new DataSet();
                    da.Fill(ds);

                    ReportDataSource rds = new ReportDataSource();
                    rds.Name  = DataSourceName1;
                    rds.Value = ds.Tables[0];
                    _reportViewer.LocalReport.DataSources.Clear();
                    _reportViewer.LocalReport.DataSources.Add(rds);

                    // Get data for second dataset
                    SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
                    DataSet        ds2 = new DataSet();
                    da2.Fill(ds2);

                    ReportDataSource rds2 = new ReportDataSource();
                    rds2.Name  = DataSourceName2;
                    rds2.Value = ds2.Tables[0];
                    _reportViewer.LocalReport.DataSources.Add(rds2);

                    // Get data for third dataset
                    SqlDataAdapter da3 = new SqlDataAdapter(cmd3);
                    DataSet        ds3 = new DataSet();
                    da3.Fill(ds3);

                    ReportDataSource rds3 = new ReportDataSource();
                    rds3.Name  = DataSourceName3;
                    rds3.Value = ds3.Tables[0];
                    _reportViewer.LocalReport.DataSources.Add(rds3);

                    // Get data for fourth dataset
                    SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
                    DataSet        ds4 = new DataSet();
                    da4.Fill(ds4);

                    ReportDataSource rds4 = new ReportDataSource();
                    rds4.Name  = DataSourceName4;
                    rds4.Value = ds4.Tables[0];
                    _reportViewer.LocalReport.DataSources.Add(rds4);

                    // Get data for fifth dataset
                    SqlDataAdapter da5 = new SqlDataAdapter(cmd5);
                    DataSet        ds5 = new DataSet();
                    da5.Fill(ds5);

                    ReportDataSource rds5 = new ReportDataSource();
                    rds5.Name  = DataSourceName5;
                    rds5.Value = ds5.Tables[0];
                    _reportViewer.LocalReport.DataSources.Add(rds5);
                }
            }
            catch (Exception ex)
            {
                logX.loggerX.Error(@"Error - Unable to get report data", ex);
                MsgBox.ShowError(m_Title, ErrorMsgs.CantGetReportData, ex);
                return;
            }

            //add report parameters
            ReportParameter[] Param = new ReportParameter[2];
            Param[0] = new ReportParameter("ReportTitle", string.Format(Utility.Constants.REPORTS_TITLE_STR, m_Title));
            Param[1] = new ReportParameter("Expand_All", _isExpanded.ToString());

            _reportViewer.LocalReport.SetParameters(Param);

            // Make sure _reportViewer is created.
            // We had issues on some servers where the _reportViewer was not yet created
            // and this caused a crash.
            if (!_reportViewer.IsHandleCreated)
            {
                if (!_reportViewer.Created)
                {
                    _reportViewer.CreateControl();
                }
            }

            _reportViewer.RefreshReport();
        }
        private void loadDataSource()
        {
            logX.loggerX.Info("Retrieve Policy Report Card");

            try
            {
                _textBox_Description.Text = DisplayNoLog;

                // Open connection to repository and query permissions.
                using (SqlConnection connection = new SqlConnection(Program.gController.Repository.ConnectionString))
                {
                    // Open the connection.
                    connection.Open();

                    // Setup parameters for all queries
                    SqlParameter paramPolicyId     = new SqlParameter(ParamPolicyId, m_policy.PolicyId);
                    SqlParameter paramAssessmentId = new SqlParameter(ParamAssessmentId, m_policy.AssessmentId);

                    // Get Change Log
                    SqlCommand cmd = new SqlCommand(QueryGetChangeLog, connection);
                    cmd.CommandType    = CommandType.Text;
                    cmd.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();

                    cmd.Parameters.Add(paramPolicyId);
                    cmd.Parameters.Add(paramAssessmentId);

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet        ds = new DataSet();
                    da.Fill(ds);

                    m_ChangeLogTable = ds.Tables[0];

                    // fix the time by converting to local for display
                    foreach (DataRow row in m_ChangeLogTable.Rows)
                    {
                        row[colChangedDate] = ((DateTime)row[colChangedDate]).ToLocalTime();
                    }

                    m_ChangeLogTable.DefaultView.Sort = colChangedDate;

                    _grid_ChangeLog.SuspendLayout();

                    // Save the user configuration of the grid to restore it after setting the datasource again
                    Utility.GridSettings gridSettings = GridSettings.GetSettings(_grid_ChangeLog);

                    _label_ChangeLog.Text =
                        string.Format(HeaderDisplay,
                                      m_ChangeLogTable.DefaultView.Count,
                                      m_ChangeLogTable.DefaultView.Count == 1 ? @"y" : @"ies");

                    _grid_ChangeLog.SetDataBinding(m_ChangeLogTable.DefaultView, null);

                    // Reapply the user's settings after rebuilding the grid
                    GridSettings.ApplySettingsToGrid(gridSettings, _grid_ChangeLog);

                    if (!m_Initialized)
                    {
                        foreach (UltraGridColumn col in _grid_ChangeLog.DisplayLayout.Bands[0].Columns)
                        {
                            //if (col.Key != colSeverityCode)
                            {
                                col.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                            }
                        }
                        _grid_ChangeLog.DisplayLayout.Bands[0].SortedColumns.Add(colChangedDate, true, false);

                        m_Initialized = true;
                    }



                    _grid_ChangeLog.ResumeLayout();
                }
            }
            catch (Exception ex)
            {
                logX.loggerX.Error(@"Error - Unable to retrieve policy change log", ex);
                MsgBox.ShowError(string.Format(ErrorMsgs.CantGetPolicyInfoMsg, "Policy Change Log"),
                                 ErrorMsgs.ErrorProcessPolicyInfo,
                                 ex);
                initDataSources();

                _grid_ChangeLog.ResumeLayout();
            }
        }
        protected internal override void runReport()
        {
            if (_comboBox_Server.Text == Utility.Constants.ReportSelect_AllServers)
            {
                if (DialogResult.No ==
                    MsgBox.ShowWarningConfirm(Utility.Constants.ReportTitle_AllObjectsWithPermissions,
                                              Utility.ErrorMsgs.ReportAllServersWarning))
                {
                    return;
                }
            }

            base.runReport();

            logX.loggerX.Info(@"Retrieve data for report All Objects With Permissions");

            string databaseName = allserversvalue;

            if (!_checkBox_allDatabases.Checked)
            {
                databaseName = string.Empty;
                for (int i = 0; i < _listBox_database.Items.Count; i++)
                {
                    if (_listBox_database.GetSelected(i))
                    {
                        databaseName += (databaseName != string.Empty ? "," : "") + _listBox_database.Items[i].ToString();
                    }
                }
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(Program.gController.Repository.ConnectionString))
                {
                    // Open the connection.
                    connection.Open();

                    // Setup stored procedure
                    SqlCommand cmd = new SqlCommand(_comboBox_Level.SelectedIndex == 0 ? QueryDataSource : QueryDataSourceUser, connection);
                    cmd.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();

                    // Build parameters
                    SqlParameter paramRunDate      = new SqlParameter(SqlParamRunDate, m_reportDate);
                    SqlParameter paramPolicyid     = new SqlParameter(SqlParamPolicyid, m_policyid);
                    SqlParameter paramServerName   = new SqlParameter(SqlParamServerName2, getServerName(_comboBox_Server.Text));
                    SqlParameter paramUseBaseline  = new SqlParameter(SqlParamUsebaseline, m_useBaseline);
                    SqlParameter paramDatabaseName = new SqlParameter(SqlParamDatabaseName, databaseName);

                    cmd.Parameters.Add(paramRunDate);
                    cmd.Parameters.Add(paramPolicyid);
                    cmd.Parameters.Add(paramServerName);
                    cmd.Parameters.Add(paramUseBaseline);
                    cmd.Parameters.Add(paramDatabaseName);

                    // Get data
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet        ds = new DataSet();
                    da.Fill(ds);

                    ReportDataSource rds = new ReportDataSource();
                    rds.Name  = DataSourceName;
                    rds.Value = ds.Tables[0];
                    _reportViewer.Reset();
                    _reportViewer.LocalReport.DataSources.Clear();
                    _reportViewer.LocalReport.SubreportProcessing   += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
                    _reportViewer.LocalReport.EnableHyperlinks       = true;
                    _reportViewer.LocalReport.ReportEmbeddedResource = _comboBox_Level.SelectedIndex == 0 ? ReportEmbeddedResource : ReportEmbeddedResourceUser;
                    _reportViewer.LocalReport.DataSources.Add(rds);
                }
            }
            catch (SqlException ex)
            {
                logX.loggerX.Error(@"Error - Unable to get report data", ex);

                MsgBox.ShowError(m_Title, ErrorMsgs.CantGetReportData, ex);

                return;
            }

            //add report parameters
            ReportParameter[] Param = new ReportParameter[4];
            Param[0] = new ReportParameter("ReportTitle", string.Format(Utility.Constants.REPORTS_TITLE_STR, m_Title));
            Param[1] = new ReportParameter("UserRange", m_reportDateDisplay);
            Param[2] = new ReportParameter("serverName", _comboBox_Server.Text);
            Param[3] = new ReportParameter("Expand_All", _isExpanded.ToString());

            _reportViewer.LocalReport.SetParameters(Param);

            // Make sure _reportViewer is created.
            // We had issues on some servers where the _reportViewer was not yet created
            // and this caused a crash.
            if (!_reportViewer.IsHandleCreated)
            {
                if (!_reportViewer.Created)
                {
                    _reportViewer.CreateControl();
                }
            }

            _reportViewer.RefreshReport();
        }
        void SubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
        {
            logX.loggerX.Info(@"Retrieve data for report User Permissions subreport " + e.ReportPath);

            ReportDataSource rds = new ReportDataSource();

            //This event will run once for each iteration of each subreport
            //the ReportPath will identify which one is running and the report parameters
            //can be accessed to create a unique datasource for each pass if needed
            e.DataSources.Clear();

            switch (e.ReportPath)
            {
            case "SubReport_Logins":
            case "SubReport_LoginsUser":

                // This is the same dataset that the primary report uses, so just pass it again
                // The full dataset is passed since it already contains all the data on the first run
                // and the subreport uses the servername as a filter internally
                rds.Name  = DataSourceName;
                rds.Value = m_userPermissions;
                e.DataSources.Add(rds);
                break;

            case "SubReport_UsersPermissions":
                //the server name is passed as a parameter to the subreport
                //so extract it to create a unique dataset on each pass
                string server = e.Parameters[ReportParamServer].Values[0].ToString();

                try
                {
                    using (SqlConnection connection = new SqlConnection(Program.gController.Repository.ConnectionString))
                    {
                        // Open the connection.
                        connection.Open();

                        //Create the permissions sub report datasource
                        SqlCommand cmd = new SqlCommand(SubReportPermissionsQueryDataSource, connection);
                        cmd.CommandType    = CommandType.StoredProcedure;
                        cmd.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();

                        DataSet ds = new DataSet();

                        // Build parameters
                        SqlParameter paramRunDate    = new SqlParameter(SqlParamRunDate, m_reportDate);
                        SqlParameter paramUser       = new SqlParameter(SqlParamUser, _textBox_User.Text.Trim());
                        SqlParameter paramServer     = new SqlParameter(ReportParamServer, server);
                        SqlParameter paramUserType   = new SqlParameter(SqlParamUserType, m_loginType);
                        SqlParameter paramPermission = new SqlParameter(SqlParamPermissionType, m_permissionType);
                        cmd.Parameters.Add(paramRunDate);
                        cmd.Parameters.Add(paramUser);
                        cmd.Parameters.Add(paramServer);
                        cmd.Parameters.Add(paramUserType);
                        cmd.Parameters.Add(paramPermission);

                        // Get data
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(ds);

                        // Attach datasource
                        rds.Name  = SubReportPermissionsDataSourceName;
                        rds.Value = ds.Tables[0].DefaultView;
                        e.DataSources.Add(rds);
                    }
                }
                catch (SqlException ex)
                {
                    logX.loggerX.Error("Unable to create User Permissions Detail subreport datasource", ex);
                    return;
                }

                break;

            case "SubReport_ServersUsedSummary":
                e.DataSources.Add(getServerListDataSet());

                break;
            }
        }
Beispiel #6
0
        protected internal override void runReport()
        {
            if (_comboBox_Server.SelectedValue == null)
            {
                _comboBox_Server.SelectedItem = _comboBox_Server.Items[0];
            }
            m_ServerId   = (int)_comboBox_Server.SelectedValue;
            m_ServerName = _comboBox_Server.Text;
            base.runReport();

            logX.loggerX.Info(@"Retrieve data for report Compare Snapshots");

            try
            {
                using (SqlConnection connection = new SqlConnection(Program.gController.Repository.ConnectionString))
                {
                    // Open the connection.
                    connection.Open();

                    // Setup stored procedures
                    SqlCommand cmd  = new SqlCommand(QueryDataSource1, connection);
                    SqlCommand cmd2 = new SqlCommand(QueryDataSource2, connection);
                    cmd.CommandType     = CommandType.StoredProcedure;
                    cmd2.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandTimeout  = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                    cmd2.CommandTimeout = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();

                    // Build parameters
                    SqlParameter paramSnapshotId1 = new SqlParameter(SqlParamSnapshotid, (int)_comboBox_Snapshot1.SelectedValue);
                    SqlParameter paramSnapshotId2 = new SqlParameter(SqlParamSnapshotid2, (int)_comboBox_Snapshot2.SelectedValue);

                    cmd.Parameters.Add(paramSnapshotId1);
                    cmd.Parameters.Add(paramSnapshotId2);

                    SqlParameter paramSnapshotId3 = new SqlParameter(SqlParamSnapshotid, (int)_comboBox_Snapshot1.SelectedValue);
                    SqlParameter paramSnapshotId4 = new SqlParameter(SqlParamSnapshotid2, (int)_comboBox_Snapshot2.SelectedValue);

                    cmd2.Parameters.Add(paramSnapshotId3);
                    cmd2.Parameters.Add(paramSnapshotId4);

                    // Get data for first dataset
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet        ds = new DataSet();
                    da.Fill(ds);

                    ReportDataSource rds = new ReportDataSource();
                    rds.Name  = DataSourceName1;
                    rds.Value = ds.Tables[0];
                    _reportViewer.LocalReport.DataSources.Clear();
                    _reportViewer.LocalReport.DataSources.Add(rds);

                    // Get data for second dataset
                    SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
                    DataSet        ds2 = new DataSet();
                    da2.Fill(ds2);

                    ReportDataSource rds2 = new ReportDataSource();
                    rds2.Name  = DataSourceName2;
                    rds2.Value = ds2.Tables[0];
                    _reportViewer.LocalReport.DataSources.Add(rds2);
                }
            }
            catch (SqlException ex)
            {
                logX.loggerX.Error(@"Error - Unable to get report data", ex);
                MsgBox.ShowError(m_Title, ErrorMsgs.CantGetReportData, ex);
            }

            //add report parameters
            ReportParameter[] Param = new ReportParameter[6];
            Param[0] = new ReportParameter("ReportTitle", string.Format(Utility.Constants.REPORTS_TITLE_STR, m_Title));
            Param[1] = new ReportParameter("UserRange", m_reportDateDisplay);
            Param[2] = new ReportParameter("serverName", _comboBox_Server.Text);
            Param[3] = new ReportParameter("Expand_All", _isExpanded.ToString());
            Param[4] = new ReportParameter("SnapshotName1", _comboBox_Snapshot1.SelectedText);
            Param[5] = new ReportParameter("SnapshotName2", _comboBox_Snapshot2.SelectedText);

            _reportViewer.LocalReport.SetParameters(Param);

            // Make sure _reportViewer is created.
            // We had issues on some servers where the _reportViewer was not yet created
            // and this caused a crash.
            if (!_reportViewer.IsHandleCreated)
            {
                if (!_reportViewer.Created)
                {
                    _reportViewer.CreateControl();
                }
            }

            _reportViewer.RefreshReport();
        }
        public static bool ImportItem(ImportItem itemToImport, Repository repository, ImportSettings settings)
        {
            using (logX.loggerX.InfoCall())
            {
                string sqlServerVersion, machine, instance, connectionName, edition;
                var    errorList = new List <string>();

                if (itemToImport.HasErrors())
                {
                    settings.ChangeStatus(ImportStatusIcon.Warning,
                                          string.Format("Skipped due to errors: {0}", itemToImport.GetErrors()));
                    return(false);
                }
                settings.ChangeStatus(ImportStatusIcon.Importing, "Importing");


                var serverNameParts = itemToImport.ServerName.Split(',');
                var serverPort      = serverNameParts.Length > 1 ? Convert.ToInt32(serverNameParts[1]) : (int?)null;
                ScheduleJob.ScheduleData scheduleData = new ScheduleJob.ScheduleData();

                //Validation of instance connection credentials
                OperationResult <bool> operationResult =
                    ValidateCredentials(itemToImport, out sqlServerVersion, out machine, out instance,
                                        out connectionName, out edition);

                if (!operationResult.Value)
                {
                    settings.ChangeStatus(ImportStatusIcon.Error, string.Format("Not imported. {0}", operationResult.GetEventAllMessagesString()));
                    return(false); //Skip importing of server
                }

                // SQLsecure 3.1 (Anshul) - Validate server edition based on server type.
                // SQLsecure 3.1 (Anshul) - SQLSECU-1775 - Azure VM : Register a Server as Azure DB by selecting Server type as Azure VM.
                if (!SqlHelper.ValidateServerEdition(itemToImport.ServerType, edition))
                {
                    settings.ChangeStatus(ImportStatusIcon.Error, string.Format("Not imported. {0}",
                                                                                itemToImport.ServerType == ServerType.AzureSQLDatabase ? ErrorMsgs.IncorrectServerTypeAzureSQLDBImportMsg :
                                                                                ErrorMsgs.IncorrectServerTypeSQLServerImportMsg));
                    return(false); //Skip importing of server
                }

                //Validation of server acces credentials (using WindowsCredentials)
                //Add operation error if not successful but continue import operation
                operationResult = CheckServerAccess(itemToImport, machine);
                if (!operationResult.Value)
                {
                    errorList.AddRange(operationResult.GetEventMessagesStringList());
                }
                ;

                var        parsedSqlServerVersion = SqlHelper.ParseVersion(sqlServerVersion);
                ServerInfo serverInfo             = new ServerInfo(parsedSqlServerVersion, (itemToImport.AuthType == SqlServerAuthenticationType.WindowsAuthentication || itemToImport.AuthType == SqlServerAuthenticationType.AzureADAuthentication),
                                                                   itemToImport.UserName, itemToImport.Password, connectionName, SqlServer.GetValueByName(itemToImport.ServerType));
                try
                {
                    if (repository.RegisteredServers.Find(connectionName) != null)
                    {
                        UpdateCredentials(itemToImport, repository, connectionName);
                        if (errorList.Count > 0)
                        {
                            settings.ChangeStatus(ImportStatusIcon.Warning, string.Format("Updated with warnings: {0}", string.Join("\n", errorList.ToArray())));
                        }
                        else
                        {
                            settings.ChangeStatus(ImportStatusIcon.Imported, "Updated");
                        }
                        return(true);
                    }
                    string serverType = itemToImport.ServerType == ServerType.OnPremise ? "OP" : (itemToImport.ServerType == ServerType.SQLServerOnAzureVM ? "AVM" : "ADB");
                    RegisteredServer.AddServer(repository.ConnectionString,
                                               connectionName, serverPort, machine, instance,
                                               (itemToImport.AuthType == SqlServerAuthenticationType.WindowsAuthentication || itemToImport.AuthType == SqlServerAuthenticationType.AzureADAuthentication) ? "W" : "S",
                                               itemToImport.UserName, itemToImport.Password,
                                               itemToImport.UseSameCredentials ? itemToImport.UserName : itemToImport.WindowsUserName,
                                               itemToImport.UseSameCredentials
                            ? itemToImport.Password
                            : itemToImport.WindowsUserPassword,
                                               sqlServerVersion, 0, new string[0], serverType);
                    repository.RefreshRegisteredServers();
                }
                catch (Exception ex)
                {
                    errorList.Add(ex.Message);

                    logX.loggerX.Error(ex.Message);
                    return(false);
                }
                var server = repository.RegisteredServers.Find(connectionName);

                //Add email notification
                try
                {
                    int providerId = Program.gController.Repository.NotificationProvider.ProviderId;
                    RegisteredServerNotification rSN =
                        new RegisteredServerNotification(SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry());
                    rSN.RegisteredServerId   = server.RegisteredServerId;
                    rSN.ProviderId           = providerId;
                    rSN.Recipients           = string.Empty;
                    rSN.SnapshotStatus       = RegisteredServerNotification.SnapshotStatusNotification_Never;
                    rSN.PolicyMetricSeverity = (int)RegisteredServerNotification.MetricSeverityNotificaiton.Never;
                    rSN.AddNotificationProvider(repository.ConnectionString);
                }
                catch (Exception ex)
                {
                    errorList.Add(ex.Message);
                }
                // Add rules to the repository.
                try
                {
                    AddRulesToRepository(repository, instance, serverInfo);
                }
                catch (Exception ex)
                {
                    errorList.Add(ex.Message);
                }

                // Add job to repository
                try
                {
                    AddJobToRepository(repository, scheduleData, connectionName);
                }
                catch (Exception ex)
                {
                    errorList.Add(ex.Message);
                }

                try
                {
                    AddServerToTags(server.RegisteredServerId);
                }
                catch (Exception ex)
                {
                    errorList.Add(ex.Message);
                }


                var errorMessage = string.Join("\n", errorList.ToArray());
                if (string.IsNullOrEmpty(errorMessage))
                {
                    settings.ChangeStatus(ImportStatusIcon.Imported, "Imported");
                }
                else
                {
                    settings.ChangeStatus(ImportStatusIcon.Warning, string.Format("Imported with warnings: {0}", errorMessage));
                }


                return(true);
            }
        }