Esempio n. 1
0
        public void UploadImage(object sender, EventArgs e)
        {
            if (UploadContainer.HasFile && Session["username"] != null)
            {
                string username       = (string)Session["username"];
                string filename       = Path.GetFileName(UploadContainer.PostedFile.FileName);
                string serverFilePath = "~/Images/" + username + "/";

                if (!CreateFolderIfNeeded(Server.MapPath(serverFilePath)))
                {
                    PageMessage.Text = "Failed to upload image. Try again later or contact the administrator of the site!";
                    return;
                }

                string randomString = RandomUtils.RandomString(10);

                string fullPath = serverFilePath + randomString + filename;

                UploadContainer.PostedFile.SaveAs(Server.MapPath(fullPath));

                int imgId = SqlUtilities.InsertIntoImages(username, fullPath, ImageDescription.Text, ImageCity.Text, ImageCountry.Text);

                ConnectWithSelectedCategories(fullPath);
                ConnectWithSelectedAlbums(fullPath);

                Response.Redirect("Image.aspx?id=" + imgId);
            }
        }
        private void LogException(Exception exception)
        {
            try
            {
                SqlUtilities sqlHelper = new SqlUtilities(new SqlConnection(ConfigurationManager.AppSettings["DSConnectionString"]));
                sqlHelper.LogExceptionToDB(LogType.WindowsService, exception.Message, exception.StackTrace);
            }
            catch (Exception DBException)
            {
                try
                {
                    LoggerService.LogError("DBException: " + DBException.ToString() + Environment.NewLine);
                }
                catch
                {
                }
            }

            try
            {
                LoggerService.LogError("Exception: " + exception.ToString());
            }
            catch (Exception LoggerException)
            {
                try
                {
                    SqlUtilities sqlHelper = new SqlUtilities(new SqlConnection(ConfigurationManager.AppSettings["DSConnectionString"]));
                    sqlHelper.LogExceptionToDB(LogType.WindowsService, LoggerException.Message, LoggerException.StackTrace);
                }
                catch
                {
                }
            }
        }
Esempio n. 3
0
        public void FillUserAlbums()
        {
            User user = new User(SqlUtilities.GetUserId((string)Session["username"]));

            SqlConnection conn      = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            string        selectTxt = "SELECT a.name, a.id FROM users u JOIN albums a ON u.id = a.id_user AND u.id = @id ORDER BY name";

            conn.Open();
            SqlCommand cmd = new SqlCommand(selectTxt, conn);

            cmd.Parameters.Add(new SqlParameter("@id", System.Data.SqlDbType.Int));
            cmd.Parameters["@id"].Value = user.Id;

            SqlDataReader result = cmd.ExecuteReader();

            while (result.Read())
            {
                string   album = result.GetValue(0).ToString();
                string   id    = result.GetValue(1).ToString();
                ListItem item  = new ListItem(album, id);
                UserAlbums.Items.Add(item);
            }
            result.Close();
            conn.Close();
            int      newAlbumValue = -1;
            ListItem lastItem      = new ListItem("New album", newAlbumValue.ToString());

            UserAlbums.Items.Add(lastItem);
        }
        void btnChangeDefaultSqlServer_Click(object sender, EventArgs e)
        {
            ChooseDefaultSqlServerDialog dlg = new ChooseDefaultSqlServerDialog()
            {
                Icon = Program.GetAppIcon()
            };

            dlg.VerifyConnectionString = true;
            DialogResult dr = dlg.ShowDialog();

            if (dr == DialogResult.OK)
            {
                if (dlg.SqlDataSourceType == SqlDataSourceEnum.SqlServer)
                {
                    string connectionString = dlg.GetConnectionString("master");
                    string connectionErrorMessage;

                    if (SqlUtilities.TestSQLConnectionString(connectionString, out connectionErrorMessage))
                    {
                        DefaultSqlConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
                        SetDefaultSqlServerLabel();
                    }
                    else
                    {
                        Messager.ShowWarning(this, connectionErrorMessage);
                    }
                }
                else // SqlDataSourceEnum.SqlServerCompact
                {
                    DefaultSqlConnectionStringBuilder = null;
                    SetDefaultSqlServerLabel();
                }
            }
        }
Esempio n. 5
0
        protected void ValidateRunningJobs()
        {
            Dictionary <String, Object> sqlParameters = new Dictionary <String, Object>();

            sqlParameters.Add(":machinename", Environment.MachineName);

            // Pull the jobs running on this machine.
            DataTable dt = SqlUtilities.GetData(_ConnectionString, _SqlJobsInProgress, sqlParameters);

            if ((dt != null) && (dt.Rows != null) && (dt.Rows.Count > 0))
            {
                sqlParameters.Add(":inprogress", false);
                sqlParameters.Add(":scanrequested", false);
                sqlParameters.Add(":jobstatus", "Error");
                sqlParameters.Add(":statusdescription", "See activity log for details.");
                sqlParameters.Add(":pkey", -1);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        if (!MiscUtilities.isAlive(dt.Rows[i]["definition_name"].ToString()))
                        {
                            sqlParameters[":pkey"] = MiscUtilities.ObjectToInteger(dt.Rows[i]["pkey"], "No primary key defined.");
                            SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters);
                        }
                    }
                    catch (Exception ex)
                    {
                        LocalLog.AddLine("Error while updating in progress job status.  Error message was: " + ex.Message);
                        _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                    }
                }
            }
        }
Esempio n. 6
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Session["username"] != null && !string.IsNullOrEmpty((string)Session["username"]))
     {
         string username = (string)Session["username"];
         User   user     = new User(SqlUtilities.GetUserId(username));
         if (user.IsAdmin)
         {
             IsAdmin.Visible = true;
         }
         else
         {
             if (Request.UrlReferrer != null)
             {
                 Response.Redirect(Request.UrlReferrer.ToString());
             }
             else
             {
                 Response.Redirect("Profile.aspx?username=" + username);
             }
         }
     }
     if (SqlUtilities.GetAdmins() == null)
     {
         IsAdmin.Visible = true;
     }
     if (!IsPostBack)
     {
         Populate_MonthList();
         Populate_YearList();
     }
 }
