Exemple #1
0
        public void Convert(DBHelper source, DBHelper target)
        {
            using (MD47.DataContext dataContext47 = new MD47.DataContext(string.Empty))
            {
                // Initialize metadata
                MD47.DataContext.Current = dataContext47;
                MD47.DataContext.Current.SqlContext.CommandTimeout = _commandTimeout;

                SqlTransaction previous45Transaction = MD45.MetaDataContext.Current.Transaction;
                SqlTransaction previous47Transaction = MD47.DataContext.Current.SqlContext.Transaction;
                //SqlTransaction previousDatabaseTransaction = Mediachase.IBN.Database.DbContext.Current.Transaction;

                using (DBTransaction tranSource = source.BeginTransaction())
                    using (DBTransaction tran = target.BeginTransaction())
                    {
                        DBHelper2.Init(source);
                        MD45.MetaDataContext.Current.Transaction        = tranSource.SqlTran;
                        MD47.DataContext.Current.SqlContext.Transaction = tran.SqlTran;
                        //Mediachase.IBN.Database.DbContext.Current.Transaction = tran.SqlTran;
                        try
                        {
                            Dictionary <int, OrganizationEntity> organizationsById = new Dictionary <int, OrganizationEntity>();
                            Dictionary <int, ContactEntity>      contactsById      = new Dictionary <int, ContactEntity>();

                            ConvertOrganizations(organizationsById);

                            string companyLocale = (string)target.RunTextScalar("SELECT [Locale] FROM [LANGUAGES] WHERE [IsDefault]=1");
                            ConvertContacts(companyLocale, organizationsById, contactsById);

                            UpdateObjects(target, organizationsById, contactsById);

                            //Update email boxes
                            UpdateXmlInDatabase(target, organizationsById, contactsById, new ProcessXmlDelegate(UpdateEmailBoxes), "EMailRouterPop3Box", "EMailRouterPop3BoxId", "Settings");

                            // Update reports
                            UpdateXmlInDatabase(target, organizationsById, contactsById, new ProcessXmlDelegate(UpdateReports), "Report", "ReportId", "IBNReportTemplate");

                            tran.Commit();
                        }
                        finally
                        {
                            MD45.MetaDataContext.Current.Transaction        = previous45Transaction;
                            MD47.DataContext.Current.SqlContext.Transaction = previous47Transaction;
                            //Mediachase.IBN.Database.DbContext.Current.Transaction = previousDatabaseTransaction;
                        }
                    }
            }
        }
