Esempio n. 1
0
        private DBTransaction _transaction; // commit, dispose

        #endregion Fields

        #region Constructors

        public MetadataContext(DBHelper dbHelper)
        {
            _previousContext = DataContext.Current;

            _transaction = dbHelper.BeginTransaction();

            _currentContext = new DataContext(string.Empty);
            _currentContext.SqlContext.CommandTimeout = dbHelper.CommandTimeout;
            _currentContext.SqlContext.Transaction = _transaction.SqlTran;

            DataContext.Current = _currentContext;
        }
Esempio n. 2
0
		private void CopyTable(string sourceTableName, string targetTableName, NameValueCollection columnsMapping, string selPrefix, string selColumns, string selCondition, bool copyBinary, DBHelper source, DBHelper target, IList<StringCollection> nameLists, IList<Hashtable> valueHashTables, bool insertIdentity, Hashtable identities)
		{
			SendProgress("Copying data from table {0} to table {1}", sourceTableName, targetTableName);

			StringBuilder sb = new StringBuilder();
			StringBuilder sb2 = new StringBuilder();
			SqlCommand cmd = new SqlCommand();

			cmd.CommandType = CommandType.Text;

			DataTable dt;
			Type dataType;
			bool isIdentity, hasIdentity = false;
			string selectCommand;
			string insertCommand;

			ArrayList columnTypes = new ArrayList();
			ArrayList sourceColumns = new ArrayList();
			ArrayList targetColumns = new ArrayList();
			ArrayList sourceBinColumns = new ArrayList();
			ArrayList targetBinColumns = new ArrayList();
			Hashtable binIdentities = new Hashtable();
			string sourceIdentityColumn = null, targetIdentityColumn = null;
			int identityIndex = -1;
			string sourceColumnName, targetColumnName;

			// Get column names to be inserted
			selectCommand = string.Format(CultureInfo.InvariantCulture, "SELECT {0}{1} FROM [{2}] {3}", selPrefix, selColumns, sourceTableName, selCondition);
			using (IDataReader reader = source.RunTextDataReaderSchemaOnly(selectCommand))
			{
				dt = reader.GetSchemaTable();
				foreach (DataRow row in dt.Rows)
				{
					sourceColumnName = (string)row["ColumnName"];
					targetColumnName = GetTargetColumn(sourceColumnName, columnsMapping);
					dataType = (Type)row["DataType"];

					// Check if column exists and is identity
					if (CheckColumn(target, cmd, targetTableName, targetColumnName, out isIdentity))
					{
						if (isIdentity)
						{
							hasIdentity = true;
							sourceIdentityColumn = sourceColumnName;
							targetIdentityColumn = targetColumnName;
						}

						if (dataType == typeof(byte[]))
						{
							sourceBinColumns.Add(sourceColumnName);
							targetBinColumns.Add(targetColumnName);
						}
						else
						{
							columnTypes.Add(dataType);
							sourceColumns.Add(sourceColumnName);
							targetColumns.Add(targetColumnName);
						}
					}
				}
			}

			// Build select command
			sb.Append("SELECT ");
			int n = 0;
			foreach (string colName in sourceColumns)
			{
				if (n > 0)
					sb.Append(", ");
				sb.Append(selPrefix);
				sb.Append("[");
				sb.Append(colName);
				sb.Append("]");
				n++;
			}
			sb.Append(" FROM [");
			sb.Append(sourceTableName);
			sb.Append("] ");
			sb.Append(selCondition);

			// Build insert command
			sb2.Append("INSERT INTO [");
			sb2.Append(targetTableName);
			sb2.Append("] (");
			int j = n = 0;
			foreach (string colName in targetColumns)
			{
				if (colName == targetIdentityColumn)
					identityIndex = j;
				if (insertIdentity || identityIndex != j)
				{
					if (n > 0)
						sb2.Append(", ");
					sb2.Append("[");
					sb2.Append(colName);
					sb2.Append("]");
					n++;
				}
				j++;
			}
			sb2.Append(") VALUES (");
			n = 0;
			for (int i = 0; i < targetColumns.Count; i++)
			{
				if (insertIdentity || identityIndex != i)
				{
					if (n > 0)
						sb2.Append(", ");
					sb2.Append("@p");
					sb2.Append(i);
					n++;
				}
			}
			sb2.Append(")");

			if (hasIdentity && !insertIdentity)
				sb2.Append(" SELECT @@IDENTITY");

			selectCommand = sb.ToString();
			insertCommand = sb2.ToString();

			// Read data from source and insert into target
			using (DBTransaction tran = target.BeginTransaction())
			{
				object identity;
				using (IDataReader reader = source.RunTextDataReader(selectCommand))
				{
					dt = reader.GetSchemaTable();
					if (insertIdentity && hasIdentity)
						SetInsertIdentity(target, targetTableName, true);

					try
					{
						cmd.CommandText = insertCommand;

						while (reader.Read())
						{
							if (cmd.Parameters.Count == 0)
							{
								// Create parameters
								for (int i = 0; i < targetColumns.Count; i++)
								{
									SqlParameter p = cmd.Parameters.AddWithValue(string.Format(CultureInfo.InvariantCulture, "@p{0}", i), GetColumnValue((string)sourceColumns[i], reader[i], nameLists, valueHashTables));
									if (columnTypes[i] == typeof(Decimal))
										p.DbType = DbType.Decimal;
								}
							}
							else
							{
								// Set values
								for (int i = 0; i < targetColumns.Count; i++)
								{
									cmd.Parameters[i].Value = GetColumnValue((string)sourceColumns[i], reader[i], nameLists, valueHashTables);
								}
							}
							identity = target.RunCmdScalar(cmd);
							if (hasIdentity)
							{
								object oldIdentity = reader[identityIndex];
								if (insertIdentity)
									binIdentities[oldIdentity] = oldIdentity;
								else
									binIdentities[oldIdentity] = identity;
								if (!insertIdentity && identities != null)
									identities[oldIdentity] = identity;
							}
						}
					}
					finally
					{
						if (insertIdentity && hasIdentity)
							SetInsertIdentity(target, targetTableName, false);
					}
				}
				tran.Commit();
			}

			// Copy binary and image fields
			if (copyBinary)
			{
				if (sourceIdentityColumn != null && sourceBinColumns.Count > 0)
				{
					SqlParameter paramTextPtr = DBHelper.MP("@ptr", SqlDbType.VarBinary, 16, null);

					SqlParameter paramData = new SqlParameter("@data", SqlDbType.VarBinary);
					paramData.Value = _buffer;

					SqlParameter paramId = new SqlParameter();
					paramId.ParameterName = "@id";

					foreach (object id in binIdentities.Keys)
					{
						paramId.Value = binIdentities[id];

						for (int i = 0; i < sourceBinColumns.Count; i++)
						{
							CopyBinaryData(source, sourceTableName, (string)sourceBinColumns[i], sourceIdentityColumn, id,
								target, targetTableName, (string)targetBinColumns[i], targetIdentityColumn,
								cmd, paramTextPtr, paramData, paramId);
						}
					}
				}
			}
			SendProgress("Done");
		}