Esempio n. 7
0
        private void PopulateDropDown()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                SqlConnectionStringBuilder connectionBuilder;


                connectionBuilder = new SqlConnectionStringBuilder( );

                connectionBuilder.DataSource         = serverNameCoboBox.Text;
                connectionBuilder.IntegratedSecurity = windowsAuthenticationRadioButton.Checked;
                connectionBuilder.UserID             = userNameTextBox.Text;
                connectionBuilder.Password           = passwordTextBox.Text;

                serverDatabaseComboBox.DataSource = SqlUtilities.GetDatabaseList(connectionBuilder);
            }
            catch (Exception exp)
            {
                serverDatabaseComboBox.DataSource = null;

                serverDatabaseComboBox.Items.Clear( );

                Messager.ShowError(this, exp);

                System.Diagnostics.Debug.Assert(false);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Esempio n. 8
0
        public void RegisterSubmitClick(object sender, EventArgs e)
        {
            if (!RegistrationFieldsValid())
            {
                PageMessage.Text = "Registration fields are invalid";
                return;
            }
            if (!UsernameAvailable())
            {
                PageMessage.Text = "Username is already used for an account";
                return;
            }
            if (!EmailAvailable())
            {
                PageMessage.Text = "Email is already user for an account";
                return;
            }

            bool isAdmin = false;

            if (IsAdmin.Visible && IsAdmin.Checked)
            {
                isAdmin = true;
            }

            SqlUtilities.InsertIntoUsers(Username.Text, FirstName.Text, LastName.Text, Email.Text, BirthdayCalendar.SelectedDate, Password.Text, isAdmin);

            Session["username"] = Username.Text;

            Response.Redirect(string.Format("Profile.aspx?username={0}", Username.Text));
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            foreach (string command in args)
            {
                if (String.Compare(command, "EnableUserHost", true) == 0)
                {
                    _enableUserHost = true;
                    break;
                }
            }

            // This application requires admin privileges if this is a Windows Vista or 7 machine
            if (!CheckAdminRights(args))
            {
                return;
            }

            bool   userHost         = true;
            string address          = string.Empty;
            string connectionString = string.Empty;

            Properties.Settings settings = new Properties.Settings();
            if (settings["HostAddress"] != null)
            {
                address = settings.HostAddress;
            }
            if (settings["UserHost"] != null)
            {
                userHost = settings.UserHost;
            }
            if (settings["ConnectionString"] != null)
            {
                connectionString = settings.ConnectionString;
            }

            if (String.IsNullOrEmpty(address))
            {
                address = string.Format("http://{0}:8181/LEADTOOLSJobProcessorServices", Environment.MachineName);
            }

            ConnectionForm connectionForm = new ConnectionForm(userHost, address, connectionString, "LEADTOOLS C# JobProcessor Administrator Demo", false, _enableUserHost);

            connectionForm.Type = ServicesType.JobProcessorJobService;

            if (connectionForm.ShowDialog() == DialogResult.OK)
            {
                if (SqlUtilities.IsDatabaseExist(connectionForm.ConnectionString))
                {
                    Application.Run(new MainForm(connectionForm.Address, connectionForm.UserHost, connectionForm.ConnectionString));
                }
                else
                {
                    MessageBox.Show("The specified database was not found. Please ensure the database is available.", "Error");
                }
            }
        }
Esempio n. 10
0
 public WidgetBusiness()
 {
     //
     // TODO (Demo Mode) - load seed data to database
     //
     //MongoDbUtilities.WriteSeedDataToDatabase();
     SqlUtilities.WriteSeedDataToDatabase();
 }
        private void buttonValidate_Click(object sender, EventArgs e)
        {
            string         connectionString  = GetConnectionString("master");
            bool           bThreadTestResult = false;
            AutoResetEvent enumServersEvent  = new AutoResetEvent(false);

            Exception error = null;

            if (VerifyConnectionString)
            {
                Thread validateConnectionStringThread = new Thread(delegate()
                {
                    try
                    {
                        bThreadTestResult = ThreadTest(connectionString);
                    }
                    catch (Exception exp)
                    {
                        error = exp;
                    }
                    finally
                    {
                        enumServersEvent.Set();
                    }
                });

                validateConnectionStringThread.Start();
                EnumenratingSQLServersDialog enumDlg = new EnumenratingSQLServersDialog();
                enumDlg.WaitMessage = "Validating Connection String...";

                enumDlg.Show(this);
                enumServersEvent.WaitOne();
                enumDlg.Close();
                if (bThreadTestResult)
                {
                    string         sMsg           = "Connection String is valid";
                    MessageBoxIcon messageBoxIcon = MessageBoxIcon.None;

                    if (SqlUtilities.IsSqlServer2012OrLater(_sqlServerVersion) && sqlServerConfiguration1.IsWindowsAuthentication())
                    {
                        sMsg = "It is recommended to select the 'Use SQL Server Authentication' option.\n\n" +
                               "You are connecting to a version of SQL Server 2012 or later, where  NT_AUTHORITY\\System is no longer installed by default.  This can cause problems with the DICOM Server Components";
                        messageBoxIcon = MessageBoxIcon.Warning;
                    }
                    buttonOk.Enabled = true;
                    _validated       = true;
                    MessageBox.Show(sMsg, "Connection String Validation", MessageBoxButtons.OK, messageBoxIcon);
                }
                else
                {
                    _validated = false;
                    MessageBox.Show(_connectionErrorMessage, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
 public void AddTaggingNotificationRecord()
 {
     try
     {
         SqlUtilities sqlHelper = new SqlUtilities(new SqlConnection(ConfigurationManager.AppSettings["DSConnectionString"]));
         sqlHelper.ExecuteNonQuery("TaggingService_AddTaggingNotificationDetails");
     }
     catch (Exception ex)
     {
         LogException(ex);
     }
 }
Esempio n. 13
0
        private void ConnectWithSelectedCategories(string imgPath)
        {
            int imgId = SqlUtilities.GetImageId(imgPath);

            foreach (ListItem item in ImageCategories.Items)
            {
                int categId;
                if (item.Selected && int.TryParse(item.Value, out categId))
                {
                    SqlUtilities.InsertIntoBelongsTo(imgId, categId);
                }
            }
        }
Esempio n. 14
0
        protected Boolean BackupCastDatabase(int JobKey, String JobFileName, String RawJobFileName)
        {
            Dictionary <String, Object> sqlParameters = new Dictionary <string, object>();

            sqlParameters.Add(":inprogress", true);
            sqlParameters.Add(":scanrequested", true);
            sqlParameters.Add(":jobstatus", "Ready");
            sqlParameters.Add(":statusdescription", String.Format("Backup Started: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now));
            sqlParameters.Add(":machinename", Environment.MachineName);
            sqlParameters.Add(":jobkey", JobKey);

            JobFileName = _tokens.Resolve("Scheduler", "BackupDatabase", "Missing the Scheduler/BackupDatabase attribute with the name of the backup definition. SQL query. Please add the name of the backup definition to the settings file under SchedulerSettings/Tokens/Scheduler BackupDatabase");
            // Look for backup database request
            DataTable dt = SqlUtilities.GetData(_ConnectionString, _SqlNextDbBackup);

            if ((dt == null) || (dt.Rows.Count == 0))
            {
                return(false);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                try
                {
                    JobKey = MiscUtilities.ObjectToInteger(dt.Rows[0]["pkey"], "No primary key is definied");
                    sqlParameters[":jobkey"] = JobKey;
                    RunJava(JobKey, JobFileName, RawJobFileName);

                    // Job finished update record.
                    sqlParameters[":jobstatus"]         = "Backup Completed";
                    sqlParameters[":statusdescription"] = String.Format("Backup Completed: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now);
                }
                catch (Exception ex)
                {
                    LocalLog.AddLine("Database Backup Error: " + ex.Message);
                    sqlParameters[":jobstatus"] = "Error";
                    String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                    if (message.Length > 99)
                    {
                        message = message.Substring(0, 99);
                    }
                    sqlParameters[":statusdescription"] = message;
                }
                SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters);
            }
            return(false);
        }
Esempio n. 15
0
        private void ConnectWithSelectedAlbums(string imgPath)
        {
            int imgId = SqlUtilities.GetImageId(imgPath);

            foreach (ListItem item in UserAlbums.Items)
            {
                int albumId;
                if (item.Selected && int.TryParse(item.Value, out albumId))
                {
                    if (albumId == -1)
                    {
                        albumId = SqlUtilities.InsertIntoAlbums(NewAlbumName.Text, (string)Session["username"]);
                    }
                    SqlUtilities.InsertIntoIncludedIn(imgId, albumId);
                }
            }
        }
Esempio n. 16
0
        protected Boolean RunDefinition(int JobKey, String JobFileName, String RawJobFileName, String processingMessage)
        {
            Dictionary <String, Object> sqlParameters = new Dictionary <string, object>();

            sqlParameters.Add(":inprogress", true);
            sqlParameters.Add(":scanrequested", true);
            sqlParameters.Add(":jobstatus", processingMessage);
            sqlParameters.Add(":statusdescription", String.Format("Started: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now));
            sqlParameters.Add(":machinename", Environment.MachineName);
            sqlParameters.Add(":jobkey", JobKey);

            try
            {
                SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters);
                // Shell to the JAVA program and run it.
                RunJava(JobKey, JobFileName, RawJobFileName);

                // Job finished update record.
                sqlParameters[":inprogress"]        = false;
                sqlParameters[":scanrequested"]     = false;
                sqlParameters[":jobstatus"]         = "Completed";
                sqlParameters[":statusdescription"] = String.Format("Completed: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now);
                sqlParameters[":machinename"]       = null;

                // Error out this queue item and rest for this application.
            }
            catch (Exception ex)
            {
                LocalLog.AddLine("Code Scan Error: " + ex.Message);
                LocalLog.AddLine(ex);

                String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                if (message.Length > 99)
                {
                    message = message.Substring(0, 99);
                }
                sqlParameters[":statusdescription"] = message;
                sqlParameters[":inprogress"]        = false;
                sqlParameters[":scanrequested"]     = false;
                sqlParameters[":jobstatus"]         = "Error";
                sqlParameters[":machinename"]       = null;
            }
            SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters);
            return(false);
        }
Esempio n. 17
0
        protected Boolean BackupCastDatabase()
        {
            Dictionary <String, Object> sqlParameters = new Dictionary <string, object>();

            sqlParameters.Add(":jobkey", _JobKey);
            sqlParameters.Add(":jobstatus", "Ready");
            sqlParameters.Add(":statusdescription", "Ready");

            try
            {
                // Look for the next rescan request.
                DataTable requests = SqlUtilities.GetData(_ConnectionString, "SELECT pkey, definition_name, scan_status, dbprefix FROM fnma_measure8.scan_manager WHERE in_progress and scan_status='Backup Database'");
                if ((requests == null) || (requests.Rows.Count == 0))
                {
                    return(false);
                }

                _JobKey                  = (int)requests.Rows[0]["pkey"];
                _JobFileName             = (String)requests.Rows[0]["definition_name"];
                sqlParameters[":jobkey"] = _JobKey;
                _JobFileName             = "DatabaseBackup.xml";

                // Shell to the JAVA program and run it.
                RunJava();

                // Job finished update record.
                sqlParameters[":jobstatus"]         = "Backup Completed";
                sqlParameters[":statusdescription"] = String.Format("Backup Completed: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now);
            }
            catch (Exception ex)
            {
                LocalLog.AddLine("Database Backup Error: " + ex.Message);
                sqlParameters[":jobstatus"] = "Error";
                String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                if (message.Length > 99)
                {
                    message = message.Substring(0, 99);
                }
                sqlParameters[":statusdescription"] = message;
            }

            SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateStatus, sqlParameters);
            return(false);
        }
        public static void InstallDatabase(string connectionString)
        {
            string message;
            SqlConnectionStringBuilder csB = new SqlConnectionStringBuilder(connectionString);

            if (SqlUtilities.DatabaseExist(csB))
            {
                message = string.Format("--- Deleting Previous Database [{0}]...", csB.InitialCatalog);
                MyLogger.ShowMessage(message);
                SqlUtilities.DeleteDbIfExists(csB, 1000, MyCallbacks.MyDatabaseCallback);
            }

            message = string.Format("--- Creating New Database [{0}]...", csB.InitialCatalog);
            MyLogger.ShowMessage(message);

            SqlUtilities.CreateDatabase(csB, 1000, MyCallbacks.MyDatabaseCallback);

            CreateSqlTables(connectionString);
        }
Esempio n. 19
0
        protected void CheckScheduledJobs()
        {
            DateTime currentDateTime = DateTime.Now;

            // Check = SELECT pkey, definition_name FROM fnma_measure8.scan_manager WHERE scheduled_date is not null and scheduled_date &lt; current_timestamp and definition_name is not null
            // Queue = UPDATE fnma_measure8.scan_manager SET scan_requested=true, request_date=current_timestamp, scan_status='Queued', machine_name=null, scheduled_date=null WHERE pkey=:key and scan_requested=false and machine_name is null and in_progress=false and scan_status='Completed'

            // Put here to lighten the load on the database server, system checks schedules every 2 minutes.
            // With 4 machines running this code, the offset between them should ensure pretty quick schedule pickups.
            if (_nextScheduleCheck > currentDateTime)
            {
                return;
            }

            DataTable dt = SqlUtilities.GetData(_ConnectionString, _sqlScheduleCheck);

            if ((dt != null) && (dt.Rows != null) && (dt.Rows.Count > 0))
            {
                Dictionary <String, Object> sqlParameters = new Dictionary <String, Object>();
                sqlParameters.Add(":key", -1);
                sqlParameters.Add(":requestdate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string job_name = "";
                    try
                    {
                        if ((DateTime)dt.Rows[i]["scheduled_date"] < DateTime.Now)
                        {
                            job_name = MiscUtilities.ObjectToStringDefault(dt.Rows[i]["definition_name"], "Definition name is blank.");
                            sqlParameters[":key"] = MiscUtilities.ObjectToInteger(dt.Rows[i]["pkey"], "No primary key defined.");
                            SqlUtilities.ExcecuteNonQuery(_ConnectionString, _sqlQueueScheduledJob, sqlParameters);
                        }
                    }
                    catch (Exception ex)
                    {
                        LocalLog.AddLine("Error while queuing scheduled job.  Error message was: " + ex.Message);
                        _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                    }
                }
            }
            _nextScheduleCheck = DateTime.Now.AddMinutes(2);
        }
        private bool ThreadTest(string connectionString)
        {
            string connectionErrorMessage;

            _sqlServerVersion = string.Empty;

            if (VerifyConnectionString)
            {
                if (SqlUtilities.TestSQLConnectionString(connectionString, out connectionErrorMessage, out _sqlServerVersion))
                {
                    return(true);
                }
                else
                {
                    _connectionErrorMessage = connectionErrorMessage;
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 21
0
        protected DataRow GetNextJob()
        {
            try
            {
                Dictionary <String, Object> sqlParameters = new Dictionary <String, Object>();
                sqlParameters.Add(":machinename", Environment.MachineName);

                DataTable dt = SqlUtilities.GetData(_ConnectionString, _SqlNextJob, sqlParameters);
                if ((dt != null) && (dt.Rows != null) && (dt.Rows.Count > 0))
                {
                    return(dt.Rows[0]);
                }
                return(null);
            }
            catch (Exception ex)
            {
                LocalLog.AddLine("Error while getting next job from queue.  Error message was: " + ex.Message);
                _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
            }
            return(null);
        }
Esempio n. 22
0
        protected Boolean RunDefinition(String processingMessage)
        {
            Dictionary <String, Object> sqlParameters = new Dictionary <string, object>();

            sqlParameters.Add(":jobkey", _JobKey);
            sqlParameters.Add(":jobstatus", "Ready");
            sqlParameters.Add(":statusdescription", "Ready");

            try
            {
                sqlParameters[":jobkey"] = _JobKey;

                // Run the definition and wait till it finishes.
                sqlParameters[":jobstatus"]         = processingMessage;
                sqlParameters[":statusdescription"] = String.Format("Started: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now);
                SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateStatus, sqlParameters);

                // Shell to the JAVA program and run it.
                RunJava();

                // Job finished update record.
                sqlParameters[":jobstatus"]         = "Completed";
                sqlParameters[":statusdescription"] = String.Format("Completed: {0:MMMM d, yyyy HH:mm:ss}", DateTime.Now);
                // Error out this queue item and rest for this application.
            }
            catch (Exception ex)
            {
                LocalLog.AddLine("Code Scan Error: " + ex.Message);
                sqlParameters[":jobstatus"] = "Error";
                String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                if (message.Length > 99)
                {
                    message = message.Substring(0, 99);
                }
                sqlParameters[":statusdescription"] = message;
                SqlUtilities.ExcecuteNonQuery(_ConnectionString, String.Format("UPDATE fnma_measure8.automated_queue SET ready=false, status='ERROR' WHERE ready and scan_manager_pkey={0}", _JobKey));
            }
            SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlJobFinished, sqlParameters);
            return(false);
        }
Esempio n. 23
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            _txtAddress.Text    = GetMachineIP();
            _txtAddress.Enabled = false;

            if (ConfigurationManager.ConnectionStrings["LEADTOOLSJobProcessorDB"] != null)
            {
                SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["LEADTOOLSJobProcessorDB"].ConnectionString);
                if (SqlUtilities.IsDatabaseExist(sqlConnectionStringBuilder.ConnectionString))
                {
                    _lstvwDatabases.Items.Clear();
                    _lstvwDatabases.Items.Add(new ListViewItem(new string[] { "Server", sqlConnectionStringBuilder.DataSource }));
                    _lstvwDatabases.Items.Add(new ListViewItem(new string[] { "Database", sqlConnectionStringBuilder.InitialCatalog }));
                    if (!sqlConnectionStringBuilder.IntegratedSecurity)
                    {
                        _lstvwDatabases.Items.Add(new ListViewItem(new string[] { "User Id", sqlConnectionStringBuilder.UserID }));
                    }
                    else
                    {
                        _lstvwDatabases.Items.Add(new ListViewItem(new string[] { "User Id", "Trusted Connection" }));
                    }
                }
            }
        }
Esempio n. 24
0
        public Boolean ProcessQueue()
        {
            try
            {
                if (this._IsDbBackup)
                {
                    return(BackupCastDatabase());
                }
                else
                {
                    Dictionary <String, Object> aParams = new Dictionary <String, Object>();
                    aParams.Add(":machinename", Environment.MachineName);

                    // Set any definitions left in_progress from previous run to error. -- turned off, to test.
                    SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlErrorOutInProgress, aParams);

                    // Update next ready record with machine name
                    int gotOne = SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlNextJob, aParams);
                    if (gotOne == 0)
                    {
                        return(false);
                    }

                    // Check for next request
                    DataTable requests = SqlUtilities.GetData(_ConnectionString, _SqlNextJob, aParams);
                    if ((requests == null) || (requests.Rows.Count == 0))
                    {
                        // Ready the next application in the automated queue
                        DataTable next_automated_queue = SqlUtilities.GetData(_ConnectionString, "SELECT scan_manager_pkey, code_loc_type, code_loc_url, version_name FROM fnma_measure8.automated_queue WHERE ready and scan_manager_pkey > 0 ORDER BY scan_order, id");
                        if ((next_automated_queue != null) && (next_automated_queue.Rows.Count > 0))
                        {
                            int updatedCount = 0;
                            int lastPkey     = -1;
                            foreach (DataRow dr in next_automated_queue.Rows)
                            {
                                int scanManagerPkey = ObjectToInteger(dr["scan_manager_pkey"], "No scan_manager_pkey is definied");
                                if (scanManagerPkey == lastPkey)
                                {
                                    continue;
                                }

                                lastPkey = scanManagerPkey;
                                try
                                {
                                    int    codeLocationType = ObjectToInteger(dr["code_loc_type"], "No code_loc_type definied");
                                    String codeLocationUrl  = ObjectToString(dr["code_loc_url"], "No code_loc_url defined.");
                                    String versionName      = ObjectToString(dr["version_name"], "No version_name defined.");
                                    String request_date     = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);

                                    // Queue the next rescan
                                    updatedCount = SqlUtilities.ExcecuteNonQuery(_ConnectionString, String.Format("UPDATE fnma_measure8.scan_manager SET scan_requested=true, request_date='{0}', scan_status='Queued', code_url='{1}', code_version='{2}', action_requested='rescan', code_location_type={3} WHERE pkey={4} and machine_name is null and in_progress=false and scan_requested=false and scan_status='Completed'", request_date, codeLocationUrl, versionName, codeLocationType, scanManagerPkey));
                                }
                                catch (Exception exAutomated)
                                {
                                    String error = exAutomated.Message;
                                    // Error out this queue item and rest for this application.
                                    SqlUtilities.ExcecuteNonQuery(_ConnectionString, String.Format("UPDATE fnma_measure8.automated_queue SET ready=false, status='ERROR' WHERE ready and scan_manager_pkey={0}", scanManagerPkey));
                                }
                                if (updatedCount > 0)
                                {
                                    break;
                                }
                            }
                        }
                        //if ((next_automated_queue != null) && (next_automated_queue.Rows.Count > 0))
                        //{
                        //    int scanManagerPkey = ObjectToInteger(next_automated_queue.Rows[0]["scan_manager_pkey"], "No scan_manager_pkey is definied");
                        //    try
                        //    {
                        //        int codeLocationType = ObjectToInteger(next_automated_queue.Rows[0]["code_loc_type"], "No code_loc_type definied");
                        //        String codeLocationUrl = ObjectToString(next_automated_queue.Rows[0]["code_loc_url"], "No code_loc_url defined.");
                        //        String versionName = ObjectToString(next_automated_queue.Rows[0]["version_name"], "No version_name defined.");
                        //        String request_date = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);

                        //        // Queue the next rescan
                        //        SqlUtilities.ExcecuteNonQuery(_ConnectionString, String.Format("UPDATE fnma_measure8.scan_manager SET scan_requested=true, request_date='{0}', scan_status='Queued', code_url='{1}', code_version='{2}', action_requested='rescan', code_location_type={3}, machine_name='{5}' WHERE pkey={4} and machine_name is null", request_date, codeLocationUrl, versionName, codeLocationType, scanManagerPkey, Environment.MachineName));
                        //    }
                        //    catch (Exception exAutomated)
                        //    {
                        //        String error = exAutomated.Message;
                        //        // Error out this queue item and rest for this application.
                        //        SqlUtilities.ExcecuteNonQuery(_ConnectionString, String.Format("UPDATE fnma_measure8.automated_queue SET ready=false, status='ERROR' WHERE ready and scan_manager_pkey={0}", scanManagerPkey));
                        //    }
                        //}
                        return(false);
                    }


                    _JobKey         = ObjectToInteger(requests.Rows[0]["pkey"], "No primary key is definied");
                    _JobFileName    = ObjectToString(requests.Rows[0]["definition_name"], "No definition file name is defined.");
                    _RawJobFileName = _JobFileName;

                    // Until the UI is updated, defaulting to 'rescan'
                    //String action_requested = ObjectToString(requests.Rows[0]["action_requested"], "Action_request value is null.  Typical actions include Publish, Rescan, or Onboard.");
                    String action_requested = ObjectToStringDefault(requests.Rows[0]["action_requested"], "rescan");

                    String message = "Scanning";
                    switch (action_requested.ToLower())
                    {
                    case "publish":
                        _JobFileName = ReadTokenValue("SelfServiceScan", "PublishDefinition", "No publish definition defined in the settings file.  Please add a Tokens/SelfServiceScan PublishDefinition");
                        message      = "Publishing";
                        break;

                    case "empty":
                    case "rescan":
                        message = "Processing";
                        break;

                    case "onboard":
                        _JobFileName = ReadTokenValue("SelfServiceScan", "OnBoardDefinition", "No onboard definition defined in the settings file.  Please add a Tokens/SelfServiceScan OnBoardDefinition");
                        message      = "OnBoarding";
                        break;

                    default:
                        throw new Exception(String.Format("{0} is not a valid action request.", action_requested));
                    }
                    return(RunDefinition(message));
                }
            }
            catch (Exception ex)
            {
                LocalLog.AddLine("Queue Error: " + ex.Message);
                _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);

                if (_JobKey > 0)
                {
                    Dictionary <String, Object> aParams = new Dictionary <string, object>();
                    aParams.Add(":jobkey", _JobKey);
                    aParams.Add(":jobstatus", "Error");
                    String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                    if (message.Length > 99)
                    {
                        message = message.Substring(0, 99);
                    }
                    aParams.Add(":statusdescription", message);
                    SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlJobFinished, aParams);
                }
            }
            return(false);
        }
        public void TagScriptsToReleaseVehicle()
        {
            try
            {
                DataTable tagScripts = new DataTable();
                tagScripts.Columns.Add("NoSoonerThan", typeof(DateTime));
                tagScripts.Columns.Add("NoLaterThan", typeof(DateTime));
                tagScripts.Columns.Add("ReleaseID", typeof(int));
                tagScripts.Columns.Add("ReleaseName", typeof(string));
                tagScripts.Columns.Add("ReleaseStartDate", typeof(DateTime));
                tagScripts.Columns.Add("ReleaseEndDate", typeof(DateTime));
                tagScripts.Columns.Add("TechnicalSignoffID", typeof(int));
                tagScripts.Columns.Add("TechnicalSignoffstartdate", typeof(DateTime));
                tagScripts.Columns.Add("TechnicalSignoffEnddate", typeof(DateTime));
                tagScripts.Columns.Add("ReleaseType", typeof(string));


                DataSet      dataSet   = new DataSet();
                SqlUtilities sqlHelper = new SqlUtilities(new SqlConnection(ConfigurationManager.AppSettings["DSConnectionString"]));
                dataSet = sqlHelper.GetDataSet("TaggingService_GetNotTaggedScripts");

                if (dataSet.Tables[0] != null && dataSet.Tables[0].Rows.Count > 0)
                {
                    SqlUtilities DOMOSQLHelper = new SqlUtilities(new SqlConnection(ConfigurationManager.AppSettings["DOMOAutomationConnectionString"]));
                    foreach (DataRow row in dataSet.Tables[0].Rows)
                    {
                        DataSet dsReleaseCalendarDetails = DOMOSQLHelper.GetDataSet("GetReleaseCalendarEventDates",
                                                                                    new List <CommandParameter> {
                            new CommandParameter {
                                Name = "NoSoonerDate", Type = SqlDbType.DateTime, Value = row["NoSoonerThan"].ToString()
                            },
                            new CommandParameter {
                                Name = "NoLongerDate", Type = SqlDbType.DateTime, Value = row["NoLaterThan"].ToString()
                            }
                        });
                        if (dsReleaseCalendarDetails != null && dsReleaseCalendarDetails.Tables[0] != null && dsReleaseCalendarDetails.Tables[0].Rows.Count > 0 && dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseType"].ToString() != "101")
                        {
                            tagScripts.Rows.Add(row["NoSoonerThan"].ToString(),
                                                row["NoLaterThan"].ToString(),
                                                Convert.ToInt32(dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseID"]),
                                                dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseName"].ToString(),
                                                Convert.ToDateTime(dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseStartDate"]),
                                                Convert.ToDateTime(dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseEndDate"]),
                                                Convert.ToInt32(dsReleaseCalendarDetails.Tables[0].Rows[0]["TechnicalSignoffID"]),
                                                Convert.ToDateTime(dsReleaseCalendarDetails.Tables[0].Rows[0]["TechnicalSignoffstartdate"]),
                                                Convert.ToDateTime(dsReleaseCalendarDetails.Tables[0].Rows[0]["TechnicalSignoffEnddate"]),
                                                dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseType"].ToString());
                        }
                        else
                        {
                            tagScripts.Rows.Add(row["NoSoonerThan"].ToString(),
                                                row["NoLaterThan"].ToString(),
                                                null,
                                                null,
                                                null,
                                                null,
                                                null,
                                                null,
                                                null,
                                                dsReleaseCalendarDetails != null && dsReleaseCalendarDetails.Tables[0] != null && dsReleaseCalendarDetails.Tables[0].Rows.Count > 0
                                                        ? dsReleaseCalendarDetails.Tables[0].Rows[0]["ReleaseType"].ToString() : null);
                        }
                    }

                    if (tagScripts.Rows.Count > 0)
                    {
                        sqlHelper.ExecuteNonQuery("TaggingService_TagScriptsToReleaseVehicle",
                                                  new List <CommandParameter> {
                            new CommandParameter {
                                Name = "ReleaseCalendarDetails", Type = SqlDbType.Structured, Value = tagScripts
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
Esempio n. 26
0
        void SqlServerConfiguration_Load(object sender, EventArgs e)
        {
            refreshServersButton.Visible = Program.ShouldEnumerateSqlServers;
            labelDataSource.Visible      = !Program.ShouldEnumerateSqlServers;
            this.Cursor = Cursors.WaitCursor;

            string selectedServer = serverNameCoboBox.Text;

            try
            {
                if (Program.ShouldEnumerateSqlServers)
                {
                    if (!_DesignMode)
                    {
                        AutoResetEvent enumServersEvent = new AutoResetEvent(false);
                        Exception      error            = null;
                        Thread         getServersThread;

                        getServersThread = new Thread(delegate()
                        {
                            try
                            {
                                servers = SqlUtilities.GetServerList();
                            }
                            catch (Exception exp)
                            {
                                error = exp;
                            }
                            finally
                            {
                                enumServersEvent.Set();
                            }
                        });

                        if (servers == null)
                        {
                            getServersThread.Start();


                            EnumenratingSQLServersDialog enumDlg = new EnumenratingSQLServersDialog();

                            enumDlg.Show(this);

                            enumServersEvent.WaitOne();

                            enumDlg.Close();
                        }

                        if (null != error)
                        {
                            throw error;
                        }
                        else
                        {
                            string[] localServers = SqlUtilities.GetLocalSQLServerInstances();

                            if (servers.Count > 0)
                            {
                                serverNameCoboBox.DataSource = servers;

                                if (localServers != null && localServers.Length > 0)
                                {
                                    serverNameCoboBox.Text = localServers[0];
                                }
                            }
                            else
                            {
                                serverNameCoboBox.DataSource = localServers;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);

                serverNameCoboBox.DataSource = SqlUtilities.GetLocalSQLServerInstances( );

                Messager.ShowWarning(this,
                                     "The application can't enumerate the SQL Servers located in your network because \"Microsoft SQL Server 2008 Management Objects (SMO)\" is not installed.\n" +
                                     "You can manually type the SQL Server name in the server name field or install Microsoft SMO from Microsoft site:\n" +
                                     "http://www.microsoft.com/downloadS/details.aspx?familyid=C6C3E9EF-BA29-4A43-8D69-A2BED18FE73C&displaylang=en");

                return;
            }
            finally
            {
                if (!string.IsNullOrEmpty(selectedServer))
                {
                    serverNameCoboBox.Text = selectedServer;
                }

                this.Cursor = Cursors.Default;
            }
        }
Esempio n. 27
0
        public bool IsConnectionStringValid(out string connectionErrorMessage, List <string> databaseLocations)
        {
            try
            {
                if (Mode == DbConfigurationMode.Create)
                {
                    if (sqlServerConfiguration.Visible)
                    {
                        SqlConnectionStringBuilder csB;


                        csB = new SqlConnectionStringBuilder(sqlServerConfiguration.ConnectionString);

                        if (string.IsNullOrEmpty(csB.InitialCatalog))
                        {
                            connectionErrorMessage = "Database name is empty";

                            return(false);
                        }
                        else
                        {
                            string dbName;
                            string fop;


                            dbName = csB.InitialCatalog;
                            fop    = csB.FailoverPartner;

                            csB.InitialCatalog  = string.Empty;
                            csB.FailoverPartner = string.Empty;

                            if (SqlUtilities.TestSQLConnectionString(csB.ConnectionString, out connectionErrorMessage))
                            {
                                csB.InitialCatalog  = dbName;
                                csB.FailoverPartner = fop;

                                if (IsDatabaseLocationAlreadyUsed(databaseLocations, ConnectionString, csB.InitialCatalog, out connectionErrorMessage))
                                {
                                    return(false);
                                }

                                else if (SqlUtilities.DatabaseExist(csB))
                                {
                                    DialogResult deleteExistent;


                                    deleteExistent = Messager.ShowQuestion(this,
                                                                           "The database you selected already exists.\n\nDo you want to delete the existing database and create a new one?\n\n" +
                                                                           "Click 'Yes' to delete the existing database or click 'No' to change the database name.",
                                                                           MessageBoxButtons.YesNo);

                                    if (deleteExistent == DialogResult.No)
                                    {
                                        connectionErrorMessage = string.Empty;//string.Format ( "Database {0} already exists. Please select a different database name.", dbName ) ;

                                        sqlServerConfiguration.SetComponentFocus(SqlServerConfiguration.ConnectionStringCommponents.Database);

                                        return(false);
                                    }
                                    else
                                    {
                                        connectionErrorMessage = string.Empty;

                                        return(true);
                                    }
                                }
                                else
                                {
                                    connectionErrorMessage = string.Empty;

                                    return(true);
                                }
                            }
                            else
                            {
                                sqlServerConfiguration.SetComponentFocus(SqlServerConfiguration.ConnectionStringCommponents.Server);

                                return(false);
                            }
                        }
                    }
                    else
                    {
                        connectionErrorMessage = string.Empty;

                        if (String.IsNullOrEmpty(sqlCeConfiguration.ConnectionString))
                        {
                            connectionErrorMessage = "Database name is empty";

                            return(false);
                        }
                        else if (IsDatabaseLocationAlreadyUsed(databaseLocations, ConnectionString, sqlCeConfiguration.DatabaseLocation, out connectionErrorMessage))
                        {
                            return(false);
                        }
                        else if (File.Exists(sqlCeConfiguration.DatabaseLocation))
                        {
                            DialogResult deleteExistent;


                            deleteExistent = Messager.ShowQuestion(this,
                                                                   "The database you selected already exists.\n\nDo you want to delete the existing database and create a new one?\n\n" +
                                                                   "Click 'Yes' to delete the existing database or click 'No' to change the database name.",
                                                                   MessageBoxButtons.YesNo);

                            if (deleteExistent == DialogResult.No)
                            {
                                connectionErrorMessage = string.Empty; //string.Format ( "Database {0} already exists. Please select a different database name.", sqlCeConfiguration.DatabaseLocation ) ;

                                return(false);
                            }
                            else
                            {
                                return(true);
                            }
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
                else
                {
                    if (sqlServerConfiguration.Visible)
                    {
                        SqlConnectionStringBuilder csB = new SqlConnectionStringBuilder(sqlServerConfiguration.ConnectionString);

                        if (string.IsNullOrEmpty(csB.InitialCatalog))
                        {
                            connectionErrorMessage = "Database name is empty";

                            return(false);
                        }

                        csB.Pooling = false;

                        if (IsDatabaseLocationAlreadyUsed(databaseLocations, ConnectionString, csB.InitialCatalog, out connectionErrorMessage))
                        {
                            return(false);
                        }

                        return(SqlUtilities.TestSQLConnectionString(csB.ConnectionString, out connectionErrorMessage));
                    }
                    else
                    {
                        return(IsConnectionStringValidSqlCe(databaseLocations, out connectionErrorMessage));
                    }
                }
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.Assert(false, exception.Message);

                throw;
            }
        }
Esempio n. 28
0
        public static void DebugWrite(this IDbConnection db, string sql, List <DbParameter> parameters)
        {
            var st = ArgsAsSql(sql, parameters);

            SqlUtilities.Log(st);
        }
Esempio n. 29
0
        public void ProcessQueue()
        {
            int JobKey = -1;

            try
            {
                // Validate the processing job and update those that are no long running.
                ValidateRunningJobs();
                // Check for any scheduled work
                CheckScheduledJobs();
                // Check for any queued work
                DataRow dr = GetNextJob();
                if (dr == null)
                {
                    return;
                }

                JobKey = MiscUtilities.ObjectToInteger(dr["pkey"], "No primary key is definied");
                String JobFileName      = MiscUtilities.ObjectToString(dr["definition_name"], "No definition file name is defined.");
                String RawJobFileName   = JobFileName;
                String lockFilename     = MiscUtilities.LockFilename(RawJobFileName);
                String action_requested = MiscUtilities.ObjectToStringDefault(dr["action_requested"], "rescan");

                using (FileStream fs = new FileStream(lockFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine("While file is locked open, processing thread is running.  Seeing this message means the thread may not be running, please delete this file.");
                        if (_IsDbBackup)
                        {
                            BackupCastDatabase(JobKey, JobFileName, RawJobFileName);
                        }
                        else
                        {
                            String message = "Processing";
                            switch (action_requested.ToLower())
                            {
                            case "publish":
                                JobFileName = _tokens.Resolve("Scheduler", "PublishDefinition", "No publish definition defined in the settings file.  Please add a Tokens/Scheduler PublishDefinition");
                                message     = "Publishing";
                                break;

                            case "empty":
                            case "rescan":
                                message = "Processing";
                                break;

                            case "onboard":
                                JobFileName = _tokens.Resolve("Scheduler", "OnBoardDefinition", "No onboard definition defined in the settings file.  Please add a Tokens/Scheduler OnBoardDefinition");
                                message     = "OnBoarding";
                                break;

                            default:
                                throw new Exception(String.Format("{0} is not a valid action request.", action_requested));
                            }

                            // Kick off the definition
                            RunDefinition(JobKey, JobFileName, RawJobFileName, message);
                        }
                    }
                    fs.Close();
                }
                File.Delete(lockFilename);
            }
            catch (Exception ex)
            {
                lock (_lock)
                {
                    LocalLog.AddLine("Queue Error: " + ex.Message);
                }
                _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);

                if (JobKey > 0)
                {
                    Dictionary <String, Object> sqlParameters = new Dictionary <string, object>();
                    sqlParameters.Add(":jobkey", JobKey);
                    sqlParameters.Add(":jobstatus", "Error");
                    sqlParameters.Add(":inprogress", false);
                    sqlParameters.Add(":scanrequested", false);
                    String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message);
                    if (message.Length > 99)
                    {
                        message = message.Substring(0, 99);
                    }
                    sqlParameters.Add(":statusdescription", message);
                    SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters);
                }
            }
        }
Esempio n. 30
0
        private string DoDatabaseConfiguration(string connectionString)
        {
            using (WaitCursor waitCursor = new WaitCursor())
            {
                using (DatabaseConfigurationDialog configDialog = new DatabaseConfigurationDialog())
                {
                    configDialog.ConnectionString = connectionString;
                    if (configDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        try
                        {
                            bool dbExist = SqlUtilities.IsDatabaseExist(configDialog.ConnectionString);
                            connectionString = configDialog.ConnectionString;
                            SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);

                            string script       = string.Empty;
                            string databaseName = sqlConnectionStringBuilder.InitialCatalog;

                            if ((dbExist && configDialog.Overwrite) || !dbExist)
                            {
                                script = Resources.ASPNetSqlReg;
                                RunScript(connectionString, script);
                            }

                            if (!sqlConnectionStringBuilder.IntegratedSecurity)
                            {
                                script = Resources.CreateDatabaseUser.Replace("@LoginName@", sqlConnectionStringBuilder.UserID);
                                script = script.Replace("@LoginPassword@", sqlConnectionStringBuilder.Password);
                                RunScript(connectionString, script);
                            }
                            else
                            {
                                if (CheckXPMachine())
                                {
                                    script = Resources.CreateASPNETDatabaseUser.Replace("@MachineName@", Environment.MachineName);

                                    RunScript(connectionString, script);
                                }
                            }

                            connectionString = sqlConnectionStringBuilder.ConnectionString;

                            // Check the SQL version
                            string connectionErrorMessage = "";
                            string version = "";
                            if (SqlUtilities.TestSQLConnectionString(connectionString, out connectionErrorMessage, out version))
                            {
                                if (SqlUtilities.IsSqlServer2012OrLater(version) && sqlConnectionStringBuilder.IntegratedSecurity)
                                {
                                    MessageBox.Show("It is recommended to select the 'Use SQL Server Authentication' option.\n\n" +
                                                    "You are connecting to a version of SQL Server 2012 or later, where  NT_AUTHORITY\\System is no longer installed by default.  This can cause problems with the JobProcessor Components",
                                                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            }

            return(connectionString);
        }