Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
15
SQL Server Installation while Setup and Deployment of the Project
posted

Hi Everyone,

I have a problem with Sql server Installation created with Named Instance  in setup and Deployment of the Windows Application. I have done the setup and Deployment using Visual studio Installer.

The Methods I have tried are,

Method-1) I have selected the Prerequisite button in the Setup project Properties and tick  the .Net Framework and SQL Server Express Options and selected the radiobutton "Download  the Prerequesite from the Component Vendor's Website" and Press Apply and OK but when I deploy the project It is not getting the SQL server installed in the machine.


Method-2) Then I tried with Custom Action View of the Setup Project. In the Install tab, I have added the SQL Express(.exe file) and pass the Arguments in the Property window of the SQL File as "Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=SW /InstanceName=SW /SECURITYMODE=SQL /SAPWD="1Soft1". But it also shows the error called "Setup Account Privileges failed while running the setup rules" for Sql Server Installation
The Error Message: "The account that is running SQL Server Setup does not have one or all of the following rights: the right to back up files and directories, the right to manage auditing and the security log and the right to debug programs. To continue, use an account with both of these rights." For more information, see msdn.microsoft.com/.../ms813696.aspx, msdn.microsoft.com/.../ms813959.aspx and msdn.microsoft.com/.../ms813847.aspx.

