public void BindItem(SqlDatabase item)
        {
            // enable/disable controls according to hosting context
            PackageContext cntx = PackagesHelper.GetCachedPackageContext(item.PackageId);
            string backupQuotaName = item.GroupName + ".Backup";
            btnBackup.Enabled = cntx.Quotas.ContainsKey(backupQuotaName) && !cntx.Quotas[backupQuotaName].QuotaExhausted;

            ViewState["ControlsToggled"] = true;
        }
		public void BindItem(SqlDatabase item)
		{
			litDataSize.Text = item.DataSize.ToString();
			// enable/disable controls according to hosting context
			PackageContext cntx = PackagesHelper.GetCachedPackageContext(item.PackageId);
			string backupQuotaName = item.GroupName + ".Backup";
			string restoreQuotaName = item.GroupName + ".Restore";
			string truncateQuotaName = item.GroupName + ".Truncate";
			btnBackup.Enabled = cntx.Quotas.ContainsKey(backupQuotaName) && !cntx.Quotas[backupQuotaName].QuotaExhausted;
			btnRestore.Enabled = cntx.Quotas.ContainsKey(restoreQuotaName) && !cntx.Quotas[restoreQuotaName].QuotaExhausted;
			btnTruncate.Enabled = cntx.Quotas.ContainsKey(truncateQuotaName) && !cntx.Quotas[truncateQuotaName].QuotaExhausted;

			ViewState["ControlsToggled"] = true;
		}
        protected void Page_Load(object sender, EventArgs e)
        {
			// check for "View" mode
			if (String.Compare(Request["Mode"], "view", true) == 0)
			{
				// load database
				try
				{
					item = ES.Services.DatabaseServers.GetSqlDatabase(PanelRequest.ItemID);

					if (item.Users != null && item.Users.Length > 0)
					{
						DatabaseBrowserConfiguration config = ES.Services.DatabaseServers.GetDatabaseBrowserLogonScript(
							PanelSecurity.PackageId, item.GroupName, item.Users[0]);

						if (String.Compare(config.Method, "get", true) == 0)
						{
							Response.Redirect(config.GetData, true);
						}
						else
						{
							Response.Clear();
							Response.Write(config.PostData);
							Response.End();
						}
					}

				}
				catch (Exception ex)
				{
					ShowErrorMessage("SQL_GET_DATABASE", ex);
					return;
				}
			}



            bool editMode = (PanelRequest.ItemID > 0);
            btnDelete.Visible = editMode;

            BindItem();
        }
 /// <remarks/>
 public System.IAsyncResult BeginUpdateDatabase(SqlDatabase database, System.AsyncCallback callback, object asyncState)
 {
     return this.BeginInvoke("UpdateDatabase", new object[] {
                 database}, callback, asyncState);
 }