Exemple #2
0
		public void Convert(int sourceCompanyId, int targetCompanyId)
		{
			bool convertAll = true;

			DBHelper source = new DBHelper(_sourceConnectionString);
			DBHelper target = new DBHelper(_targetConnectionString);
			source.CommandTimeout = target.CommandTimeout = _sqlCommandTimeout;

			#region Validate databases' versions

			ValidateDatabaseVersion(source, RequiredSourceVersion, true);
			ValidateDatabaseVersion(target, RequiredTargetVersion, false);

			string sourcePortalDatabase = GetPortalDB(source, sourceCompanyId);
			string targetPortalDatabase = GetPortalDB(target, targetCompanyId);

			source.Database = sourcePortalDatabase;
			target.Database = targetPortalDatabase;

			ValidateDatabaseVersion(source, RequiredSourceVersion, true);
			ValidateDatabaseVersion(target, RequiredTargetVersion, false);

			source.Database = null;
			target.Database = null;

			#endregion

			#region Declare variables

			XmlDocument doc = new XmlDocument();
			string tableName, selectCommand;
			List<StringCollection> nameLists = new List<StringCollection>();
			List<Hashtable> valueHashTables = new List<Hashtable>();

			StringCollection namesCompanyId = new StringCollection();
			StringCollection namesImGroupId = new StringCollection();
			StringCollection namesUserId = new StringCollection();
			StringCollection namesChatId = new StringCollection();

			Hashtable valuesCompanyId = new Hashtable();
			Hashtable valuesImGroupId = new Hashtable();
			Hashtable valuesUserId = new Hashtable();
			Hashtable valuesChatId = new Hashtable();

			nameLists.Add(namesCompanyId);
			nameLists.Add(namesImGroupId);
			nameLists.Add(namesUserId);
			nameLists.Add(namesChatId);

			valueHashTables.Add(valuesCompanyId);
			valueHashTables.Add(valuesImGroupId);
			valueHashTables.Add(valuesUserId);
			valueHashTables.Add(valuesChatId);

			namesCompanyId.Add("company_id");
			namesImGroupId.Add("imgroup_id");
			namesImGroupId.Add("dep_imgroup_id");
			namesImGroupId.Add("imgroupid");
			namesUserId.Add("user_id");
			namesUserId.Add("from_user_id");
			namesUserId.Add("to_user_id");
			namesUserId.Add("owner_id");
			namesUserId.Add("cont_user_id");
			namesUserId.Add("originalid");
			namesChatId.Add("chat_id");
			#endregion

			if (convertAll)
			{
				#region Convert Main DB
				SendProgress("*** Converting main database ***");
				SendProgress("Deleting target company data");

				target.RunSP("ASP_EmptyTables",
					DBHelper.MP("@company_id", SqlDbType.Int, targetCompanyId),
					DBHelper.MP("@delete_trial_requests", SqlDbType.Bit, true));

				SendProgress("Done");

				doc.Load("ConvertMain.xml");
				foreach (XmlNode table in doc.SelectNodes("/tables/table"))
				{
					bool copyBinary = true;
					{
						XmlAttribute attr = table.Attributes["copyBinary"];
						if (attr != null)
							copyBinary = bool.Parse(attr.Value);
					}

					tableName = table.Attributes["name"].Value;
					switch (tableName)
					{
						case "COMPANIES":
							valuesCompanyId[sourceCompanyId] = targetCompanyId;
							ArrayList skip = new ArrayList();
							skip.Add("company_id");
							skip.Add("domain");
							skip.Add("db_name");
							skip.Add("app_id");
							UpdateRecord(tableName, string.Format(CultureInfo.InvariantCulture, "WHERE [company_id] = {0}", sourceCompanyId), string.Format(CultureInfo.InvariantCulture, "WHERE [company_id] = {0}", targetCompanyId), skip, source, target);
							break;
						case "IMGROUPS":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "WHERE company_id={1}", tableName, sourceCompanyId);
							CopyTable(tableName, "", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, valuesImGroupId);
							break;
						case "USER":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "U JOIN IMGROUPS G ON (G.imgroup_id = U.imgroup_id) WHERE G.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "U.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, valuesUserId);
							break;
						case "CHATS":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "C JOIN [USER] U ON (U.user_id = C.owner_id) JOIN IMGROUPS G ON (G.imgroup_id = U.imgroup_id) WHERE G.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "C.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, valuesChatId);
							break;

						case "BINARY_DATA":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "WHERE [fid] IN (SELECT D2.file_id FROM [FILE] D2 JOIN [USER] U1 ON (U1.user_id = D2.from_user_id) JOIN IMGROUPS G1 ON (G1.imgroup_id = U1.imgroup_id) JOIN [USER] U2 ON (U2.user_id = D2.to_user_id) JOIN IMGROUPS G2 ON (G2.imgroup_id = U2.imgroup_id) WHERE G1.company_id = {0} AND G2.company_id = {0})", sourceCompanyId);
							CopyTable(tableName, "", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, null);
							break;
						case "CONTACT_LIST":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "D2 JOIN [USER] U1 ON (U1.user_id = D2.user_id) JOIN IMGROUPS G1 ON (G1.imgroup_id = U1.imgroup_id) JOIN [USER] U2 ON (U2.user_id = D2.cont_user_id) JOIN IMGROUPS G2 ON (G2.imgroup_id = U2.imgroup_id) WHERE G1.company_id = {1} AND G2.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "D2.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, null);
							break;
						case "DEPENDENCES":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "D JOIN IMGROUPS G1 ON (G1.imgroup_id = D.imgroup_id) JOIN IMGROUPS G2 ON (G2.imgroup_id = D.DEP_IMGROUP_ID) WHERE G1.company_id = {1} AND G2.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "D.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, null);
							break;
						case "CHAT_USERS":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "D2 JOIN [USER] U1 ON (U1.user_id = D2.user_id) JOIN IMGROUPS G1 ON (G1.imgroup_id = U1.imgroup_id) JOIN [USER] U2 ON (U2.user_id = D2.from_user_id) JOIN IMGROUPS G2 ON (G2.imgroup_id = U2.imgroup_id) WHERE G1.company_id = {1} AND G2.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "D2.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, null);
							break;

						case "AUTH_LIST":
						case "FILE":
						case "USER_MESS":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "D2 JOIN [USER] U1 ON (U1.user_id = D2.from_user_id) JOIN IMGROUPS G1 ON (G1.imgroup_id = U1.imgroup_id) JOIN [USER] U2 ON (U2.user_id = D2.to_user_id) JOIN IMGROUPS G2 ON (G2.imgroup_id = U2.imgroup_id) WHERE G1.company_id = {1} AND G2.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "D2.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, null);
							break;

						case "PORTAL_SESSIONS":
						case "SESSIONS":
						case "STATUS_LOG":
						case "CHAT_MESS":
							selectCommand = string.Format(CultureInfo.InvariantCulture, "D1 JOIN [USER] U ON (U.user_id = D1.user_id) JOIN IMGROUPS G ON (G.imgroup_id = U.imgroup_id) WHERE G.company_id = {1}", tableName, sourceCompanyId);
							CopyTable(tableName, "D1.", "*", selectCommand, copyBinary, source, target, nameLists, valueHashTables, false, null);
							break;
					}
				}

				SendProgress("Hashing passwords...");
				HashPasswords(target, "USER", "USER_ID", "PASSWORD");
				SendProgress("Done");

				SendProgress("*** Done ***");
				#endregion
			}

			#region Convert portal DB
			SendProgress("*** Converting portal database ***");

			source.Database = sourcePortalDatabase;
			target.Database = targetPortalDatabase;

			if (convertAll)
			{
				SqlCommand cmd = new SqlCommand();
				cmd.CommandType = CommandType.Text;

				doc.Load("ConvertPortal.xml");
				XmlNodeList tablesCopy = doc.SelectNodes("/tables/table");

				#region Clear tables in reversed order

				ClearTables(tablesCopy, target);

				#endregion

				#region Load calendars for imported projects
				Hashtable calendars = new Hashtable();
				using (IDataReader reader = source.RunTextDataReader("SELECT CalendarId, ProjectId FROM [CALENDARS] WHERE ProjectId IS NOT NULL"))
				{
					while (reader.Read())
					{
						calendars[reader[0]] = reader[1];
					}
				}
				#endregion

				#region Copy tables

				CopyPortalTables(1, 1, tablesCopy, source, target, nameLists, valueHashTables);

				#endregion

				#region Update ProjectId column for CALENDARS
				SendProgress("Updating project calendars");

				foreach (object key in calendars.Keys)
				{
					object projectId = calendars[key];
					target.RunTextDataReader("UPDATE [CALENDARS] SET ProjectId=@pid WHERE CalendarId=@cid"
						, DBHelper.MP("@pid", SqlDbType.Int, projectId)
						, DBHelper.MP("@cid", SqlDbType.Int, key)
						);
				}

				SendProgress("Done");
				#endregion

				#region Copy meta data
				SendProgress("* Copying metadata *");

				// Load meta classes
				ArrayList metaClasses = MyMetaClass.LoadList(source);

				StringBuilder sbMetaClassesToDelete = new StringBuilder();

				// Load meta fields, create and copy tables
				foreach (MyMetaClass mc in metaClasses)
				{
					if (mc.Name.StartsWith("ListsEx_", StringComparison.Ordinal) || mc.Name.StartsWith("ListTemplate_", StringComparison.Ordinal))
					{
						if(sbMetaClassesToDelete.Length > 0)
							sbMetaClassesToDelete.Append(",");
						sbMetaClassesToDelete.Append(mc.MetaClassId.ToString(CultureInfo.InvariantCulture));
					}
					else
					{
						mc.LoadFields(source);

						SendProgress("Creating tables for MetaData class: {0}", mc.Name);

						mc.CreateTables(target);

						SendProgress("Done");

						selectCommand = "";//string.Format("SELECT * FROM [{0}]", mc.TableName);
						CopyTable(mc.TableName, "", "*", selectCommand, true, source, target, null, null, true, null);
						CopyTable(mc.TableNameHistory, "", "*", selectCommand, true, source, target, null, null, true, null);
					}
				}

				string metaClassesToDelete = sbMetaClassesToDelete.ToString();
				if (!string.IsNullOrEmpty(metaClassesToDelete))
				{
					target.RunText(string.Concat("DELETE FROM [MetaClassMetaFieldRelation] WHERE [MetaClassId] IN (", metaClassesToDelete, ")"));
					target.RunText(string.Concat("DELETE FROM [MetaClass] WHERE [MetaClassId] IN (", metaClassesToDelete, ")"));
				}

				string defaultLocale = (string)source.RunTextScalar("SELECT [Locale] FROM [LANGUAGES] WHERE [IsDefault] = 1");
				using (DBTransaction tran = target.BeginTransaction())
				{
					//target.RunText("DROP TABLE [OrganizationsEx]");
					//target.RunText("DROP TABLE [OrganizationsEx_History]");
					Mediachase.MetaDataPlus.Configurator.MetaInstaller.RestoreFromFile(tran.SqlTran, string.Format(CultureInfo.InvariantCulture, "metadata_{0}.xml", defaultLocale));

					tran.Commit();
				}

				SendProgress("* Done *");
				#endregion

				#region Copy GROUPS to cls_Principal

				using (IDataReader reader = source.RunTextDataReader("SELECT [PrincipalId], [GroupName] FROM [GROUPS] WHERE [PrincipalId] > 9"))
				{
					while (reader.Read())
					{
						int principalId = (int)reader["PrincipalId"];
						string groupName = reader["GroupName"].ToString();

						target.RunText(
							"INSERT INTO [cls_Principal] ([PrincipalId],[Card],[Name],[Activity]) VALUES (@1,N'Department',@2,3)"
						, DBHelper.MP("@1", SqlDbType.Int, principalId)
						, DBHelper.MP("@2", SqlDbType.NVarChar, 100, groupName)
						);
					}
				}

				#endregion

				#region Copy USERS to cls_Principal

				using (IDataReader reader = source.RunTextDataReader("SELECT [PrincipalId], [FirstName], [LastName], [Activity] FROM [USERS]"))
				{
					while (reader.Read())
					{
						int principalId = (int)reader["PrincipalId"];
						string firstName = reader["FirstName"].ToString();
						string lastName = reader["LastName"].ToString();
						byte activity = (byte)reader["Activity"];

						target.RunText(
							"INSERT INTO [cls_Principal] ([PrincipalId],[Card],[Name],[Activity]) VALUES (@1,N'User',@2,@3)"
						, DBHelper.MP("@1", SqlDbType.Int, principalId)
						, DBHelper.MP("@2", SqlDbType.NVarChar, 100, lastName + ", " + firstName)
						, DBHelper.MP("@3", SqlDbType.Int, activity)
						);
					}
				}

				#endregion


				SendProgress("Hashing passwords...");
				HashPasswords(target, "USERS", "PrincipalId", "Password");
				SendProgress("Done");

				// Update ExpectedAssignDate for issues
				target.RunText("SET DATEFIRST 7 UPDATE [INCIDENTS] SET [ExpectedAssignDate] = [dbo].GetFinishDateByDuration(B.CalendarId, I.CreationDate, B.ExpectedAssignTime) FROM [INCIDENTS] I JOIN [IncidentBox] B ON (B.IncidentBoxId = I.IncidentBoxId)");

				#region Convert timesheets

				SendProgress("* Converting timesheets *");

				using (DBTransaction tran = target.BeginTransaction())
				{
					ConvertTimesheets(source, target);

					tran.Commit();
				}

				SendProgress("* Done *");

				#endregion
			}

			string installationDirectoryPath = @"..\"; // TODO: get from registry
			Mediachase.Ibn.GlobalContext.Current = new GlobalContext(System.IO.Path.Combine(installationDirectoryPath, @"Web\portal\Apps"));

			#region Convert lists

			SendProgress("* Converting lists *");

			using (MD47.DataContext dataContext47 = new MD47.DataContext(string.Empty))
			{
				// Initialize metadata
				MD47.DataContext.Current = dataContext47;
				dataContext47.SqlContext.CommandTimeout = _sqlCommandTimeout;
				//MD45.MetaDataContext.Current.ConnectionString = sourcePortalConnectionString;

				SqlTransaction previousSourceTransaction = MD45.MetaDataContext.Current.Transaction;
				SqlTransaction previousTargetTransaction = MD47.DataContext.Current.SqlContext.Transaction;
				SqlTransaction previousDatabaseTransaction = Mediachase.IBN.Database.DbContext.Current.Transaction;

				using (DBTransaction tranSource = source.BeginTransaction())
				using (DBTransaction tran = target.BeginTransaction())
				{
					MD45.MetaDataContext.Current.Transaction = tranSource.SqlTran;
					MD47.DataContext.Current.SqlContext.Transaction = tran.SqlTran;
					Mediachase.IBN.Database.DbContext.Current.Transaction = tran.SqlTran;
					try
					{
						ConvertLists(source, target);

						tran.Commit();
					}
					finally
					{
						MD45.MetaDataContext.Current.Transaction = previousSourceTransaction;
						MD47.DataContext.Current.SqlContext.Transaction = previousTargetTransaction;
						Mediachase.IBN.Database.DbContext.Current.Transaction = previousDatabaseTransaction;
					}
				}
			}

			SendProgress("* Done *");

			#endregion

			#region Convert contacts and organizations

			SendProgress("* Converting contacts and organizations *");

			ClientsConverter clientsConverter = new ClientsConverter(_sqlCommandTimeout);
			try
			{
				clientsConverter.Warning += new EventHandler<ClientsConverterEventArgs>(OnClientsConverterWarning);
				clientsConverter.Convert(source, target);
			}
			finally
			{
				clientsConverter.Warning -= OnClientsConverterWarning;
			}

			SendProgress("* Done *");

			#endregion

			target.RunText("DELETE [HISTORY] WHERE [ObjectTypeId] = 21 OR [ObjectTypeId] = 22");
			target.RunText("DELETE FROM [USER_SETTINGS] WHERE [Value] LIKE '%org%' OR [Value] LIKE '%vcard%' OR [Key] LIKE '%org%' OR [Key] LIKE '%vcard%'");

			SendProgress("*** Done ***");
			#endregion
		}