Esempio n. 3
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
		}
Esempio n. 4
0
		private void ValidateDatabaseVersion(DBHelper dbHelper, Version requiredVersion, bool isSource)
		{
			using (DBTransaction tran = dbHelper.BeginTransaction())
			{
				Version currentVersion = new Version();

				using (IDataReader reader = dbHelper.RunTextDataReader("SELECT [Major],[Minor],[Build] FROM [DatabaseVersion]"))
				{
					if (reader.Read())
					{
						int major = (int)reader["Major"];
						int minor = (int)reader["Minor"];
						int build = (int)reader["Build"];

						currentVersion = new Version(major, minor, build);
					}
				}

				if (currentVersion != requiredVersion)
				{
					string databaseType;
					string advise;

					if (isSource)
					{
						databaseType = "Source";
						if (currentVersion < requiredVersion)
							advise = "Update IBN 4.5 to the required version.";
						else
							advise = "Update IBN 4.7 to the latest version or wait for the next update if you already have the latest version.";
					}
					else
					{
						databaseType = "Target";
						advise = "Select different database.";
					}

					throw new IbnConverterException(string.Format("{0} database {1}.{2} has unsupported version {3}. Required version is {4}. {5}"
						, databaseType, tran.SqlTran.Connection.DataSource, tran.SqlTran.Connection.Database, currentVersion, requiredVersion, advise)
						);
				}
			}
		}