Esempio n. 5
0
        private void RestoreFromBackup(SqlDatabase database, string[] files)
        {
            // close current database connections
            CloseDatabaseConnections(database.Name);

            if (files.Length == 0)
                throw new ApplicationException("No backup files were uploaded"); // error: no backup files were uploaded

            if (files.Length > 1)
                throw new ApplicationException("Too many files were uploaded"); // error: too many files were uploaded

            string bakFile = files[0];

            try
            {
                // restore database
                // get file list from backup file
                string[][] backupFiles = GetBackupFiles(bakFile);

                if (backupFiles.Length != 2)
                    throw new ApplicationException("backup should contain exactly 2 logical files");

                // map backup files to existing ones
                string[] movings = new string[backupFiles.Length];
                for (int i = 0; i < backupFiles.Length; i++)
                {
                    string name = backupFiles[i][0];
                    string path = backupFiles[i][1];
                    if (Path.GetExtension(path).ToLower() == ".mdf")
                        path = database.DataPath;
                    else
                        path = database.LogPath;

                    movings[i] = String.Format("MOVE '{0}' TO '{1}'", name, path);
                }

                // restore database
                ExecuteNonQuery(String.Format(@"RESTORE DATABASE [{0}] FROM DISK = '{1}' WITH REPLACE, {2}",
                    database.Name, bakFile, String.Join(", ", movings)));


                // restore original database users
                UpdateDatabaseUsers(database.Name, database.Users);
            }
            finally
            {
                // delete uploaded files
                FileUtils.DeleteFiles(files);
                
            }
        }
		public int UpdateSqlDatabase(SqlDatabase item)
		{
			object[] results = this.Invoke("UpdateSqlDatabase", new object[] {
                        item});
			return ((int)(results[0]));
		}
        public static int AddSqlDatabase(SqlDatabase item, string groupName)
        {
			// check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // check package
            int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // check quota
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, groupName + ".Databases");
            if (quota.QuotaExhausted)
                return BusinessErrorCodes.ERROR_MSSQL_DATABASES_RESOURCE_QUOTA_LIMIT;

            // check if mail resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, groupName);
            if (serviceId == 0)
                return BusinessErrorCodes.ERROR_MSSQL_RESOURCE_UNAVAILABLE;

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, groupName, item.Name, typeof(SqlDatabase)) != null)
                return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_EXISTS;

            // place log record
            TaskManager.StartTask("SQL_DATABASE", "ADD", item.Name);
            TaskManager.WriteParameter("Provider", groupName);

            int itemId = default(int);
			//
            try
            {
                // check service items
                DatabaseServer sql = GetDatabaseServer(serviceId);
                if (sql.DatabaseExists(item.Name))
                    return BusinessErrorCodes.ERROR_MSSQL_DATABASES_SERVICE_ITEM_EXISTS;

                // calculate database location
                StringDictionary settings = ServerController.GetServiceSettings(serviceId);
                UserInfo user = PackageController.GetPackageOwner(item.PackageId);
                if (settings["UseDefaultDatabaseLocation"] != null &&
                    !Utils.ParseBool(settings["UseDefaultDatabaseLocation"], false))
                {
                    item.Location = Utils.ReplaceStringVariable(settings["DatabaseLocation"], "user_name", user.Username);
                }

                // set database size
                item.DataSize = GetMaxDatabaseSize(item.PackageId, groupName);

                
                // set log size
                item.LogSize = GetMaxLogSize(item.PackageId, groupName);

                // add service item
                sql.CreateDatabase(item);

                // save item
                item.ServiceId = serviceId;
                itemId = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;
                                
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
				//
                if (ex.Message.Contains("INVALID_DATABASE_NAME"))
                    return BusinessErrorCodes.ERROR_MYSQL_INVALID_DATABASE_NAME;
				// Return a generic error instead of default(int)
				itemId = BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            return itemId;
        }