Method-3) I have tried using the Installer class and in that write the code in the Install Method as
public override void Install(System.Collections.IDictionary stateSaver)
   {

            MessageBox.Show("Installing Application...");
RegistryView registryView = RegistryView.Registry64;
                using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
                {
                    //RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                    RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                    //if (instanceKey != null)
                    //{
                    foreach (var InstanceName1 in instanceKey.GetValueNames())
                    {
                        //Console.WriteLine(Environment.MachineName + @"\" + instanceName);
                        MessageBox.Show(Environment.MachineName + @"\" + InstanceName1, "Instances Present in the SERVER", MessageBoxButton.OK, MessageBoxImage.Information);


                    }
                    string InstanceName = "SW"; 
                    object o = instanceKey.GetValue(InstanceName);

                    string x = o?.ToString() ?? "";
                    //string x = o==null? "" : o.ToString();

                    if (x == "MSSQL11.SW")
                    {
                        MessageBox.Show("SQL Server with the Instance name \"SW\" already installed", "Alert", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
 ProcessStartInfo startInfo = new ProcessStartInfo"SQLEXPR_x86_ENU.exe"
                        startInfo.Arguments = "/qs /Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=SW /InstanceName=SW /SECURITYMODE=SQL /" + BuildCommandLine();

                        //startInfo.Arguments = @"/qs /Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=NRI /InstanceName=NRI /SQLSYSADMINACCOUNTS=""NT AUTHORITY\SYSTEM"" /SQLSVCACCOUNT=""NT AUTHORITY\SYSTEM"" /SQLSVCPASSWORD=""1Soft1"" /SAPWD=""1Soft1""";
                        //Process.Start(startInfo);

                        Process p = new Process();
                        p = Process.Start(startInfo);
                        p.WaitForExit();
}
   }
}
}

Then In Custom Action View, I have added the Project Output file of the Application and in the Property Window of the Output file Set Installerclass="true" .When I install this Setup file the same error shows as mentioned in Method-2.
(The Error Message: "The account that is running SQL Server Setup does not have one or all of the following rights: the right to back up files and directories, the right to manage auditing and the security log and the right to debug programs. To continue, use an account with both of these rights." For more information, see msdn.microsoft.com/.../ms813696.aspx, msdn.microsoft.com/.../ms813959.aspx and msdn.microsoft.com/.../ms813847.aspx.)


Please ,Can Anyone help to solve this issue and error and send me the code with Detailed explanation. I want to install the project  like,While running the Setup.msi file, the SQL Server with Named Instance gets installed if it is not present and then open the application with desktop shortcut created for the Project. 

Thanks,

Dhivya

using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Server;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Data;
using System.Collections;
using System;
using Microsoft.Win32;
using System.Collections.Generic;

namespace EntityFramework
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private bool os64 = true;
        private string setupFolder = "";
        private string filename;


        //Variables for setup.exe command line
        //private string instanceName = "SQLEXPRESS";
        private string instanceid = "";
        private string installSqlDir = "";
        private string installSqlSharedDir = "";
        private string installSqlDataDir = "";
        // private string addLocal = "All";
        private bool sqlAutoStart = true;
        private bool sqlBrowserAutoStart = false;
        private string sqlBrowserAccount = "NT AUTHORITY\\SYSTEM";
        private string sqlBrowserPassword = "";
        private string SQLSYSADMINACCOUNTS = "NT AUTHORITY\\SYSTEM";
        private string SQLSVCACCOUNT = "NT AUTHORITY\\SYSTEM"; //"NT AUTHORITY\\SYSTEM";
        private bool sqlSecurityMode = true;
        private string SQLSVCPASSWORD = "";
        public string SAPWD = "dhivya123";
        private string sqlCollation = "";
        private bool disableNetworkProtocols = true;
        private bool errorReporting = true;
        //private string sqlExpressSetupFileLocation = "C:\\Program Files\\Microsoft SQL Server\\110\\Setup Bootstrap\\SQLServer2012\\setup.exe";

        private bool enableRANU = false;

        //System.Environment.GetEnvironmentVariable("TEMP") + 
        #region Properties
        //public string InstanceName
        //{
        //    get
        //    {
        //        return instanceName;
        //    }
        //    set
        //    {
        //        instanceName = value;
        //    }
        //}

        public string InstanceID
        {
            get
            {
                return instanceid;
            }
            set
            {
                instanceid = value;
            }
        }
        //public string SetupFileLocation
        //{
        //    get
        //    {
        //        return sqlExpressSetupFileLocation;
        //    }
        //    set
        //    {
        //        sqlExpressSetupFileLocation = value;
        //    }
        //}

        public string SqlInstallSharedDirectory
        {
            get
            {
                return installSqlSharedDir;
            }
            set
            {
                installSqlSharedDir = value;
            }
        }
        public string SqlDataDirectory
        {
            get
            {
                return installSqlDataDir;
            }
            set
            {
                installSqlDataDir = value;
            }
        }
        //public bool AutostartSQLService
        //{
        //    get
        //    {
        //        return sqlAutoStart;
        //    }
        //    set
        //    {
        //        sqlAutoStart = value;
        //    }
        //}
        //public bool AutostartSQLBrowserService
        //{
        //    get
        //    {
        //        return sqlBrowserAutoStart;
        //    }
        //    set
        //    {
        //        sqlBrowserAutoStart = value;
        //    }
        //}
        public string SqlBrowserAccountName
        {
            get
            {
                return sqlBrowserAccount;
            }
            set
            {
                sqlBrowserAccount = value;
            }
        }
        public string SqlBrowserPassword
        {
            get
            {
                return sqlBrowserPassword;
            }
            set
            {
                sqlBrowserPassword = value;
            }
        }
        //Defaults to LocalSystem
        public string SqlServiceAccountName
        {
            get
            {
                return SQLSYSADMINACCOUNTS;
            }
            set
            {
                SQLSYSADMINACCOUNTS = value;
            }
        }
        public string SqlServicePassword
        {
            get
            {
                return SQLSVCACCOUNT;
            }
            set
            {
                SQLSVCACCOUNT = value;
            }
        }

        public string sqlsapassword
        {
            get
            {
                return SAPWD;
            }
            set
            {
                SAPWD = value;
            }
        }

        public bool UseSQLSecurityMode
        {
            get
            {
                return sqlSecurityMode;
            }
            set
            {
                sqlSecurityMode = value;
            }
        }
        public string SysadminPassword
        {
            set
            {
                SQLSVCPASSWORD = value;
            }
        }
        public string Collation
        {
            get
            {
                return sqlCollation;
            }
            set
            {
                sqlCollation = value;
            }
        }
        public bool DisableNetworkProtocols
        {
            get
            {
                return disableNetworkProtocols;
            }
            set
            {
                disableNetworkProtocols = value;
            }
        }
        public bool ReportErrors
        {
            get
            {
                return errorReporting;
            }
            set
            {
                errorReporting = value;
            }
        }
        public string SqlInstallDirectory
        {
            get
            {
                return installSqlDir;
            }
            set
            {
                installSqlDir = value;
            }
        }

        public bool EnableRANU
        {
            get { return enableRANU; }
            set { enableRANU = value; }
        }

        #endregion

        string strConn = ConfigurationManager.ConnectionStrings["EFEntitiesContainer"].ConnectionString;
        EFEntitiesContainer db = new EFEntitiesContainer();


        public Window1()
        {
            try
            {
                InitializeComponent();


                OSCheck_Install();

                //RestartPc();
                ProgramFiles_check();
                Attach_Database();


                AfterRestart_startApp();

            }
            catch (Exception ex)
            {
                MessageBox.Show("A handled exception just occurred: " + ex.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Stop);
            }

            //RestoreDatabase();

            //BackupDatabase();

            //Emp_DetailViewModel vm = new Emp_DetailViewModel();
            //DataContext = vm;

            //EFEntitiesContainer db = new EFEntitiesContainer();
            //dgrid.ItemsSource = db.Emp_Table.ToList();
        }

        private void RestoreDatabase()
        {
            string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
            s += @"Nortech Controls\";

            string mdfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
            string ldfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
            mdfLocation += @"Nortech Controls\EmployeeInfo.mdf";
            ldfLocation += @"Nortech Controls\EmployeeInfo_log.ldf";


            string str_back = s + @"Backup\"; //System.IO.Path.Combine(s, "Backup\\EmployeeInfo.bak");//s + @"Backup\";
            SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

            if (!Directory.Exists(str_back))
            {
                Directory.CreateDirectory(str_back);
            }
            string back = System.IO.Path.Combine(str_back, "EmployeeInfo.bak"); //File.Create(System.IO.Path.Combine(str_back, "EmployeeInfo.bak")).ToString();
            System.Diagnostics.Debug.WriteLine(back);
            System.Diagnostics.Debug.WriteLine(str_back);

            conn.Open();

            string str_cmd1 = "USE master; ALTER DATABASE EmployeeInfo SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
            System.Diagnostics.Debug.WriteLine(str_cmd1);

            SqlCommand cmd = new SqlCommand(str_cmd1, conn);
            cmd.ExecuteNonQuery();

            //string str_cmd2 = @"DROP DATABASE EmployeeInfo";
            //System.Diagnostics.Debug.WriteLine(str_cmd2);

            //SqlCommand cmd2 = new SqlCommand(str_cmd2, conn);
            //cmd2.ExecuteNonQuery();

            string str_cmd = "RESTORE DATABASE EmployeeInfo FROM DISK =" + "'" + back + "'" + " WITH replace ALTER DATABASE EmployeeInfo SET MULTI_USER";
            //string str_cmd = "RESTORE DATABASE EmployeeInfo FROM DISK =" + "'" + str_back + "'"+ " with move 'EmployeeInfo' TO "+"'"+ mdfLocation+"'"+", move 'EmployeeInfo_log' TO "+"'"+ ldfLocation+"'";
            System.Diagnostics.Debug.WriteLine(str_cmd);

            cmd = new SqlCommand(str_cmd, conn);
            cmd.ExecuteNonQuery();

            conn.Close();
            //MessageBox.Show("Database Restored Successful.");

        }
        //private void restore_db_Click(object sender, RoutedEventArgs e)
        //{
        //    string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
        //    s += @"Nortech Controls\";

        //    string mdfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
        //    string ldfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
        //    mdfLocation += @"Nortech Controls\EmployeeInfo.mdf";
        //    ldfLocation += @"Nortech Controls\EmployeeInfo_log.ldf";


        //    string str_back = s + @"Backup\"; //System.IO.Path.Combine(s, "Backup\\EmployeeInfo.bak");//s + @"Backup\";
        //    SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

        //    if (!Directory.Exists(str_back))
        //    {
        //        Directory.CreateDirectory(str_back);
        //    }
        //    string back = System.IO.Path.Combine(str_back, "EmployeeInfo.bak"); //File.Create(System.IO.Path.Combine(str_back, "EmployeeInfo.bak")).ToString();
        //    System.Diagnostics.Debug.WriteLine(back);
        //    System.Diagnostics.Debug.WriteLine(str_back);

        //    conn.Open();

        //    string str_cmd1 = "USE master; ALTER DATABASE EmployeeInfo SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
        //    System.Diagnostics.Debug.WriteLine(str_cmd1);

        //    SqlCommand cmd = new SqlCommand(str_cmd1, conn);
        //    cmd.ExecuteNonQuery();

        //    //string str_cmd2 = @"DROP DATABASE EmployeeInfo";
        //    //System.Diagnostics.Debug.WriteLine(str_cmd2);

        //    //SqlCommand cmd2 = new SqlCommand(str_cmd2, conn);
        //    //cmd2.ExecuteNonQuery();

        //    string str_cmd = "RESTORE DATABASE EmployeeInfo FROM DISK =" + "'" + back + "'" + " WITH replace ALTER DATABASE EmployeeInfo SET MULTI_USER";
        //    //string str_cmd = "RESTORE DATABASE EmployeeInfo FROM DISK =" + "'" + str_back + "'"+ " with move 'EmployeeInfo' TO "+"'"+ mdfLocation+"'"+", move 'EmployeeInfo_log' TO "+"'"+ ldfLocation+"'";
        //    System.Diagnostics.Debug.WriteLine(str_cmd);

        //    cmd = new SqlCommand(str_cmd, conn);
        //    cmd.ExecuteNonQuery();

        //    conn.Close();
        //    MessageBox.Show("Database Restored Successful.");
        //}


        private void backup_db_Click(object sender, RoutedEventArgs e)
        {
            string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
            s += @"Nortech Controls\";

            string str_back = s + @"Backup\";//System.IO.Path.Combine(s, "Backup\\EmployeeInfo.bak");
            SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

            if (!Directory.Exists(str_back))
            {
                Directory.CreateDirectory(str_back);
            }
            string back = System.IO.Path.Combine(str_back, "EmployeeInfo.bak"); //File.Create(System.IO.Path.Combine(str_back, "EmployeeInfo.bak")).ToString();
            System.Diagnostics.Debug.WriteLine(back);

            conn.Open();
            //string str_cmd = "BACKUP DATABASE EmployeeInfo TO DISK =" + "'" + back + "'";
            string str_cmd = "BACKUP DATABASE EmployeeInfo TO DISK = '" + back + "';";
            System.Diagnostics.Debug.WriteLine(str_cmd);

            SqlCommand cmd = new SqlCommand(str_cmd, conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            MessageBox.Show("Database Backup Successful.");
        }
        //private void BackupDatabase()
        //{
        //    string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
        //    s += @"Nortech Controls\";

        //    string str_back = s + @"Backup\";//System.IO.Path.Combine(s, "Backup\\EmployeeInfo.bak");
        //    SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

        //    if(!Directory.Exists(str_back))
        //    {
        //        Directory.CreateDirectory(str_back);
        //    }
        //    string back = System.IO.Path.Combine(str_back, "EmployeeInfo.bak"); //File.Create(System.IO.Path.Combine(str_back, "EmployeeInfo.bak")).ToString();
        //    System.Diagnostics.Debug.WriteLine(back);

        //    conn.Open();
        //    //SqlCommand cmd = new SqlCommand();
        //    SqlDataReader reader;
        //    string str_cmd= @"BACKUP DATABASE EmployeeInfo TO DISK =" + "'" + back + "'" + "";
        //    System.Diagnostics.Debug.WriteLine(str_cmd);
        //    //cmd.CommandText = @"BACKUP DATABASE EmployeeInfo TO DISK ="+ "'"+ back + "'" + "";

        //    SqlCommand cmd = new SqlCommand(str_cmd,conn);
        //    //cmd.CommandType = CommandType.Text;
        //    //cmd.Connection = conn;
        //    //reader = cmd.ExecuteReader();
        //    cmd.ExecuteNonQuery();
        //    conn.Close();
        //    MessageBox.Show("Database Backup Successful.");
        //}//str_back+ @"EmployeeInfo.bak"

        private void Attach_Database()
        {
            SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");
            if (Environment.Is64BitOperatingSystem)
            {
                //string str = Environment.GetEnvironmentVariable(@"ProgramFiles(x86)");

                //str += @"\Microsoft SQL Server\MSSQL11.NORTECH\MSSQL\DATA\";

                string str_db;
                bool result = false;

                //string sqlConnectionString = "Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True";
                try
                {
                    //SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

                    string dbase = "EmployeeInfo";

                    str_db = string.Format("SELECT database_id  FROM sys.databases WHERE Name = '{0}'", dbase);

                    using (conn)
                    {
                        using (SqlCommand sqlCmd = new SqlCommand(str_db, conn))
                        {
                            conn.Open();

                            object resultObj = sqlCmd.ExecuteScalar();

                            int databaseID = 0;

                            if (resultObj != null)
                            {
                                int.TryParse(resultObj.ToString(), out databaseID);
                            }
                            else
                            {

                                string mdfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                                string ldfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);

                                string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                                s += @"Nortech Controls\";

                                mdfLocation += @"Nortech Controls\EmployeeInfo.mdf";
                                ldfLocation += @"Nortech Controls\EmployeeInfo_log.ldf";

                                if (Directory.Exists(s))
                                {
                                    DirectoryInfo dInfo = new DirectoryInfo(s);
                                    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                                    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                                                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                                    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                                    dInfo.SetAccessControl(dSecurity);

                                    DirectoryInfo dInfo1 = new DirectoryInfo(mdfLocation);
                                    DirectorySecurity dSecurity1 = dInfo1.GetAccessControl();
                                    dSecurity1.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                                                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                                    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                                    dInfo.SetAccessControl(dSecurity1);

                                    //conn.Open();

                                    str_db = "CREATE DATABASE EmployeeInfo ON " +
                                        //str_db = "CREATE DATABASE" + dbase + "ON " +
                                        "PRIMARY ( FILENAME =" + "'" + mdfLocation + "'" + " ),( FILENAME =" + "'" + ldfLocation + "'" + " ) " +
                                        //"PRIMARY ( FILENAME ='C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf' ),( FILENAME ='C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf' ) " +
                                        "FOR ATTACH";

                                    System.Diagnostics.Debug.WriteLine(str_db);
                                    SqlCommand cmd = new SqlCommand(str_db, conn);



                                    try
                                    {
                                        //conn.Open();
                                        cmd.ExecuteNonQuery();
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                    conn.Close();
                                }
                                //conn.Close();

                                result = (databaseID > 0);
                            }
                        }
                    }
                }


                catch (Exception ex)
                {
                    result = false;
                    MessageBox.Show(ex.Message);
                }

                MessageBox.Show("Database Connection Success");
                System.Diagnostics.Debug.WriteLine(result.ToString());
            }
            else
            {
                string str = Environment.GetEnvironmentVariable(@"ProgramFiles");

                str += @"\Microsoft SQL Server\MSSQL11.NORTECH\MSSQL\DATA\";

                string str_db;
                bool result = false;

                //string sqlConnectionString = "Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True";
                try
                {
                    //SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

                    string dbase = "EmployeeInfo";

                    str_db = string.Format("SELECT database_id  FROM sys.databases WHERE Name = '{0}'", dbase);

                    using (conn)
                    {
                        using (SqlCommand sqlCmd = new SqlCommand(str_db, conn))
                        {
                            conn.Open();

                            object resultObj = sqlCmd.ExecuteScalar();

                            int databaseID = 0;

                            if (resultObj != null)
                            {
                                int.TryParse(resultObj.ToString(), out databaseID);
                            }
                            else
                            {
                                string mdfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                                string ldfLocation = System.IO.Path.GetPathRoot(Environment.SystemDirectory);

                                string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                                s += @"Nortech Controls\";

                                mdfLocation += @"Nortech Controls\EmployeeInfo.mdf";
                                ldfLocation += @"Nortech Controls\EmployeeInfo_log.ldf";

                                if (Directory.Exists(s))
                                {
                                    DirectoryInfo dInfo = new DirectoryInfo(s);
                                    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                                    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                                                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                                    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                                    dInfo.SetAccessControl(dSecurity);
                                    //conn.Open();

                                    str_db = "CREATE DATABASE EmployeeInfo ON " +
                                        //str_db = "CREATE DATABASE" + dbase + "ON " +
                                        "PRIMARY ( FILENAME =" + "'" + mdfLocation + "'" + " ),( FILENAME =" + "'" + ldfLocation + "'" + " ) " +
                                        //"PRIMARY ( FILENAME ='C:\\Program Files\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf' ),( FILENAME ='C:\\Program Files\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf' ) " +
                                        "FOR ATTACH";


                                    SqlCommand cmd = new SqlCommand(str_db, conn);



                                    try
                                    {
                                        //conn.Open();
                                        cmd.ExecuteNonQuery();
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                    conn.Close();
                                }
                                //conn.Close();

                                result = (databaseID > 0);
                            }
                        }
                    }
                }


                catch (Exception ex)
                {
                    result = false;
                }

                MessageBox.Show("Database Connection Success");
                System.Diagnostics.Debug.WriteLine(result.ToString());
            }
            //conn.Open();


            //else
            //{
            //    string str = Environment.GetEnvironmentVariable(@"ProgramFiles");

            //    str += @"\Microsoft SQL Server\MSSQL11.NORTECH\MSSQL\DATA\";

            //    string str_db;
            //    //string sqlConnectionString = "Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True";

            //    SqlConnection conn = new SqlConnection("Data Source=localhost\\NORTECH;User Id=sa;Password=dhivya123;integrated security=True");

            //    //string dbase = "EmployeeInfo";
            //    Boolean bRet = false;  //***Check database exists in sql server or not*****//

            //    if (bRet == true)
            //    {
            //        MessageBox.Show("Database Exists");
            //    }
            //    else
            //    {

            //        if (Directory.Exists(str))
            //        {
            //            DirectoryInfo dInfo = new DirectoryInfo(str);
            //            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            //            dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
            //                                             InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
            //                                             PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            //            //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            //            dInfo.SetAccessControl(dSecurity);
            //            conn.Open();

            //            str_db = "CREATE DATABASE EmployeeInfo ON " +
            //                //str_db = "CREATE DATABASE" + dbase + "ON " +
            //                "PRIMARY ( FILENAME ='C:\\Program Files\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf' ),( FILENAME ='C:\\Program Files\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf' ) " +
            //                "FOR ATTACH";


            //            SqlCommand cmd = new SqlCommand(str_db, conn);



            //            try
            //            {
            //                //conn.Open();
            //                cmd.ExecuteNonQuery();
            //            }
            //            catch (Exception ex)
            //            {
            //                MessageBox.Show(ex.Message);
            //            }
            //            conn.Close();
            //        }
            //    }
            //    conn.Open();
            //}

            //try
            //    //if (!File.Exists(str + @"EmployeeInfo.mdf") || (!File.Exists(str + @"EmployeeInfo_log.ldf")))
            //    {
            //        conn.Open();
            //        SqlCommand cmd = new SqlCommand("select * from master.dbo.sysdatabases where name ='EmployeeInfo'", conn);

            //        SqlDataReader dr = cmd.ExecuteReader();
            //        bRet = dr.HasRows;
            //        conn.Close();
            //    }
            //    catch (Exception ex)
            //    {
            //        bRet = false;
            //        MessageBox.Show(ex.Message);
            //    }

            //if (bRet == true)
            //{
            //    MessageBox.Show("Database Exists");
            //}
            //else
            //{

            //    if (Directory.Exists(str))
            //    {
            //        DirectoryInfo dInfo = new DirectoryInfo(str);
            //        DirectorySecurity dSecurity = dInfo.GetAccessControl();
            //        dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
            //                                         InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
            //                                         PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            //        //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            //        dInfo.SetAccessControl(dSecurity);
            //        conn.Open();

            //        str_db = "CREATE DATABASE EmployeeInfo ON " +
            //            //str_db = "CREATE DATABASE" + dbase + "ON " +
            //            "PRIMARY ( FILENAME ='C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf' ),( FILENAME ='C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf' ) " +
            //            "FOR ATTACH";


            //        SqlCommand cmd = new SqlCommand(str_db, conn);



            //        try
            //        {
            //            //conn.Open();
            //            cmd.ExecuteNonQuery();
            //        }
            //        catch (Exception ex)
            //        {
            //            MessageBox.Show(ex.Message);
            //        }
            //        conn.Close();
            //    }
            //}
            //conn.Open();
            //}


            //try
            //    //if (!File.Exists(str + @"EmployeeInfo.mdf") || (!File.Exists(str + @"EmployeeInfo_log.ldf")))
            //    {
            //        conn.Open();
            //        SqlCommand cmd = new SqlCommand("select * from master.dbo.sysdatabases where name ='EmployeeInfo'", conn);

            //        SqlDataReader dr = cmd.ExecuteReader();
            //        bRet = dr.HasRows;
            //        conn.Close();
            //    }
            //    catch (Exception ex)
            //    {
            //        bRet = false;
            //        MessageBox.Show(ex.Message);
            //    }

            //    if (bRet == true)
            //    {
            //        MessageBox.Show("Database Exists");
            //    }
            //    else
            //    {

            //        if (Directory.Exists(str))
            //        {
            //            DirectoryInfo dInfo = new DirectoryInfo(str);
            //            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            //            dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
            //                                             InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
            //                                             PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            //            //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            //            dInfo.SetAccessControl(dSecurity);
            //            conn.Open();

            //            str_db = "CREATE DATABASE EmployeeInfo ON " +
            //                //str_db = "CREATE DATABASE" + dbase + "ON " +
            //                "PRIMARY ( FILENAME ='C:\\Program Files\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf' ),( FILENAME ='C:\\Program Files\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf' ) " +
            //                "FOR ATTACH";


            //            SqlCommand cmd = new SqlCommand(str_db, conn);



            //            try
            //            {
            //                //conn.Open();
            //                cmd.ExecuteNonQuery();
            //            }
            //            catch (Exception ex)
            //            {
            //                MessageBox.Show(ex.Message);
            //            }
            //            conn.Close();
            //        }
            //    }
            //    conn.Open();
            //}
        }

        //str_db = "CREATE DATABASE EmployeeInfo ON " +
        //    //str_db = "CREATE DATABASE" + dbase + "ON " +
        //        "PRIMARY ( FILENAME ='C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf' ),( FILENAME ='C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf' ) " +
        //        "FOR ATTACH";


        //    //SqlCommand cmd = new SqlCommand(str_db, conn);



        //    try
        //    {
        //        //conn.Open();
        //        cmd.ExecuteNonQuery();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //    conn.Close();
        //}
        //conn.Open();
        //using (conn = new SqlConnection(sqlConnectionString))
        //{
        /**--Script sql file --***/
        //string sqlCommandFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"EFEntities.edmx.sql");
        //if (File.Exists(sqlCommandFilePath))
        //{
        //    string script = File.ReadAllText(sqlCommandFilePath);

        //    var sqlqueries = script.Split(new[] { " GO " }, StringSplitOptions.RemoveEmptyEntries);

        //    using (SqlCommand command = new SqlCommand(script, conn))
        //    {
        //    //conn.Open();
        //        foreach (var query in sqlqueries)
        //        {
        //            command.CommandText = query;
        //            command.ExecuteNonQuery();
        //        }


        //        //int affectedRows = command.ExecuteNonQuery();
        //    }
        //}
        //conn.Close();
        //}



        //SqlConnection conn = new SqlConnection("user id=sa;" +
        //                           "password=dhivya123;server=localhost\\NORTECH;" +
        //                           "Trusted_Connection=yes;" +
        //                           "database=EmployeeInfo; " +
        //                           "connection timeout=30");

        //    string str_db;

        //    SqlConnection conn = new SqlConnection("Server=localhost\\NORTECH;Integrated security=SSPI;database=master");

        //    string str = Environment.GetEnvironmentVariable(@"ProgramFiles(x86)");

        //    str += @"\Microsoft SQL Server\MSSQL11.NORTECH\MSSQL\DATA\";
        //    if (Directory.Exists(str))
        //    {
        //        DirectoryInfo dInfo = new DirectoryInfo(str);
        //        DirectorySecurity dSecurity = dInfo.GetAccessControl();
        //        dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
        //                                         InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
        //                                         PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
        //        //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
        //        dInfo.SetAccessControl(dSecurity);

        //        str_db = "CREATE DATABASE 'EmployeeInfo' ON PRIMARY " +
        //        "(NAME = EmployeeInfo_Data, " +
        //"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo.mdf', " +
        //"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
        //"LOG ON (NAME = EmployeeInfo_Log, " +
        //"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL11.NORTECH\\MSSQL\\DATA\\EmployeeInfo_log.ldf', " +
        //"SIZE = 1MB, " +
        //"MAXSIZE = 5MB, " +
        //"FILEGROWTH = 10%)";

        //        SqlCommand cmd = new SqlCommand(str_db, conn);

        //        // conn.Open();

        //        try
        //        {
        //            conn.Open();
        //            cmd.ExecuteNonQuery();

        //            cmd.Dispose();
        //            conn.Dispose();
        //        }
        //        catch (Exception e)
        //        {
        //            MessageBox.Show(e.ToString());
        //        }
        //    }



        //cmd.ExecuteNonQuery();

        //cmd.Dispose();
        //conn.Dispose();



        private void ProgramFiles_check()
        {
            //if (8 == IntPtr.Size
            //|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
            if (Environment.Is64BitOperatingSystem)

            {
                //C:\Program Files (x86)\Microsoft SQL Server\MSSQL11.NORTECH
                string str = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                //string str = Environment.GetEnvironmentVariable(@"ProgramFiles(x86)");

                str += @"Program Files (x86)\Microsoft SQL Server\MSSQL11.NORTECH\MSSQL\DATA\";
                System.Diagnostics.Debug.WriteLine(str);


                //string file = System.IO.Path.Combine(str, "EmployeeInfo.mdf","EmployeeInfo_log.ldf");
                //System.Diagnostics.Debug.WriteLine(str);

                string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                System.Diagnostics.Debug.WriteLine(s);
                //s += @"DB\EmployeeInfo.mdf";

                s += @"Nortech Controls\";
                if (!Directory.Exists(s))
                {
                    Directory.CreateDirectory(s);

                    DirectoryInfo dInfo = new DirectoryInfo(s);
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                    dInfo.SetAccessControl(dSecurity);

                    string executableLocation = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string mdfLocation = System.IO.Path.Combine(executableLocation, "DB\\EmployeeInfo.mdf"); /**** This 'DB\Employee.mdf' is taken from the Application Project-"bin folder"****/
                    string ldfLocation = System.IO.Path.Combine(executableLocation, "DB\\EmployeeInfo_log.ldf");

                    File.Copy(mdfLocation, s + System.IO.Path.GetFileName(mdfLocation));
                    File.Copy(ldfLocation, s + System.IO.Path.GetFileName(ldfLocation));

                    System.Diagnostics.Debug.WriteLine(System.IO.Path.GetFileName(mdfLocation));
                    System.Diagnostics.Debug.WriteLine(s + System.IO.Path.GetFileName(mdfLocation));
                }

                string executableLocation1 = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string mdfLocation1 = System.IO.Path.Combine(executableLocation1, "DB\\EmployeeInfo.mdf"); /**** This 'DB\Employee.mdf' is taken from the Application Project-"bin folder"****/
                string ldfLocation1 = System.IO.Path.Combine(executableLocation1, "DB\\EmployeeInfo_log.ldf");

                if (!File.Exists(s + System.IO.Path.GetFileName(mdfLocation1)))
                {
                    File.Copy(mdfLocation1, s + System.IO.Path.GetFileName(mdfLocation1));
                    File.Copy(ldfLocation1, s + System.IO.Path.GetFileName(ldfLocation1));
                }



                System.Diagnostics.Debug.WriteLine(s);
                //if (Directory.Exists(str))
                //{
                //    DirectoryInfo dInfo = new DirectoryInfo(str);
                //    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                //    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                //                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                //                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                //    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                //    dInfo.SetAccessControl(dSecurity);

                //    if (!File.Exists(str+@"EmployeeInfo.mdf")||(!File.Exists(str+@"EmployeeInfo_log.ldf")))
                //    {
                //        File.Copy(@"C:DB\EmployeeInfo.mdf", str + System.IO.Path.GetFileName("EmployeeInfo.mdf"));
                //        File.Copy(@"C:DB\EmployeeInfo_log.ldf", str + System.IO.Path.GetFileName("EmployeeInfo_log.ldf"));
                //    }

                //    System.Diagnostics.Debug.WriteLine(str);

                //string file = System.IO.Path.Combine(str, "EmployeeInfo.mdf");



                //conn.Dispose();
                //}
                //}




            }

            else
            {
                //C:\Program Files (x86)\Microsoft SQL Server\MSSQL11.NORTECH
                string str = Environment.GetEnvironmentVariable(@"ProgramFiles");

                str += @"\Microsoft SQL Server\MSSQL11.NORTECH\MSSQL\DATA\";
                System.Diagnostics.Debug.WriteLine(str);


                //string file = System.IO.Path.Combine(str, "EmployeeInfo.mdf","EmployeeInfo_log.ldf");
                //System.Diagnostics.Debug.WriteLine(str);

                string s = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
                //s += @"DB\EmployeeInfo.mdf";

                s += @"Nortech Controls\";
                if (!Directory.Exists(s))
                {
                    Directory.CreateDirectory(s);

                    DirectoryInfo dInfo = new DirectoryInfo(s);
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                    dInfo.SetAccessControl(dSecurity);

                    string executableLocation = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string mdfLocation = System.IO.Path.Combine(executableLocation, "DB\\EmployeeInfo.mdf");  /**** This 'DB\Employee.mdf' is taken from the Application Project-"bin folder"****/
                    string ldfLocation = System.IO.Path.Combine(executableLocation, "DB\\EmployeeInfo_log.ldf");

                    File.Copy(mdfLocation, s + System.IO.Path.GetFileName(mdfLocation));
                    File.Copy(ldfLocation, s + System.IO.Path.GetFileName(ldfLocation));
                }

                string executableLocation1 = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string mdfLocation1 = System.IO.Path.Combine(executableLocation1, "DB\\EmployeeInfo.mdf"); /**** This 'DB\Employee.mdf' is taken from the Application Project-"bin folder"****/
                string ldfLocation1 = System.IO.Path.Combine(executableLocation1, "DB\\EmployeeInfo_log.ldf");

                if (!File.Exists(s + System.IO.Path.GetFileName(mdfLocation1)))
                {
                    File.Copy(mdfLocation1, s + System.IO.Path.GetFileName(mdfLocation1));
                    File.Copy(ldfLocation1, s + System.IO.Path.GetFileName(ldfLocation1));
                }


                System.Diagnostics.Debug.WriteLine(s);
                //if (Directory.Exists(str))
                //{
                //    DirectoryInfo dInfo = new DirectoryInfo(str);
                //    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                //    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,
                //                                     InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                //                                     PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                //    //dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                //    dInfo.SetAccessControl(dSecurity);

                //    if (!File.Exists(str + @"EmployeeInfo.mdf") || (!File.Exists(str + @"EmployeeInfo_log.ldf")))
                //    {
                //        File.Copy(@"C:DB\EmployeeInfo.mdf", str + System.IO.Path.GetFileName("EmployeeInfo.mdf"));
                //        File.Copy(@"C:DB\EmployeeInfo_log.ldf", str + System.IO.Path.GetFileName("EmployeeInfo_log.ldf"));
                //    }

                //    System.Diagnostics.Debug.WriteLine(str);

                //    //string file = System.IO.Path.Combine(str, "EmployeeInfo.mdf");



                //    //conn.Dispose();
                //    //}
                //}




            }

            Thread.Sleep(5000);
        }

        private void RestartPc()
        {
            Process.Start("shutdown", "/r /t 0");
        }

        private void AfterRestart_startApp()
        {
            Emp_DetailViewModel vm = new Emp_DetailViewModel();
            DataContext = vm;
        }


        private void OSCheck_Install()
        {
            
                if (Environment.Is64BitOperatingSystem)
                {
                    RegistryView registryView = RegistryView.Registry64;
                    using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
                    {
                        //RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                        RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                        //if (instanceKey != null)
                        //{
                        foreach (var InstanceName1 in instanceKey.GetValueNames())
                        {
                            //Console.WriteLine(Environment.MachineName + @"\" + instanceName);
                            MessageBox.Show(Environment.MachineName + @"\" + InstanceName1, "Instances Present in the SERVER", MessageBoxButton.OK, MessageBoxImage.Information);


                        }
                        string InstanceName = "NORTECH"; //NORTECH
                        object o = instanceKey.GetValue(InstanceName);

                        string x = o?.ToString() ?? "";
                        //string x = o==null? "" : o.ToString();

                        if (x == "MSSQL11.NORTECH")
                        {
                            MessageBox.Show("SQL Server with the Instance name \"NORTECH\" already installed", "Alert", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                        else
                        {
                            ProcessStartInfo startInfo = new ProcessStartInfo("SQLEXPR_x86_ENU.exe");
                            startInfo.Arguments = "/qs /Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=NORTECH /InstanceName=NORTECH /SECURITYMODE=SQL /" + BuildCommandLine();

                            //startInfo.Arguments = @"/qs /Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=NRI /InstanceName=NRI /SQLSYSADMINACCOUNTS=""NT AUTHORITY\SYSTEM"" /SQLSVCACCOUNT=""NT AUTHORITY\SYSTEM"" /SQLSVCPASSWORD=""1Soft1"" /SAPWD=""1Soft1""";
                            //Process.Start(startInfo);

                            Process p = new Process();
                            p = Process.Start(startInfo);
                            p.WaitForExit();

                            //if (p.HasExited)
                            //{
                            //    MessageBox.Show("SQL Server with New Instance has been Successfully installed");
                            //}

                            //Thread.Sleep(100000);
                            MessageBox.Show("SQL Server with New Instance \"NORTECH\" has been Successfully installed", "Success", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                        }

                    }
                }
                else
                {
                    RegistryView registryView = RegistryView.Registry32;
                    using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
                    {
                        RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                        //RegistryKey instanceKey1 = hklm.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                        //if (instanceKey != null)
                        //{
                        foreach (var InstanceName1 in instanceKey.GetValueNames())
                        {
                            //Console.WriteLine(Environment.MachineName + @"\" + instanceName);
                            MessageBox.Show(Environment.MachineName + @"\" + InstanceName1, "Instances Present in the SERVER", MessageBoxButton.OK, MessageBoxImage.Information);
                        }

                        string InstanceName = "NORTECH";
                        object o = instanceKey.GetValue(InstanceName);
                        string x = o?.ToString() ?? "";

                        if (x == "MSSQL11.NORTECH")
                        {
                            MessageBox.Show("SQL Server with the Instance name \"NORTECH\" already installed", "Alert", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                        else
                        {
                            ProcessStartInfo startInfo = new ProcessStartInfo("SQLEXPR_x86_ENU.exe");
                            startInfo.Arguments = "/qs /Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=NORTECH /InstanceName=NORTECH /SECURITYMODE=SQL /" + BuildCommandLine();

                            //startInfo.Arguments = @"/qs /Action=Install /IAcceptSQLServerLicenseTerms=True /InstanceId=NRI /InstanceName=NRI /SQLSYSADMINACCOUNTS=""NT AUTHORITY\SYSTEM"" /SQLSVCACCOUNT=""NT AUTHORITY\SYSTEM"" /SQLSVCPASSWORD=""1Soft1"" /SAPWD=""1Soft1""";
                            Process p = new Process();
                            p = Process.Start(startInfo);
                            p.WaitForExit();

                            MessageBox.Show("SQL Server with New Instance \"NORTECH\" has been Successfully installed", "Success", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                            //if (p.HasExited)
                            //    {

                            //    }
                            // Thread.Sleep(100000);

                        }

                    }
                }
            
            
        }

        private string BuildCommandLine()
        {
            StringBuilder strCommandLine = new StringBuilder();

            //if (!String.IsNullOrEmpty(installSqlDir))
            //{
            //    strCommandLine.Append("INSTANCENAME=\"").Append(instanceName).Append("\"");
            //}

            //if (!String.IsNullOrEmpty(installSqlDir))
            //{
            //    strCommandLine.Append("INSTANCEID=\"").Append(instanceid).Append("\"");
            //}

            if (!String.IsNullOrEmpty(installSqlDir))
            {
                strCommandLine.Append("INSTALLSQLDIR=\"").Append(installSqlDir).Append("\"");
            }

            if (!String.IsNullOrEmpty(installSqlSharedDir))
            {
                strCommandLine.Append("INSTALLSQLSHAREDDIR=\"").Append(installSqlSharedDir).Append("\"");
            }

            if (!String.IsNullOrEmpty(installSqlDataDir))
            {
                strCommandLine.Append("INSTALLSQLDATADIR=\"").Append(installSqlDataDir).Append("\"");
            }

            //if (!String.IsNullOrEmpty(addLocal))
            //{
            //    strCommandLine.Append("ADDLOCAL=\"").Append(addLocal).Append("\"");
            //}

            //if (sqlAutoStart)
            //{
            //    strCommandLine.Append("SQLAUTOSTART=1");
            //}
            //else
            //{
            //    strCommandLine.Append("SQLAUTOSTART=0");
            //}

            //if (sqlBrowserAutoStart)
            //{
            //    strCommandLine.Append("SQLBROWSERAUTOSTART=1");
            //}
            //else
            //{
            //    strCommandLine.Append("SQLBROWSERAUTOSTART=0");
            //}

            //if (!String.IsNullOrEmpty(sqlBrowserAccount))
            //{
            //    strCommandLine.Append("SQLBROWSERACCOUNT=\"").Append(sqlBrowserAccount).Append("\"");
            //}

            //if (!String.IsNullOrEmpty(sqlBrowserPassword))
            //{
            //    strCommandLine.Append("SQLBROWSERPASSWORD=\"").Append(sqlBrowserPassword).Append("\"");
            //}

            if (!String.IsNullOrEmpty(SQLSYSADMINACCOUNTS))
            {
                strCommandLine.Append("SQLSYSADMINACCOUNTS=\"").Append(SQLSYSADMINACCOUNTS).Append("\"");
            }

            if (!String.IsNullOrEmpty(SQLSVCACCOUNT))
            {
                strCommandLine.Append(" /SQLSVCACCOUNT=\"").Append(SQLSVCACCOUNT).Append("\"");
            }

            if (sqlSecurityMode == true)
            {
                strCommandLine.Append(" /SECURITYMODE=SQL");
            }

            if (!String.IsNullOrEmpty(SQLSVCPASSWORD))
            {
                strCommandLine.Append(" /SQLSVCPASSWORD=\"").Append(SQLSVCPASSWORD).Append("\"");
            }

            if (!String.IsNullOrEmpty(SAPWD))
            {
                strCommandLine.Append(" /SAPWD=\"").Append(SAPWD).Append("\"");
            }


            if (!String.IsNullOrEmpty(sqlCollation))
            {
                strCommandLine.Append(" /SQLCOLLATION=\"").Append(sqlCollation).Append("\"");
            }

            //if (disableNetworkProtocols == true)
            //{
            //    strCommandLine.Append(" /DISABLENETWORKPROTOCOLS=1");
            //}
            //else
            //{
            //    strCommandLine.Append(" /DISABLENETWORKPROTOCOLS=0");
            //}

            if (errorReporting == true)
            {
                strCommandLine.Append(" /ERRORREPORTING=1");
            }
            else
            {
                strCommandLine.Append(" /ERRORREPORTING=0");
            }

            if (enableRANU == true)
            {
                strCommandLine.Append(" /ENABLERANU=1");
            }
            else
            {
                strCommandLine.Append(" /ENABLERANU=0");
            }

            return strCommandLine.ToString();
        }

        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            EFEntitiesContainer db = new EFEntitiesContainer();
            int emp_id = (dgrid.SelectedItem as Emp_Table).ID;
            Emp_Table emp = (from identity in db.Emp_Table where identity.ID == emp_id select identity).SingleOrDefault();
            db.Emp_Table.Remove(emp);
            db.SaveChanges();

            //var details = db.Emp_Table.ToList();
            dgrid.ItemsSource = db.Emp_Table.ToList();

        }

        private void btn_Update_Click(object sender, RoutedEventArgs e)
        {
            EFEntitiesContainer db = new EFEntitiesContainer();
            int emp_id1 = (dgrid.SelectedItem as Emp_Table).ID;
            Emp_Table emp = (from identity in db.Emp_Table where identity.ID == emp_id1 select identity).SingleOrDefault();
            emp.FirstName = txt_fname.Text;
            emp.LastName = txt_lname.Text;
            emp.Department = txt_dept.Text;
            emp.Title = txt_title.Text;

            db.Entry(emp).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            //var details = db.Emp_Table.ToList();
            dgrid.ItemsSource = db.Emp_Table.ToList();
            //ClearAll();
        }

        /*---Select the row in datagrid and the values of that row will display in the textboxes-- */
        private void dgrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var row_list = GetDataGridRows(dgrid);
                foreach (DataGridRow single_row in row_list)
                {
                    if (single_row.IsSelected == true)
                    {
                        //Get your value over here
                        var data = dgrid.SelectedItem;
                        string fname = (dgrid.SelectedCells[1].Column.GetCellContent(data) as TextBlock).Text;
                        txt_fname.Text = fname;
                        string lname = (dgrid.SelectedCells[2].Column.GetCellContent(data) as TextBlock).Text;
                        txt_lname.Text = lname;
                        string dept = (dgrid.SelectedCells[3].Column.GetCellContent(data) as TextBlock).Text;
                        txt_dept.Text = dept;
                        string title = (dgrid.SelectedCells[4].Column.GetCellContent(data) as TextBlock).Text;
                        txt_title.Text = title;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }


        public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
        {
            var itemsSource = grid.ItemsSource as IEnumerable;
            if (null == itemsSource) yield return null;
            foreach (var item in itemsSource)
            {
                var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (null != row) yield return row;
            }
        }

        private void ClearAll()
        {
            txt_fname.Text = "";
            txt_lname.Text = "";
            txt_dept.Text = "";
            txt_title.Text = "";
        }

        private void refresh_db_Click(object sender, RoutedEventArgs e)
        {
            CollectionViewSource.GetDefaultView(dgrid.ItemsSource).Refresh();
        }


   
    }
}

  • 22852
    Offline posted

    Dhivya,

    Your quesiton doesn't have anything to do with Infragistics and you would be better off asking Microsoft or posting this question on StackOverflow.