Esempio n. 5
0
        private static void WriteTables(XmlNodeList dictionaries, DBHelper target, int langId, int defaultLangId, string defaultLocale, bool addAllLanguages, Hashtable languages, NameValueCollection replace)
        {
            string name, lang, colName;
            XmlAttribute a;
            StringBuilder builder = new StringBuilder();
            bool isIdentity, hasIdentity;
            ArrayList columns = new ArrayList();
            Type type;
            Hashtable colTypes = new Hashtable();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            foreach (XmlNode dict in dictionaries)
            {
                builder.Length = 0;
                columns.Clear();
                colTypes.Clear();
                hasIdentity = false;

                name = dict.Attributes["name"].Value;

                //Console.WriteLine("Writing table: {0}", name);

                a = dict.Attributes["lang"];
                lang = (a != null) ? a.Value : null;

                if (langId == defaultLangId || lang != "single")
                {
                    foreach (XmlNode item in dict.SelectNodes("item"))
                    {
                        if (name == "LANGUAGES")
                        {
                            languages[item.Attributes["Locale"].Value] = int.Parse(item.Attributes["LanguageId"].Value, CultureInfo.InvariantCulture);
                            if (!addAllLanguages && item.Attributes["Locale"].Value != defaultLocale)
                                continue;
                        }

                        builder.Append(string.Format(CultureInfo.InvariantCulture, "\r\nINSERT [{0}] (", name));
                        int n = 0;
                        if (lang == "multi")
                        {
                            builder.Append("[LanguageId]");
                            n++;
                        }
                        foreach (XmlAttribute attr in item.Attributes)
                        {
                            colName = attr.Name;
                            if (!columns.Contains(colName))
                            {
                                columns.Add(colName);
                                if (CheckColumn(target, cmd, name, colName, out isIdentity))
                                {
                                    if (isIdentity)
                                        hasIdentity = true;
                                }
                            }
                            if (n > 0)
                                builder.Append(", ");
                            builder.Append("[");
                            builder.Append(colName);
                            builder.Append("]");

                            n++;
                        }
                        if (name == "LANGUAGES")
                        {
                            builder.Append(", [IsDefault]");
                            n++;
                        }

                        builder.Append(") VALUES(");
                        n = 0;
                        if (lang == "multi")
                        {
                            builder.Append(langId.ToString(CultureInfo.InvariantCulture));
                            n++;
                        }
                        foreach (XmlAttribute attr in item.Attributes)
                        {
                            colName = attr.Name;
                            if (n > 0)
                                builder.Append(", ");

                            string val = attr.Value;
                            if (replace != null)
                            {
                                foreach (string key in replace.Keys)
                                    val = val.Replace(key, replace[key]);
                            }

                            if (val == "[=NULL=]")
                                builder.Append("NULL");
                            else
                            {
                                type = (Type)colTypes[colName];
                                if (type == null)
                                {
                                    type = GetColumnType(target, cmd, name, colName);
                                    colTypes[colName] = type;
                                }

                                if (type == typeof(string))
                                {
                                    builder.Append("N'");
                                    builder.Append(val.Replace("'", "''"));
                                    builder.Append("'");
                                }
                                else if (type == typeof(Guid))
                                {
                                    builder.Append("'");
                                    builder.Append(val);
                                    builder.Append("'");
                                }
                                else
                                    builder.Append(val);
                            }
                            n++;
                        }
                        if (name == "LANGUAGES")
                        {
                            builder.Append(", ");
                            builder.Append(item.Attributes["Locale"].Value == defaultLocale ? "1" : "0");
                            n++;
                        }
                        builder.Append(")");
                    }

                    using (DBTransaction tran = target.BeginTransaction())
                    {
                        if (hasIdentity)
                        {
                            cmd.CommandText = string.Format(CultureInfo.InvariantCulture, "SET IDENTITY_INSERT [{0}] ON", name);
                            target.RunCmd(cmd);
                        }
                        try
                        {
                            cmd.CommandText = builder.ToString();
                            target.RunCmd(cmd);
                        }
                        finally
                        {
                            if (hasIdentity)
                            {
                                cmd.CommandText = string.Format(CultureInfo.InvariantCulture, "SET IDENTITY_INSERT [{0}] OFF", name);
                                target.RunCmd(cmd);
                            }
                        }

                        tran.Commit();
                    }
                }
            }
        }