Esempio n. 8
0
        public virtual void CreateDatabase(SqlDatabase database)
        {
            if (database.Users == null)
                database.Users = new string[0];

            string commandText = "";
            if (String.IsNullOrEmpty(database.Location))
            {
                // load default location
                SqlDatabase dbMaster = GetDatabase("master");
                database.Location = Path.GetDirectoryName(dbMaster.DataPath);
            }
            else
            {
                // subst vars
                database.Location = FileUtils.EvaluateSystemVariables(database.Location);

                // verify folder exists
                if (!Directory.Exists(database.Location))
                    Directory.CreateDirectory(database.Location);
            }

			string collation = String.IsNullOrEmpty(DatabaseCollation) ? "" : " COLLATE " + DatabaseCollation;

            // create command
            string dataFile = Path.Combine(database.Location, database.Name) + "_data.mdf";
            string logFile = Path.Combine(database.Location, database.Name) + "_log.ldf";

            
            commandText = string.Format("CREATE DATABASE [{0}]" +
                    " ON ( NAME = '{1}_data', {2})" +
                    " LOG ON ( NAME = '{3}_log', {4}){5};",
                    database.Name,
                    database.Name, 
                    CreateFileNameString(dataFile,database.DataSize),
                    database.Name, 
                    CreateFileNameString(logFile, database.LogSize),
                    collation);
            

            // create database
            ExecuteNonQuery(commandText);

            // grant users access
            UpdateDatabaseUsers(database.Name, database.Users);
        }
 public int AddSqlDatabase(SqlDatabase item, string groupName)
 {
     return DatabaseServerController.AddSqlDatabase(item, groupName);
 }
        public static int UpdateSqlDatabase(SqlDatabase item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            SqlDatabase origItem = (SqlDatabase)PackageController.GetPackageItem(item.Id);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MSSQL_DATABASES_PACKAGE_ITEM_NOT_FOUND;

            // check package
            int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // place log record
            TaskManager.StartTask("SQL_DATABASE", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;
            TaskManager.WriteParameter("Provider", origItem.GroupName);

            try
            {
                // get service
                DatabaseServer sql = GetDatabaseServer(origItem.ServiceId);

                // update service item
                sql.UpdateDatabase(item);
                return 0;
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
				// Return a generic error instead of re-throwing an exception
				return BusinessErrorCodes.FAILED_EXECUTE_SERVICE_OPERATION;
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
Esempio n. 11
0
        public virtual void CreateDatabase(SqlDatabase database)
        {
            if (database.Users == null)
                database.Users = new string[0];

            /*if (!((Regex.IsMatch(database.Name, @"[^\w\.-]")) && (database.Name.Length > 40)))
            {
                Exception ex = new Exception("INVALID_DATABASE_NAME");
                throw ex;
            }
             */

            // create database
            ExecuteNonQuery(String.Format("CREATE DATABASE IF NOT EXISTS {0};", database.Name));

            // grant users access
            foreach (string user in database.Users)
                AddUserToDatabase(database.Name, user);
        }
Esempio n. 12
0
        public virtual void UpdateDatabase(SqlDatabase database)
        {
            if (database.Users == null)
                database.Users = new string[0];

            // remove all users from database
            string[] users = GetDatabaseUsers(database.Name);
            foreach (string user in users)
                RemoveUserFromDatabase(database.Name, user);

            // grant users access
            foreach (string user in database.Users)
                AddUserToDatabase(database.Name, user);
        }
 public void UpdateDatabase(SqlDatabase database)
 {
     try
     {
         Log.WriteStart("'{0}' UpdateDatabase", ProviderSettings.ProviderName);
         DatabaseProvider.UpdateDatabase(database);
         Log.WriteEnd("'{0}' UpdateDatabase", ProviderSettings.ProviderName);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' UpdateDatabase", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
Esempio n. 14
0
        public virtual SqlDatabase GetDatabase(string databaseName)
        {
            if (!DatabaseExists(databaseName))
                return null;

            SqlDatabase database = new SqlDatabase();

            database.Name = databaseName;

            // calculate database size
            DataView dvTables = ExecuteQuery(String.Format("SHOW TABLE STATUS FROM {0}", databaseName)).DefaultView;
            long data = 0;
            long index = 0;

            foreach (DataRowView drTable in dvTables)
            {
				//
				if (!Convert.IsDBNull(drTable["Data_length"]))
				{
					data += Convert.ToInt64(drTable["Data_length"]);
				}
				//
				if (!Convert.IsDBNull(drTable["Index_length"]))
				{
					index += Convert.ToInt64(drTable["Index_length"]);
				}
            }

            //size in KB
            database.DataSize = (int)(data + index) / 1024;

            // get database uzers
            database.Users = GetDatabaseUsers(databaseName);

            return database;
        }
 public void SaveItem(SqlDatabase item)
 {
 }
		/// <remarks/>
		public void AddSqlDatabaseAsync(SqlDatabase item, string groupName)
		{
			this.AddSqlDatabaseAsync(item, groupName, null);
		}
		/// <remarks/>
		public void UpdateSqlDatabaseAsync(SqlDatabase item)
		{
			this.UpdateSqlDatabaseAsync(item, null);
		}
 /// <remarks/>
 public void UpdateDatabaseAsync(SqlDatabase database)
 {
     this.UpdateDatabaseAsync(database, null);
 }
        public int InstallWebApplication(InstallationInfo inst)
        {
            // place log record
            TaskManager.StartTask("APP_INSTALLER", "INSTALL_APPLICATION");
            TaskManager.WriteParameter("Virtual directory", inst.VirtualDir);
            TaskManager.WriteParameter("Database group", inst.DatabaseGroup);
            TaskManager.ItemId = inst.PackageId;

            try
            {
                // get application info
                app = GetApplication(inst.PackageId, inst.ApplicationId);

                TaskManager.ItemName = app.Name;

                // check web site for existance
                WebSite webSite = WebServerController.GetWebSite(inst.WebSiteId);

                if (webSite == null)
                    return BusinessErrorCodes.ERROR_WEB_INSTALLER_WEBSITE_NOT_EXISTS;

				TaskManager.WriteParameter("Web site", webSite.Name);

                webSiteName = webSite.Name;
                siteId = webSite.SiteId;

                // change web site properties if required
                if (String.IsNullOrEmpty(inst.VirtualDir))
                {
                    ChangeVirtualDirectoryProperties(webSite, app.WebSettings);
                    WebServerController.UpdateWebSite(webSite);
                }

                // get OS service
                int osId = PackageController.GetPackageServiceId(inst.PackageId, "os");
                os = new OS.OperatingSystem();
                ServiceProviderProxy.Init(os, osId);

                // get remote content path
                contentPath = webSite.ContentPath;

                // create virtual dir if required
                if (!String.IsNullOrEmpty(inst.VirtualDir))
                {
                    // check if the required virtual dir already exists
                    contentPath = Path.Combine(contentPath, inst.VirtualDir);

                    WebVirtualDirectory vdir = null;
                    int result = WebServerController.AddVirtualDirectory(inst.WebSiteId, inst.VirtualDir, contentPath);
                    if (result == BusinessErrorCodes.ERROR_VDIR_ALREADY_EXISTS)
                    {
                        // the directory alredy exists
                        vdir = WebServerController.GetVirtualDirectory(
                            inst.WebSiteId, inst.VirtualDir);

                        contentPath = vdir.ContentPath;
                    }
                    else
                    {
                        vdir = WebServerController.GetVirtualDirectory(
                            inst.WebSiteId, inst.VirtualDir);

                        inst[PROPERTY_VDIR_CREATED] = "True";
                    }

                    // change virtual directory properties if required
                    ChangeVirtualDirectoryProperties(vdir, app.WebSettings);
                    WebServerController.UpdateVirtualDirectory(inst.WebSiteId, vdir);
                }

                // deploy application codebase ZIP and then unpack it
                string codebasePath = app.Codebase;
                string remoteCodebasePath = Path.Combine(contentPath, Path.GetFileName(app.Codebase));

                // make content path absolute
                string absContentPath = FilesController.GetFullPackagePath(inst.PackageId, contentPath);

                // save content path
                inst[PROPERTY_CONTENT_PATH] = contentPath;
                inst[PROPERTY_ABSOLUTE_CONTENT_PATH] = absContentPath;

                // copy ZIP to the target server
                FileStream stream = File.OpenRead(codebasePath);
                int BUFFER_LENGTH = 5000000;

                byte[] buffer = new byte[BUFFER_LENGTH];
                int readBytes = 0;
                while (true)
                {
                    readBytes = stream.Read(buffer, 0, BUFFER_LENGTH);

                    if (readBytes < BUFFER_LENGTH)
                        Array.Resize<byte>(ref buffer, readBytes);

                    FilesController.AppendFileBinaryChunk(inst.PackageId, remoteCodebasePath, buffer);

                    if (readBytes < BUFFER_LENGTH)
                        break;
                }


                
                // unpack codebase
                inst[PROPERTY_INSTALLED_FILES] = String.Join(";",
                   FilesController.UnzipFiles(inst.PackageId, new string[] { remoteCodebasePath }));
                
                // delete codebase zip
                FilesController.DeleteFiles(inst.PackageId, new string[] { remoteCodebasePath });

                // check/create databases
                if (!String.IsNullOrEmpty(inst.DatabaseGroup) &&
                    String.Compare(inst.DatabaseGroup, "None", true) != 0)
                {
                    // database
                    if (inst.DatabaseId == 0)
                    {
                        TaskManager.WriteParameter("Database name", inst.DatabaseName);

                        // we should create a new database
                        SqlDatabase db = new SqlDatabase();
                        db.PackageId = inst.PackageId;
                        db.Name = inst.DatabaseName;
                        inst.DatabaseId = DatabaseServerController.AddSqlDatabase(db, inst.DatabaseGroup);
                        if (inst.DatabaseId < 0)
                        {
                            // rollback installation
                            RollbackInstallation(inst);

                            // return error
                            return inst.DatabaseId; // there was an error when creating database
                        }

                        inst[PROPERTY_DATABASE_CREATED] = "True";
                    }
                    else
                    {
                        // existing database
                        SqlDatabase db = DatabaseServerController.GetSqlDatabase(inst.DatabaseId);
                        inst.DatabaseName = db.Name;

                        TaskManager.WriteParameter("Database name", inst.DatabaseName);
                    }

                    SqlUser user = null;
                    // database user
                    if (inst.UserId == 0)
                    {
                        TaskManager.WriteParameter("Database user", inst.Username);

                        // NEW USER
                        user = new SqlUser();
                        user.PackageId = inst.PackageId;
                        user.Name = inst.Username;
                        user.Databases = new string[] { inst.DatabaseName };
                        user.Password = inst.Password;
                        inst.UserId = DatabaseServerController.AddSqlUser(user, inst.DatabaseGroup);
                        if (inst.UserId < 0)
                        {
                            // rollback installation
                            RollbackInstallation(inst);

                            // return error
                            return inst.UserId; // error while adding user
                        }

                        inst[PROPERTY_USER_CREATED] = "True";
                    }
                    else
                    {
                        // EXISTING USER
                        user = DatabaseServerController.GetSqlUser(inst.UserId);
                        inst.Username = user.Name;

                        TaskManager.WriteParameter("Database user", inst.Username);

                        List<string> databases = new List<string>();
                        databases.AddRange(user.Databases);

                        if (!databases.Contains(inst.DatabaseName))
                        {
                            databases.Add(inst.DatabaseName);

                            user.Databases = databases.ToArray();
                            DatabaseServerController.UpdateSqlUser(user);
                        }
                    }

                    // check connectivity with SQL Server and credentials provided
                    // load user item
                    int sqlServiceId = PackageController.GetPackageServiceId(inst.PackageId, inst.DatabaseGroup);
                    sql = new DatabaseServer();
                    ServiceProviderProxy.Init(sql, sqlServiceId);

                    if (!sql.CheckConnectivity(inst.DatabaseName, inst.Username,
                        inst.Password))
                    {
                        // can't connect to the database
                        RollbackInstallation(inst);

                        return BusinessErrorCodes.ERROR_WEB_INSTALLER_CANT_CONNECT_DATABASE;
                    }

                    // read SQL server settings
                    StringDictionary settings = ServerController.GetServiceSettings(sqlServiceId);
                    serverIpAddressExternal = settings["ExternalAddress"];
					if (settings.ContainsKey("InternalAddress"))
					{
						serverIpAddressInternal = settings["InternalAddress"];
					}
                }

                // ********* RUN INSTALL SCENARIO ***********
                int scriptResult = RunInstallScenario(inst);
                if (scriptResult < 0)
                {
                    // rollback installation
                    RollbackInstallation(inst);

                    // return error
                    return scriptResult;
                }

                // add new installation to the database
                return 0;
            }
            catch (Exception ex)
            {
                // rollback installation
                RollbackInstallation(inst);

                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
 /// <remarks/>
 public void UpdateDatabaseAsync(SqlDatabase database, object userState)
 {
     if ((this.UpdateDatabaseOperationCompleted == null))
     {
         this.UpdateDatabaseOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateDatabaseOperationCompleted);
     }
     this.InvokeAsync("UpdateDatabase", new object[] {
                 database}, this.UpdateDatabaseOperationCompleted, userState);
 }
        private void BindItem()
        {
            string policyName = (SqlDatabases.GetDatabasesGroupName(Settings).ToLower().StartsWith("mssql"))
                ? UserSettings.MSSQL_POLICY : UserSettings.MYSQL_POLICY;

            try
            {
                if (!IsPostBack)
                {
                    // load item if required
                    if (PanelRequest.ItemID > 0)
                    {
                        // existing item
                        try
                        {
                            item = ES.Services.DatabaseServers.GetSqlDatabase(PanelRequest.ItemID);
                        }
                        catch (Exception ex)
                        {
                            ShowErrorMessage("SQL_GET_DATABASE", ex);
                            return;
                        }

                        if (item != null)
                        {
                            
                            if (!string.IsNullOrEmpty(item.ExternalServerName))
                            {
                                lblDBExternalServer.Visible =litDBExternalServer.Visible = true;
                                litDBExternalServer.Text = item.ExternalServerName;
                            }

                            if (!string.IsNullOrEmpty(item.InternalServerName))
                            {
                                lblDBInternalServer.Visible = litDBInternalServer.Visible = true;
                                litDBInternalServer.Text = item.InternalServerName;
                            }

                            // save package info
                            ViewState["PackageId"] = item.PackageId;
                            usernameControl.SetPackagePolicy(item.PackageId, policyName, "DatabaseNamePolicy");
                            BindUsers(item.PackageId);
                        }
                        else
                            RedirectToBrowsePage();
                    }
                    else
                    {
                        lblDBExternalServer.Visible = lblDBInternalServer.Visible = false;
                        litDBExternalServer.Visible = litDBInternalServer.Visible = false;

                        // new item
                        ViewState["PackageId"] = PanelSecurity.PackageId;
                        usernameControl.SetPackagePolicy(PanelSecurity.PackageId, policyName, "DatabaseNamePolicy");
                        BindUsers(PanelSecurity.PackageId);
                    }
                }

                // load provider control
                LoadProviderControl((int)ViewState["PackageId"], SqlDatabases.GetDatabasesGroupName(Settings),
                    providerControl, "EditDatabase.ascx");

                if (!IsPostBack)
                {
                    // bind item to controls
                    if (item != null)
                    {
                        // bind item to controls
                        usernameControl.Text = item.Name;
                        usernameControl.EditMode = true;

                        foreach (string user in item.Users)
                        {
                            ListItem li = dlUsers.Items.FindByValue(user);
                            if (li != null)
                                li.Selected = true;
                        }

                        // other controls
                        IDatabaseEditDatabaseControl ctrl = (IDatabaseEditDatabaseControl)providerControl.Controls[0];
                        ctrl.BindItem(item);
                    }
                }
            }
            catch(Exception ex)
            {
                ShowErrorMessage("INIT_SERVICE_ITEM_FORM", ex);
                DisableFormControls(this, btnCancel);
                return;
            }
        }
 public int UpdateSqlDatabase(SqlDatabase item)
 {
     return DatabaseServerController.UpdateSqlDatabase(item);
 }
        private void SaveItem()
        {
            if (!Page.IsValid)
                return;

            // get form data
            SqlDatabase item = new SqlDatabase();
            item.Id = PanelRequest.ItemID;
            item.PackageId = PanelSecurity.PackageId;
            item.Name = usernameControl.Text;
            
            List<string> users = new List<string>();
            foreach (ListItem li in dlUsers.Items)
            {
                if (li.Selected)
                    users.Add(li.Value);
            }
            item.Users = users.ToArray();

            // get other props
            IDatabaseEditDatabaseControl ctrl = (IDatabaseEditDatabaseControl)providerControl.Controls[0];
            ctrl.SaveItem(item);

            if (PanelRequest.ItemID == 0)
            {
                // new item
                try
                {
                    int result = ES.Services.DatabaseServers.AddSqlDatabase(item, SqlDatabases.GetDatabasesGroupName(Settings));
					// Show an error message if the operation has failed to complete
                    if (result < 0)
                    {
                        ShowResultMessageWithContactForm(result);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("SQL_ADD_DATABASE", ex);
                    return;
                }
            }
            else
            {
                // existing item
                try
                {
                    int result = ES.Services.DatabaseServers.UpdateSqlDatabase(item);
					// Show an error message if the operation has failed to complete
                    if (result < 0)
                    {
						ShowResultMessageWithContactForm(result);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("SQL_UPDATE_DATABASE", ex);
                    return;
                }
            }

            // return
            RedirectSpaceHomePage();
        }
        public void ImportItem(int packageId, int itemTypeId,
            Type itemType, ResourceGroupInfo group, string itemName)
        {
            // get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
            if (serviceId == 0)
                return;

            if (itemType == typeof(SqlDatabase))
            {
                // import database
                SqlDatabase db = new SqlDatabase();
                db.ServiceId = serviceId;
                db.PackageId = packageId;
                db.Name = itemName;
                db.GroupName = group.GroupName;
                PackageController.AddPackageItem(db);
            }
            else if (itemType == typeof(SqlUser))
            {
                // import user
                SqlUser user = new SqlUser();
                user.ServiceId = serviceId;
                user.PackageId = packageId;
                user.Name = itemName;
                user.GroupName = group.GroupName;
                user.Password = "";
                PackageController.AddPackageItem(user);
            }
        }
Esempio n. 25
0
        public virtual void RestoreDatabase(string databaseName, string[] files)
        {
            string tempPath = Path.GetTempPath();

            //create folder with unique name to avoid getting all files from temp directory
            string zipPath = Path.Combine(tempPath, Guid.NewGuid().ToString());

            // store original database information
            SqlDatabase database = GetDatabase(databaseName);

            // unzip uploaded files if required
            List <string> expandedFiles = new List <string>();

            foreach (string file in files)
            {
                if (Path.GetExtension(file).ToLower() == ".zip")
                {
                    // unpack file
                    expandedFiles.AddRange(FileUtils.UnzipFiles(file, zipPath));

                    // delete zip archive
                    FileUtils.DeleteFile(file);
                }
                else
                {
                    // just add file to the collection
                    if (!FileUtils.DirectoryExists(zipPath))
                    {
                        FileUtils.CreateDirectory(zipPath);
                    }
                    string newfile = Path.Combine(zipPath, Path.GetFileName(file));
                    FileUtils.MoveFile(file, newfile);
                    expandedFiles.Add(newfile);
                }
            }

            files = new string[expandedFiles.Count];
            expandedFiles.CopyTo(files, 0);

            if (files.Length == 0)
            {
                throw new ApplicationException("No backup files were uploaded"); // error: no backup files were uploaded
            }
            if (files.Length > 1)
            {
                throw new ApplicationException("Too many files were uploaded"); // error: too many files were uploaded
            }
            // analyze uploaded files
            bool fromDump = true;

            foreach (string file in files)
            {
                if (Path.GetExtension(file).ToLower() != ".sql")
                {
                    fromDump = false;
                    break;
                }
            }

            if (fromDump)
            {
                // restore database
                // create temporary batchfile
                string       batchfilename = Path.Combine(zipPath, "MySql_Restore.bat");
                StreamWriter file          = new StreamWriter(batchfilename);
                file.WriteLine("@ECHO OFF");
                file.WriteLine("cls");
                file.WriteLine("set host=%1%");
                file.WriteLine("set port=%2%");
                file.WriteLine("set user=%3%");
                file.WriteLine("set password=%4%");
                file.WriteLine("set dbname=%5%");
                file.WriteLine("set dumpfile=%6%");
                file.WriteLine("\"" + Path.Combine(MySqlBinFolder, "mysql") + "\" --host=%host% --port=%port% --user=%user% --password=%password% %dbname% < %dumpfile%");
                file.Close();
                // restore from .SQL file
                CloseDatabaseConnections(database.Name);
                try
                {
                    string sqlFile = files[0];
                    string args    = string.Format(" {0} {1} {2} {3} {4} {5}",
                                                   ServerName, ServerPort,
                                                   RootLogin, RootPassword, database.Name, Path.GetFileName(sqlFile));

                    FileUtils.ExecuteSystemCommand(batchfilename, args);
                }
                finally
                {
                    // delete uploaded files
                    FileUtils.DeleteFiles(files);
                }
            }
            else
            {
                // do nothing
            }
            //delete temporary folder for zip contents
            if (FileUtils.DirectoryExists(zipPath))
            {
                FileUtils.DeleteDirectoryAdvanced(zipPath);
            }
        }
Esempio n. 26
0
        public virtual SqlDatabase GetDatabase(string databaseName)
        {
            if (!DatabaseExists(databaseName))
                return null;

            SqlDatabase database = new SqlDatabase();
            database.Name = databaseName;

            // get database size
            DataView dvFiles = ExecuteQuery(String.Format(
                "SELECT Status, (Size * 8) AS DbSize, Name, FileName FROM [{0}]..sysfiles", databaseName)).Tables[0].DefaultView;

            foreach (DataRowView drFile in dvFiles)
            {
                int status = (int)drFile["Status"];
                if ((status & 64) == 0)
                {
                    // data file
                    database.DataName = ((string)drFile["Name"]).Trim();
                    database.DataPath = ((string)drFile["FileName"]).Trim();
                    database.DataSize = (int)drFile["DbSize"];
                }
                else
                {
                    // log file
                    database.LogName = ((string)drFile["Name"]).Trim();
                    database.LogPath = ((string)drFile["FileName"]).Trim();
                    database.LogSize = (int)drFile["DbSize"];
                }
            }

            // get database uzers
            database.Users = GetDatabaseUsers(databaseName);
            return database;
        }
 /// <remarks/>
 public void CreateDatabaseAsync(SqlDatabase database)
 {
     this.CreateDatabaseAsync(database, null);
 }
Esempio n. 28
0
        public virtual void UpdateDatabase(SqlDatabase database)
        {
            if (database.Users == null)
                database.Users = new string[0];

            // grant users access
            UpdateDatabaseUsers(database.Name, database.Users);
        }
 public void UpdateDatabase(SqlDatabase database)
 {
     this.Invoke("UpdateDatabase", new object[] {
                 database});
 }
Esempio n. 30
0
        private void RestoreFromDataFiles(SqlDatabase database, string[] files)
        {
            // close current database connections
            CloseDatabaseConnections(database.Name);

            // detach database
            DetachDatabase(database.Name);

            string[] originalFiles = new string[] { database.DataPath, database.LogPath };

            try
            {
                // backup (rename) original database files
                BackupFiles(originalFiles);
            }
            catch (Exception ex)
            {
                AttachDatabase(database.Name, files);
                throw new Exception("Can't restore database", ex);
            }

            try
            {
                // replace original database files with uploaded ones
                for (int i = 0; i < files.Length; i++)
                {
                    if (Path.GetExtension(files[i]).ToLower() == ".mdf")
                        FileUtils.MoveFile(files[i], database.DataPath);
                    else
                        FileUtils.MoveFile(files[i], database.LogPath);
                }

                // attach database
                if (files.Length == 1)
                {
                    AttachSingleFileDatabase(database.Name, originalFiles[0]);
                }
                else
                {
                    AttachDatabase(database.Name, originalFiles);
                }
            }
            catch (SqlException ex)
            {
                if (ex.Number != 5105)
                    throw new ApplicationException("Can't attach database!", ex);

            }
            catch (Exception ex)
            {
                // restore original database files
                RollbackFiles(originalFiles);

                // attach old database
                AttachDatabase(database.Name, files);
                throw new Exception("Can't rollback original database files", ex);
            }
            finally
            {
                // restore original database users
                UpdateDatabaseUsers(database.Name, database.Users);

                // remove old backed up files
                for (int i = 0; i < originalFiles.Length; i++)
                    FileUtils.DeleteFile(originalFiles[i] + "_bak");
            }
        }
		/// <remarks/>
		public void AddSqlDatabaseAsync(SqlDatabase item, string groupName, object userState)
		{
			if ((this.AddSqlDatabaseOperationCompleted == null))
			{
				this.AddSqlDatabaseOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddSqlDatabaseOperationCompleted);
			}
			this.InvokeAsync("AddSqlDatabase", new object[] {
                        item,
                        groupName}, this.AddSqlDatabaseOperationCompleted, userState);
		}