public SchemaObjectCollection LoadCurrentUsers(string ownerID) { ownerID.CheckStringIsNullOrEmpty("ownerID"); var timePointBuilder = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(DateTime.MinValue); WhereSqlClauseBuilder whereBuilder = new WhereSqlClauseBuilder(); whereBuilder.AppendItem("C.OwnerID", ownerID); timePointBuilder.Add(whereBuilder); string sql = string.Format( "SELECT SC.* FROM {0} SC INNER JOIN SC.ConditionCalculateResult C ON SC.ID = C.UserID WHERE {1}", ORMapping.GetMappingInfo(typeof(SchemaObjectBase)).TableName, timePointBuilder.ToSqlString(TSqlBuilder.Instance)); SchemaObjectCollection result = new SchemaObjectCollection(); using (DbContext context = DbContext.GetContext(this.GetConnectionName())) { result.LoadFromDataView(DbHelper.RunSqlReturnDS(sql, this.GetConnectionName()).Tables[0].DefaultView); } return result; }
protected void AddScopesClick(object sender, EventArgs e) { var keys = this.postData.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (keys.Length > 0) { try { var unit = DbUtil.GetEffectiveObject <AU.AdminUnit>(this.AdminUnitObject.ID); var scope = unit.GetNormalScopes().GetScope(this.CurrentScopeType); if (scope == null) { throw new ObjectNotFoundException("指定的管理范围已不存在。"); } SchemaObjectCollection objs = DbUtil.GetEffectiveObjects(keys); foreach (AU.AUAdminScopeItem item in objs) { AU.Operations.Facade.InstanceWithPermissions.AddObjectToScope(item, scope); } } catch (Exception ex) { WebUtility.ShowClientError(ex); } this.InnerRefreshList(); } }
// TODO: make database migration a separate task that is explicitly invoked on production public static void UpgradeSchema(string connectionString) { // Needs admin permission on database if the database does not yet exist - does nothing if it does SchemaInstaller.CreateDatabase(connectionString); // Do upgrade in the background for faster startup during development // (new Thread(() => { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // make sure our database exists SchemaInstaller installer = new SchemaInstaller(connection); new SchemaEventConsoleLogger().Attach(installer); // load the schema from the embedded resources in this project SchemaObjectCollection schema = new SchemaObjectCollection(); schema.Load(Assembly.GetExecutingAssembly()); // install the schema installer.Install("test", schema); } } // )).Start(); }
/// <summary> /// 根据XPath查询SchemaObject /// </summary> /// <param name="xPath">符合条件的xPath语句</param> /// <param name="schemaTypes">SchemaType。如果为空数组,则查询所有类型的对象</param> /// <param name="includingDeleted">为true时,包含已删除的对象。</param> /// <param name="timePoint"></param> /// <returns></returns> public SchemaObjectCollection LoadByXPath(string xPath, string[] schemaTypes, bool includingDeleted, DateTime timePoint) { schemaTypes.NullCheck("schemaTypes"); SchemaObjectCollection result = new SchemaObjectCollection(); if (xPath.IsNotEmpty()) { InSqlClauseBuilder inBuilder = new InSqlClauseBuilder("SchemaType"); inBuilder.AppendItem(schemaTypes); WhereSqlClauseBuilder pathBuilder = new WhereSqlClauseBuilder(); pathBuilder.AppendItem("Data", xPath, string.Empty, "Data.exist(${Data}$) > 0"); if (includingDeleted == false) { pathBuilder.AppendItem("Status", (int)SchemaObjectStatus.Normal); } ConnectiveSqlClauseCollection builder = new ConnectiveSqlClauseCollection(inBuilder, pathBuilder); result = Load(builder, timePoint); } else { result = new SchemaObjectCollection(); } return(result); }
/// <summary> /// 执行导入操作 /// </summary> /// <param name="objectSet">所有数据</param> /// <param name="context">导入的执行上下文</param> public override void DoImport(SCObjectSet objectSet, IImportContext context) { var exec = PC.Executors.SCObjectOperations.InstanceWithPermissions; SchemaObjectCollection parentObjects = null; // 预先查出父级组织 if (this.IncludeSelf && objectSet.HasObjects && objectSet.HasRelations) { parentObjects = this.GetParentObjects(objectSet.Relations); } SchemaObjectCollection memberObjects = null; // 预先查出成员 if (this.IncludeMembers && objectSet.HasMembership) { memberObjects = this.GetMemberObjects(objectSet.Membership); } int allCount = objectSet.Objects.Count; int count = 0; foreach (var grp in objectSet.Objects) { count++; ImportOneGroup(objectSet, context, exec, parentObjects, memberObjects, allCount, count, grp); } }
/// <summary> /// 合并用户信息,一个事物内更新所有的 /// </summary> /// <param name="users"></param> public void BatchMerge(string containerID, string containerSchemaType, SchemaObjectCollection users) { containerID.CheckStringIsNullOrEmpty("containerID"); containerSchemaType.CheckStringIsNullOrEmpty("containerSchemaType"); users.NullCheck("users"); SameContainerUserAndContainerSnapshotCollection existedData = this.LoadByContainerID(containerID); SameContainerUserAndContainerSnapshotCollection insertData = GetInsertData(containerID, containerSchemaType, existedData, users); SameContainerUserAndContainerSnapshotCollection updateData = GetUpdateData(containerID, containerSchemaType, existedData, users); string sqlInsert = this.PrepareUpdateSql(insertData); string sqlUpdate = this.PrepareUpdateSql(updateData); using (TransactionScope scope = TransactionScopeFactory.Create()) { DateTime dtInsert = (DateTime)DbHelper.RunSqlReturnScalar(sqlInsert, this.GetConnectionName()); SCActionContext.Current.TimePoint.IsMinValue(() => SCActionContext.Current.TimePoint = dtInsert); DateTime dtUpdate = (DateTime)DbHelper.RunSqlReturnScalar(sqlUpdate, this.GetConnectionName()); SCActionContext.Current.TimePoint.IsMinValue(() => SCActionContext.Current.TimePoint = dtUpdate); scope.Complete(); } }
static void Main(string[] args) { SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder("Database=.;Initial Catalog=InsightTest;Integrated Security=true"); SchemaInstaller.CreateDatabase(connectionString.ConnectionString); using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString)) { connection.Open(); // make sure our database exists SchemaInstaller installer = new SchemaInstaller(connection); new SchemaEventConsoleLogger().Attach(installer); // load the schema from the embedded resources in this project SchemaObjectCollection schema = new SchemaObjectCollection(); schema.Load(Assembly.GetExecutingAssembly()); // install the schema Console.WriteLine("Installing"); installer.Install("BeerGarten", schema); // uninstall the schema if (args.Length > 0 && args[0].ToUpperInvariant() == "UNINSTALL") { Console.WriteLine("Uninstalling"); installer.Uninstall("BeerGarten"); } } }
public void SCQueryPermissionsByUserIDsSnapshotTest() { SCApplication application = SCObjectGenerator.PrepareApplicationObject(); SCObjectOperations.Instance.AddApplication(application); SCRole role = SCObjectGenerator.PrepareRoleObject(); SCObjectOperations.Instance.AddRole(role, application); SCPermission permission = SCObjectGenerator.PreparePermissionObject(); SCObjectOperations.Instance.AddPermission(permission, application); SCRelationObject relation = SCObjectOperations.Instance.JoinRoleAndPermission(role, permission); SCUser user1 = SCObjectGenerator.PrepareUserObject("RU1", "User1", "RoleUser1"); SCObjectOperations.Instance.AddUser(user1, SCOrganization.GetRoot()); SCObjectOperations.Instance.AddMemberToRole(user1, role); SchemaObjectCollection result = SCSnapshotAdapter.Instance.QueryPermissionsByUserIDs(new string[] { user1.ID }, false, DateTime.MinValue); Assert.IsTrue(result.Count > 0); Console.WriteLine(result[0].Properties.GetValue("Name", string.Empty)); Assert.AreEqual(permission.ID, result[0].ID); }
public SchemaObjectCollection QueryApplications(string[] schemaTypes, bool includingDeleted, DateTime timePoint) { SchemaObjectCollection result = new SchemaObjectCollection(); ConnectiveSqlClauseCollection timeConditionC = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(timePoint, "SC."); InSqlClauseBuilder schemaBuilder = new InSqlClauseBuilder("SC.SchemaType"); schemaBuilder.AppendItem(schemaTypes); WhereSqlClauseBuilder builderC = new WhereSqlClauseBuilder(); if (includingDeleted == false) { builderC.AppendItem("SC.Status", (int)SchemaObjectStatus.Normal); } ConnectiveSqlClauseCollection connectiveBuilder = new ConnectiveSqlClauseCollection(schemaBuilder, builderC, timeConditionC); string sql = string.Format("SELECT SC.*" + "\nFROM SC.SchemaObject SC" + "\nWHERE {0}", connectiveBuilder.ToSqlString(TSqlBuilder.Instance)); DataTable table = DbHelper.RunSqlReturnDS(sql, this.GetConnectionName()).Tables[0]; result.LoadFromDataView(table.DefaultView); return(result); }
/// <summary> /// 生成所有的用户容器下的用户信息快照 /// </summary> public void GenerateAllItemAndContainerSnapshot() { ProcessProgress.Current.MinStep = 0; ProcessProgress.Current.MaxStep = 100; ProcessProgress.Current.CurrentStep = 0; ProcessProgress.Current.StatusText = string.Format("正在加载所有管理范围"); ProcessProgress.Current.Response(); Stopwatch sw = new Stopwatch(); sw.Start(); try { AUCommon.DoDbAction(() => { SchemaObjectCollection containers = AUCommon.DoDbProcess <SchemaObjectCollection>(() => PC.Adapters.SchemaObjectAdapter.Instance.LoadBySchemaType(new string[] { AUCommon.SchemaAUAdminScope }, DateTime.MinValue)); containers.Sort((c1, c2) => string.Compare(c1.SchemaType, c2.SchemaType, true)); ProcessProgress.Current.StatusText = string.Format("加载所有管理范围完成,总共{0}个对象", containers.Count); ProcessProgress.Current.MaxStep = containers.Count; ProcessProgress.Current.Response(); containers.ForEach(c => this.GenerateOneItemAndContainerSnapshot((IAdminScopeItemContainer)c)); }); } finally { sw.Stop(); } ProcessProgress.Current.StatusText = string.Format("计算人员完成,耗时{0:#,##0.00}秒", sw.Elapsed.TotalSeconds); ProcessProgress.Current.Response(); }
/// <summary> /// 根据代码名称,<see cref="IConnectiveSqlClause"/>指定的条件和时间点载入对象 /// </summary> /// <param name="conditionAction">要在构造条件时执行的操作</param> /// <param name="timePoint">时间点</param> /// <param name="codeNames">代码名称</param> /// <returns>一个<see cref="SchemaObjectCollection"/>,包含条件指定的对象。</returns> public SchemaObjectCollection LoadByCodeName(Action <ConnectiveSqlClauseCollection> conditionAction, DateTime timePoint, params string[] codeNames) { var timeCondition = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(timePoint, "O."); var timeCondition2 = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(timePoint, "S."); InSqlClauseBuilder inBuilder = new InSqlClauseBuilder("S.CodeName"); inBuilder.AppendItem(codeNames); SchemaObjectCollection result = null; if (inBuilder.IsEmpty == false) { var conditions = new ConnectiveSqlClauseCollection(inBuilder, timeCondition, timeCondition2); if (conditionAction != null) { conditionAction(conditions); } result = this.LoadByCodeNameInner(conditions); } else { result = new SchemaObjectCollection(); } return(result); }
/// <summary> /// 按照Builder查询应用所包含的元素(角色和权限) /// </summary> /// <param name="builder"></param> /// <param name="includingDeleted"></param> /// <param name="timePoint"></param> /// <returns></returns> public SchemaObjectCollection QueryApplicationObjectsByBuilder(IConnectiveSqlClause builder, bool includingDeleted, DateTime timePoint) { builder.NullCheck("builder"); SchemaObjectCollection result = new SchemaObjectCollection(); if (builder.IsEmpty == false) { IConnectiveSqlClause extraBuilder = CreateStatusAndTimePointBuilder(includingDeleted, timePoint, "SC.", "A.", "M."); ConnectiveSqlClauseCollection connectiveBuilder = new ConnectiveSqlClauseCollection(builder, extraBuilder); string resourcePath = "QueryApplicationObjects_Current.sql"; if (timePoint != DateTime.MinValue && includingDeleted == true) { resourcePath = "QueryApplicationObjects.sql"; } string sqlTemplate = ResourceHelper.LoadStringFromResource(Assembly.GetExecutingAssembly(), string.Concat("MCS.Library.SOA.DataObjects.Security.Adapters.Templates.", resourcePath)); string sql = string.Format(sqlTemplate, connectiveBuilder.ToSqlString(TSqlBuilder.Instance)); DataTable table = DbHelper.RunSqlReturnDS(sql, this.GetConnectionName()).Tables[0]; result.LoadFromDataView(table.DefaultView); } return(result); }
internal static T GetUniqueNormalObject <T>(this SchemaObjectCollection obj) where T : SchemaObjectBase { if (obj == null) { throw new ArgumentNullException("obj"); } T result = null; foreach (var item in obj) { if (item.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal && item is T) { if (result == null) { result = (T)item; } else { throw new DuplicateObjectException(); } } } return(result); }
/// <summary> /// 根据AppCodeName和Permission的CodeName查询出对应的角色 /// </summary> /// <param name="schemaTypes"></param> /// <param name="appCodeName"></param> /// <param name="permissionCodeNames"></param> /// <param name="includingDeleted"></param> /// <param name="timePoint"></param> /// <returns></returns> public SchemaObjectCollection QueryPermissionRolesByCodeName(string[] schemaTypes, string appCodeName, string[] permissionCodeNames, bool includingDeleted, DateTime timePoint) { SchemaObjectCollection result = null; if (appCodeName.IsNotEmpty() && permissionCodeNames != null && permissionCodeNames.Length > 0) { InSqlClauseBuilder schemaTypeBuilder = new InSqlClauseBuilder("M.MemberSchemaType"); schemaTypeBuilder.AppendItem(schemaTypes); WhereSqlClauseBuilder codeBuilder = new WhereSqlClauseBuilder(); codeBuilder.AppendItem("A.CodeName", appCodeName); InSqlClauseBuilder permissionCodeTypeBuilder = new InSqlClauseBuilder("P.CodeName"); permissionCodeTypeBuilder.AppendItem(permissionCodeNames); result = QueryPermissionRolesByBuilder(new ConnectiveSqlClauseCollection(schemaTypeBuilder, codeBuilder, permissionCodeTypeBuilder), includingDeleted, timePoint); } else { result = new SchemaObjectCollection(); } return(result); }
private void PrepareScopeItems(AUObjectOperationContext context, AUSchema originalSchema, AUSchema targetSchema) { var srcArray = originalSchema != null?originalSchema.Scopes.Split(AUCommon.Spliter, StringSplitOptions.RemoveEmptyEntries) : AUCommon.ZeroLengthStringArray; var targetArray = targetSchema.Scopes.Split(AUCommon.Spliter, StringSplitOptions.RemoveEmptyEntries); Array.Sort(srcArray); Array.Sort(targetArray); var toBeAddedScopes = GetToBeAddedScopes(srcArray, targetArray); var toBeDeletedScopes = GetToBeRemovedScopes(srcArray, targetArray); //角色不在此修改 this.allCurrentAUs = Adapters.AUSnapshotAdapter.Instance.LoadAUBySchemaID(targetSchema.ID, true, DateTime.MinValue); if (allCurrentAUs.Any() && this.Data.Status == SchemaObjectStatus.Deleted) { throw new InvalidOperationException("必须先删除所有与此管理架构相关的管理单元才可以进行Schema删除。"); } if (toBeAddedScopes.Length > 0 || toBeDeletedScopes.Length > 0) { if (this.Data.Status == SchemaObjectStatus.Deleted) { throw new InvalidOperationException("进行删除操作时,不应修改管理范围。"); } PrepareToBeAddedScopes(toBeAddedScopes, pendingActions); PrepareToBeDeletedScopes(toBeDeletedScopes, pendingActions); } }
protected override bool DoExecute(SchemaObjectCollection srcObjects, SchemaObjectCollection targetObjects) { bool result = base.DoExecute(srcObjects, targetObjects); this.ReportProgress("操作结束", true); return(result); }
/// <summary> /// 加载指定的成员 /// </summary> /// <param name="containerSchemaType"></param> /// <param name="containerID"></param> /// <param name="status"></param> /// <param name="timePoint"></param> /// <returns></returns> public SchemaObjectCollection LoadMembers(string containerSchemaType, string containerID, SchemaObjectStatus status, DateTime timePoint) { containerSchemaType.CheckStringIsNullOrEmpty("schemaType"); containerID.CheckStringIsNullOrEmpty("containerID"); WhereSqlClauseBuilder condition = new WhereSqlClauseBuilder(); condition.AppendItem("O.Status", (int)status); condition.AppendItem("M.ContainerSchemaType", containerSchemaType).AppendItem("M.Status", (int)status); condition.AppendItem("M.ContainerID", containerID); var timeCondition = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(timePoint, "O."); var timeCondition2 = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(timePoint, "M."); ConnectiveSqlClauseCollection conditions = new ConnectiveSqlClauseCollection(condition, timeCondition, timeCondition2); string sql = string.Format("SELECT O.* FROM SC.SchemaObject O INNER JOIN SC.SchemaMembers M ON O.ID = M.MemberID WHERE {0}", conditions.ToSqlString(TSqlBuilder.Instance)); DataTable table = DbHelper.RunSqlReturnDS(sql, this.GetConnectionName()).Tables[0]; SchemaObjectCollection result = new SchemaObjectCollection(); result.LoadFromDataView(table.DefaultView); return(result); }
/// <summary> /// 按照Builder查询应用所包含的元素(角色和权限) /// </summary> /// <param name="builder"></param> /// <param name="includingDeleted"></param> /// <param name="timePoint"></param> /// <returns></returns> public SchemaObjectCollection QueryApplicationObjectsByBuilder(IConnectiveSqlClause builder, bool includingDeleted, DateTime timePoint) { builder.NullCheck("builder"); SchemaObjectCollection result = new SchemaObjectCollection(); if (builder.IsEmpty == false) { IConnectiveSqlClause extraBuilder = CreateStatusAndTimePointBuilder(includingDeleted, timePoint, "SC.", "A.", "M."); ConnectiveSqlClauseCollection connectiveBuilder = new ConnectiveSqlClauseCollection(builder, extraBuilder); string resourcePath = "QueryApplicationObjects_Current.sql"; if (timePoint != DateTime.MinValue && includingDeleted == true) resourcePath = "QueryApplicationObjects.sql"; string sqlTemplate = ResourceHelper.LoadStringFromResource(Assembly.GetExecutingAssembly(), string.Concat("MCS.Library.SOA.DataObjects.Security.Adapters.Templates.", resourcePath)); string sql = string.Format(sqlTemplate, connectiveBuilder.ToSqlString(TSqlBuilder.Instance)); DataTable table = DbHelper.RunSqlReturnDS(sql, this.GetConnectionName()).Tables[0]; result.LoadFromDataView(table.DefaultView); } return result; }
/// <summary> /// Launch the insight schema setup. /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.WriteLine("Beginning to setup the database."); var connectionString = ConfigurationManager.ConnectionStrings["CodeWithMe"].ConnectionString; // Will actually create the database if it doesn't exist! SchemaInstaller.CreateDatabase(connectionString); // Invoke the schema installer to do magic. using (var db = new SqlConnection(connectionString)) { db.Open(); // create the installer to apply changes SchemaInstaller installer = new SchemaInstaller(db); new SchemaEventConsoleLogger().Attach(installer); // get the SQL from the embedded resources SchemaObjectCollection schema = new SchemaObjectCollection(Assembly.GetExecutingAssembly()); schema.StripPrintStatements = true; // install the schema // (This allows us to have multiple schemas in a single database. Pretty cool). installer.Install("CodeWithMe", schema); } Console.WriteLine(); Console.WriteLine("Done!"); }
public SchemaObjectCollection QueryApplications(string[] schemaTypes, bool includingDeleted, DateTime timePoint) { SchemaObjectCollection result = new SchemaObjectCollection(); ConnectiveSqlClauseCollection timeConditionC = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(timePoint, "SC."); InSqlClauseBuilder schemaBuilder = new InSqlClauseBuilder("SC.SchemaType"); schemaBuilder.AppendItem(schemaTypes); WhereSqlClauseBuilder builderC = new WhereSqlClauseBuilder(); if (includingDeleted == false) builderC.AppendItem("SC.Status", (int)SchemaObjectStatus.Normal); ConnectiveSqlClauseCollection connectiveBuilder = new ConnectiveSqlClauseCollection(schemaBuilder, builderC, timeConditionC); string sql = string.Format("SELECT SC.*" + "\nFROM SC.SchemaObject SC" + "\nWHERE {0}", connectiveBuilder.ToSqlString(TSqlBuilder.Instance)); DataTable table = DbHelper.RunSqlReturnDS(sql, this.GetConnectionName()).Tables[0]; result.LoadFromDataView(table.DefaultView); return result; }
public DataSet GetUserRoles2(string userValue, string appCodeName, UserValueType userValueType, RightMaskType rightMask, DelegationMaskType delegationMask, bool includeMatrixUsers) { string[] schemaTypes = SchemaInfo.FilterByCategory("Roles").ToSchemaNames(); string[] userIDs = OGUReaderService.SplitObjectValues(userValue); SCObjectAndRelationCollection users = OGUReaderService.GetSearchAdapter(GetSearchOUIDType(userValueType), SchemaInfo.FilterByCategory("Users").ToSchemaNames(), userIDs, false).QueryObjectsAndRelations(); SchemaObjectCollection roles = SCSnapshotAdapter.Instance.QueryUserBelongToRoles(schemaTypes, appCodeName, users.ToIDArray(), false, DateTime.MinValue); if (includeMatrixUsers) { List <string> matachedRoleIDs = GetUserRoleIDsInMatrix(users.ToIDArray(), appCodeName); //过滤掉已经在之前查询过的角色 matachedRoleIDs = matachedRoleIDs.FindAll(rID => roles.ContainsKey(rID) == false); if (matachedRoleIDs.Count > 0) { InSqlClauseBuilder matrixRoleBuilder = new InSqlClauseBuilder("ID"); matrixRoleBuilder.AppendItem(matachedRoleIDs.ToArray()); SchemaObjectCollection rolesInMatrix = SchemaObjectAdapter.Instance.Load(matrixRoleBuilder, DateTime.MinValue); rolesInMatrix.ForEach(rMatrix => roles.AddNotExistsItem(rMatrix, (r) => string.Compare(r.ID, rMatrix.ID, true) == 0)); } } DataSet ds = new DataSet(); ds.Tables.Add(QueryHelper.GetAppObjectTableBuilder(schemaTypes).Convert(roles)); return(ds); }
/// <summary> /// 获取唯一的正常状态的对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="result"></param> /// <returns></returns> internal static bool GetUniqueNormalObject <T>(this SchemaObjectCollection obj, out T result) where T : SchemaObjectBase { if (obj == null) { throw new ArgumentNullException("obj"); } bool isOk = true; result = null; foreach (var item in obj) { if (item.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal && item is T) { if (result == null) { result = (T)item; } else { isOk = false; result = null; break; } } } return(isOk); }
public SchemaObjectCollection LoadCurrentObjects <T>(string ownerID) where T : SchemaObjectBase { ownerID.CheckStringIsNullOrEmpty("ownerID"); var timePointBuilder = VersionStrategyQuerySqlBuilder.Instance.TimePointToBuilder(DateTime.MinValue); WhereSqlClauseBuilder whereBuilder = new WhereSqlClauseBuilder(); whereBuilder.AppendItem("C.OwnerID", ownerID); timePointBuilder.Add(whereBuilder); string sql = string.Format( "SELECT SC.* FROM {0} SC INNER JOIN SC.ConditionCalculateResults C ON SC.ID = C.ObjectID WHERE {1}", ORMapping.GetMappingInfo(typeof(T)).TableName, timePointBuilder.ToSqlString(TSqlBuilder.Instance)); SchemaObjectCollection result = new SchemaObjectCollection(); using (DbContext context = DbContext.GetContext(this.GetConnectionName())) { result.LoadFromDataView(DbHelper.RunSPReturnDS(sql, this.GetConnectionName()).Tables[0].DefaultView); } return(result); }
protected override void PrepareData(AUObjectOperationContext context) { AUCommon.DoDbAction(() => { this.schema = (AUSchema)SchemaObjectAdapter.Instance.Load(((AdminUnit)Data).AUSchemaID); if (this.schema == null || this.schema.Status != SchemaObjectStatus.Normal) { throw new AUObjectValidationException(AUCommon.DisplayNameFor((AdminUnit)this.Data) + "管理单元的SchemaID无效,无法找到对应的Schema。"); } }); this.PrepareRelationObject(); base.PrepareData(context); var oldObject = (AdminUnit)SCActionContext.Current.OriginalObject; if (oldObject != null && oldObject.AUSchemaID != this.schema.ID) { throw new AUObjectValidationException("一旦创建,不能以任何方式修改AdminUnit的AUSchema属性"); } this.existingSchemaRoles = Adapters.AUSnapshotAdapter.Instance.LoadAUSchemaRoles(schema.ID, false, DateTime.MinValue); this.existingUnitRoles = Adapters.AUSnapshotAdapter.Instance.LoadAURoles(new string[] { this.Data.ID }, new string[0], false, DateTime.MinValue); this.existingUnitScopes = Adapters.AUSnapshotAdapter.Instance.LoadAUScope(this.Data.ID, false, DateTime.MinValue); this.pendingActions.Clear(); PrepareRolesAndScopes(); }
/// <summary> /// 合并用户信息,一个事物内更新所有的 /// </summary> /// <param name="users"></param> public void BatchMerge(string containerID, string containerSchemaType, SchemaObjectCollection users) { containerID.CheckStringIsNullOrEmpty("containerID"); containerSchemaType.CheckStringIsNullOrEmpty("containerSchemaType"); users.NullCheck("users"); SameContainerItemAndContainerSnapshotCollection existedData = this.LoadByContainerID(containerID); SameContainerItemAndContainerSnapshotCollection insertData = GetInsertData(containerID, containerSchemaType, existedData, users); SameContainerItemAndContainerSnapshotCollection updateData = GetUpdateData(containerID, containerSchemaType, existedData, users); string sqlInsert = this.PrepareUpdateSql(insertData); string sqlUpdate = this.PrepareUpdateSql(updateData); using (TransactionScope scope = TransactionScopeFactory.Create()) { DateTime dtInsert = (DateTime)DbHelper.RunSqlReturnScalar(sqlInsert, this.GetConnectionName()); SCActionContext.Current.TimePoint.IsMinValue(() => SCActionContext.Current.TimePoint = dtInsert); DateTime dtUpdate = (DateTime)DbHelper.RunSqlReturnScalar(sqlUpdate, this.GetConnectionName()); SCActionContext.Current.TimePoint.IsMinValue(() => SCActionContext.Current.TimePoint = dtUpdate); scope.Complete(); } }
private void AssertScriptCount(int count, string sql) { StringReader reader = new StringReader(sql); SchemaObjectCollection c = new SchemaObjectCollection(); c.Load(reader); Assert.AreEqual(count, c.Count); }
protected override void PrepareData(AUObjectOperationContext context) { base.PrepareData(context); this.pendingActions.Clear(); if (this.Data.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal) { //添加 this.adminUnits = Adapters.AUSnapshotAdapter.Instance.LoadAUBySchemaID(this.Container.ID, true, DateTime.MinValue); foreach (AdminUnit unit in this.adminUnits) { var existedRole = Adapters.AUSnapshotAdapter.Instance.LoadAURole(this.Data.ID, unit.ID, false, DateTime.MinValue); if (existedRole == null) { pendingActions.Add(new AddMemberAction(unit, new AURole() { ID = UuidHelper.NewUuidString(), SchemaRoleID = this.Data.ID })); } else if (existedRole.Status != Schemas.SchemaProperties.SchemaObjectStatus.Normal) { pendingActions.Add(new EnableMemberAction(unit, existedRole)); } } } else { //只是删掉角色 var existedRoles = Adapters.AUSnapshotAdapter.Instance.LoadAURoles(this.Data.ID, true, DateTime.MinValue); foreach (var item in existedRoles) { RelationHelper.Instance.ClearContainer(item); pendingActions.Add(new DeleteSelfAction(item)); } } }
private static void CreateOrModifyDbSchema() { var connStr = ConfigurationManager.ConnectionStrings["ad.util.GeneralPurposeTree"].ConnectionString; if (!SchemaInstaller.DatabaseExists(connStr)) { _logger.Info("ad.util.GeneralPurposeTree is about to create a database."); SchemaInstaller.CreateDatabase(connStr); _logger.Info("ad.util.GeneralPurposeTree has just created a database."); } using (var conn = new SqlConnection(connStr)) { conn.Open(); var installer = new SchemaInstaller(conn); installer.CreatingObject += SchemaInstaller_CreatingObject; installer.CreatedObject += SchemaInstaller_CreatedObject; installer.DroppingObject += SchemaInstaller_DroppingObject; installer.DropFailed += SchemaInstaller_DropFailed; _logger.Info("Database modification starting for database '{0}' and schema '{1}'.", conn.Database, DbSchemaName); var saveCultureInfo = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; try { var schema = new SchemaObjectCollection(); schema.Load(System.Reflection.Assembly.GetExecutingAssembly()); installer.Install(DbSchemaName, schema); } finally { Thread.CurrentThread.CurrentCulture = saveCultureInfo; } _logger.Info("Database modification ended for database '{0}' and schema '{1}'.", conn.Database, DbSchemaName); } }
private static SchemaObjectCollection GetObjects(string[] keys, BatchExecuteCardinality cardinality, IBatchErrorAdapter errors) { SchemaObjectCollection result = null; if ((cardinality & BatchExecuteCardinality.Mandatory) == BatchExecuteCardinality.Mandatory) { // 至少含有一个 if (keys == null || keys.Length == 0) { throw new ArgumentOutOfRangeException("keys", keys, "需要至少一个对象"); } } if ((cardinality & BatchExecuteCardinality.One) == BatchExecuteCardinality.One) { if (keys != null && keys.Length > 1) { throw new ArgumentOutOfRangeException("keys", keys, "只能指定一个对象"); } } if (keys != null && keys.Length > 0) { result = DbUtil.LoadAndCheckObjects("对象", errors, keys); } else { result = new SchemaObjectCollection(); } return(result); }
/// <summary> /// 生成所有的用户容器下的用户信息快照 /// </summary> public void GenerateAllUserAndContainerSnapshot() { ProcessProgress.Current.MinStep = 0; ProcessProgress.Current.MaxStep = 100; ProcessProgress.Current.CurrentStep = 0; ProcessProgress.Current.StatusText = string.Format("正在加载所有群组和角色"); ProcessProgress.Current.Response(); Stopwatch sw = new Stopwatch(); sw.Start(); try { SchemaObjectCollection containers = SchemaObjectAdapter.Instance.LoadBySchemaType(new string[] { "Groups", "Roles" }, DateTime.MinValue); // Groups排在前面 containers.Sort((c1, c2) => string.Compare(c1.SchemaType, c2.SchemaType, true)); ProcessProgress.Current.StatusText = string.Format("加载所有群组和角色完成,总共{0}个对象", containers.Count); ProcessProgress.Current.MaxStep = containers.Count; ProcessProgress.Current.Response(); containers.ForEach(c => this.GenerateOneUserAndContainerSnapshot((ISCUserContainerObject)c)); } finally { sw.Stop(); } ProcessProgress.Current.StatusText = string.Format("计算人员完成,耗时{0:#,##0.00}秒", sw.Elapsed.TotalSeconds); ProcessProgress.Current.Response(); }
private void PrepareScopeItems(AUObjectOperationContext context, AUSchema originalSchema, AUSchema targetSchema) { var srcArray = originalSchema != null ? originalSchema.Scopes.Split(AUCommon.Spliter, StringSplitOptions.RemoveEmptyEntries) : AUCommon.ZeroLengthStringArray; var targetArray = targetSchema.Scopes.Split(AUCommon.Spliter, StringSplitOptions.RemoveEmptyEntries); Array.Sort(srcArray); Array.Sort(targetArray); var toBeAddedScopes = GetToBeAddedScopes(srcArray, targetArray); var toBeDeletedScopes = GetToBeRemovedScopes(srcArray, targetArray); //角色不在此修改 this.allCurrentAUs = Adapters.AUSnapshotAdapter.Instance.LoadAUBySchemaID(targetSchema.ID, true, DateTime.MinValue); if (allCurrentAUs.Any() && this.Data.Status == SchemaObjectStatus.Deleted) throw new InvalidOperationException("必须先删除所有与此管理架构相关的管理单元才可以进行Schema删除。"); if (toBeAddedScopes.Length > 0 || toBeDeletedScopes.Length > 0) { if (this.Data.Status == SchemaObjectStatus.Deleted) throw new InvalidOperationException("进行删除操作时,不应修改管理范围。"); PrepareToBeAddedScopes(toBeAddedScopes, pendingActions); PrepareToBeDeletedScopes(toBeDeletedScopes, pendingActions); } }
private static SchemaObjectCollection GetExistsImportedPermissions(this SCApplication app) { SchemaObjectCollection result = new SchemaObjectCollection(); app.CurrentPermissions.ForEach(p => p.IsImported().TrueAction(() => result.Add(p))); return(result); }
public static SchemaObjectCollection GetExistsImportedRoles(this SCApplication app) { SchemaObjectCollection result = new SchemaObjectCollection(); app.CurrentRoles.ForEach(r => r.IsImported().TrueAction(() => result.Add(r))); return(result); }
protected override void OnIDChanged() { base.OnIDChanged(); this._AllChildrenRelations = null; this._AllChildren = null; this._CurrentlChildren = null; }
/// <summary> /// 得到变化的角色 /// </summary> /// <param name="app"></param> /// <param name="rolesNeedToImported"></param> /// <returns></returns> public static DeltaSchemaObjectCollection GetDeltaRoles(this SCApplication app, IEnumerable <SCRole> rolesNeedToImported) { ProcessProgress.Current.Response("获取需要变化的角色"); SchemaObjectCollection roles = app.GetExistsImportedRoles(); return(GetDeltaObjects(app.GetExistsImportedRoles(), rolesNeedToImported)); }
public SchemaToSimpleEnumerator(SchemaObjectCollection dataItems) { // dataItems.NullCheck<ArgumentNullException>(""); if (dataItems == null) { throw new ArgumentNullException("dataItems"); } this.dataItems = dataItems; }
public void MergeUserInGroupExecutorTest() { // 准备4位用户。User1位状态不变,User2待删除,User3新增加,User4复活 SCGroup group = SCObjectGenerator.PrepareGroupObject(); SCObjectOperations.Instance.AddGroup(group, SCOrganization.GetRoot()); SCUser user1 = SCObjectGenerator.PrepareUserObject(); SCObjectOperations.Instance.AddUser(user1, SCOrganization.GetRoot()); SCMemberRelation mr = SCObjectOperations.Instance.AddUserToGroup(user1, group); Assert.AreEqual(group.SchemaType, mr.ContainerSchemaType); Assert.AreEqual(user1.SchemaType, mr.MemberSchemaType); SCUser user2 = SCObjectGenerator.PrepareUserObject(); SCObjectOperations.Instance.AddUser(user2, SCOrganization.GetRoot()); SCObjectOperations.Instance.AddUserToGroup(user2, group); SCUser user3 = SCObjectGenerator.PrepareUserObject(); SCObjectOperations.Instance.AddUser(user3, SCOrganization.GetRoot()); SCUser user4 = SCObjectGenerator.PrepareUserObject(); SCObjectOperations.Instance.AddUser(user4, SCOrganization.GetRoot()); SCObjectOperations.Instance.AddUserToGroup(user4, group); SCObjectOperations.Instance.RemoveUserFromGroup(user4, group); user4.Status = SchemaObjectStatus.Normal; SchemaObjectCollection needMergeUsers = new SchemaObjectCollection() { user1, user3, user4 }; UserAndContainerSnapshotAdapter.Instance.Merge(group.ID, group.SchemaType, needMergeUsers); Console.WriteLine("Group ID: {0}", group.ID); SameContainerUserAndContainerSnapshotCollection ugSnapshot = UserAndContainerSnapshotAdapter.Instance.LoadByContainerID(group.ID); Assert.IsTrue(ugSnapshot.ContainsKey(user1.ID)); Assert.AreEqual(SchemaObjectStatus.Normal, ugSnapshot[user1.ID].Status); Assert.IsTrue(ugSnapshot.ContainsKey(user2.ID)); Assert.AreEqual(SchemaObjectStatus.Deleted, ugSnapshot[user2.ID].Status); Assert.IsTrue(ugSnapshot.ContainsKey(user3.ID)); Assert.AreEqual(SchemaObjectStatus.Normal, ugSnapshot[user3.ID].Status); Assert.IsTrue(ugSnapshot.ContainsKey(user4.ID)); Assert.AreEqual(SchemaObjectStatus.Normal, ugSnapshot[user4.ID].Status); }
private void AddUsersToOrgs(SchemaObjectCollection users, SchemaObjectCollection orgs) { foreach (SCUser user in users) { foreach (SCOrganization org in orgs) { SCObjectOperations.InstanceWithPermissions.AddUserToOrganization(user, org); } } }
private void InitAllUsers() { InSqlClauseBuilder inBuilder = new InSqlClauseBuilder("SchemaType"); SchemaDefineCollection schemas = SchemaExtensions.CreateSchemasDefineFromConfiguration(); schemas.ForEach(schema => { if (string.Compare(schema.Category, "Users", true) == 0) inBuilder.AppendItem(schema.Name); }); this._AllUsers = SchemaObjectAdapter.Instance.Load(inBuilder); }
/// <summary> /// 将SchemaObject转换为DataTable /// </summary> /// <param name="obj"></param> /// <returns></returns> public DataTable Convert(SchemaObjectCollection objs) { DataTable table = CreateTable(); for (int i = 0; i < objs.Count; i++) { SCBase obj = (SCBase)objs[i]; DataRow row = table.NewRow(); FillPropertiesToTable(obj, i, row); table.Rows.Add(row); } return table; }
public static void SetUpFixture() { #if !NET35 // insight.schema requires 4.0, so let's assume that in 35, the setup is already done // let's do all of our work in the test database if (!SchemaInstaller.DatabaseExists(BaseTest.ConnectionString)) SchemaInstaller.CreateDatabase(BaseTest.ConnectionString); var schema = new SchemaObjectCollection(Assembly.GetExecutingAssembly()); using (var connection = new SqlConnection(BaseTest.ConnectionString)) { connection.Open(); var installer = new SchemaInstaller(connection); installer.Install("Test", schema); } #endif }
/// <summary> /// 合并用户信息 /// </summary> /// <param name="objects"></param> public void Merge(string containerID, string containerSchemaType, SchemaObjectCollection objects) { containerID.CheckStringIsNullOrEmpty("containerID"); containerSchemaType.CheckStringIsNullOrEmpty("containerSchemaType"); objects.NullCheck("objects"); SameContainerItemAndContainerSnapshotCollection existedData = this.LoadByContainerID(containerID); SameContainerItemAndContainerSnapshotCollection insertData = GetInsertData(containerID, containerSchemaType, existedData, objects); SameContainerItemAndContainerSnapshotCollection updateData = GetUpdateData(containerID, containerSchemaType, existedData, objects); ProcessProgress.Current.MaxStep += insertData.Count; ProcessProgress.Current.MaxStep += updateData.Count; ExecUpdateSeperately(insertData); ExecUpdateSeperately(updateData); }
static void Main() { var schema = new SchemaObjectCollection(); schema.Load(Assembly.GetExecutingAssembly()); // automatically create the database var connectionString = "server = .; database = PersonalFinance; integrated security = true;"; SchemaInstaller.CreateDatabase(connectionString); // automatically install it, or upgrade it using (var connection = new SqlConnection(connectionString)) { connection.Open(); var installer = new SchemaInstaller(connection); new SchemaEventConsoleLogger().Attach(installer); installer.Install("PersonalFinance", schema); } }
static void Main() { var schema = new SchemaObjectCollection(); schema.Load(Assembly.GetExecutingAssembly()); // automatically create the database var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; var databaseName = "Thomas-test-db"; SchemaInstaller.CreateDatabase(connectionString); // automatically install it, or upgrade it using (var connection = new SqlConnection(connectionString)) { connection.Open(); var installer = new SchemaInstaller(connection); new SchemaEventConsoleLogger().Attach(installer); installer.Install(databaseName, schema); } }
private void ImportOneGroup(SCObjectSet objectSet, IImportContext context, PC.Executors.ISCObjectOperations exec, SchemaObjectCollection parentObjects, SchemaObjectCollection memberObjects, int allCount, int count, SchemaObjectBase grp) { if (grp.SchemaType == "Groups") { try { var summaryName = grp.Properties.GetValue<string>("Name", "未命名"); context.SetStatus(count, allCount, "正在导入对象:" + summaryName); if (this.IncludeSelf) { SCRelationObject parentOrgRelation = (SCRelationObject)objectSet.Relations.Find(m => ((SCRelationObject)m).ParentSchemaType == "Organizations" && ((SCRelationObject)m).ChildSchemaType == "Groups" && ((SCRelationObject)m).ID == grp.ID); if (parentOrgRelation == null) throw new HttpException("未找到群组的父级组织"); var parentOrg = (SCOrganization)(parentObjects != null ? (from p in parentObjects where p.ID == parentOrgRelation.ParentID select p).FirstOrDefault() : null); if (parentOrg == null || parentOrg.Status != SchemaObjectStatus.Normal) throw new HttpException("群组的父级组织不存在或者已删除,未能导入群组。"); exec.AddGroup((SCGroup)grp, parentOrg); context.AppendLog("已执行导入对象" + summaryName); } ImportMembers(objectSet, context, exec, memberObjects, grp); ImportConditions(objectSet, context, grp); } catch (Exception ex) { context.AppendLog("对项的操作失败,原因是:" + ex.Message); } } else { context.AppendLog("已跳过不是群组的项"); } }
public void UpsertShouldReturnRowsInOrder() { var connectionString = base.ConnectionStrings.First(); TestWithDrop(connectionString, () => { using (var c = new SqlConnection(connectionString)) { if (!SchemaInstaller.DatabaseExists(connectionString)) SchemaInstaller.CreateDatabase(connectionString); c.Open(); SchemaInstaller installer = new SchemaInstaller(c); SchemaObjectCollection schema = new SchemaObjectCollection(); schema.Add("CREATE TABLE Beer ([id] [int] NOT NULL IDENTITY, [name] varchar(100))"); schema.Add("ALTER TABLE Beer ADD CONSTRAINT PK_Beer PRIMARY KEY ([ID])"); schema.Add("-- AUTOPROC All Beer"); installer.Install("test", schema); using (var reader = c.GetReaderSql(@" truncate table Beer declare @b BeerTable insert into @b (id, name) values (null, 'one') insert into @b (id, name) values (null, 'two') exec upsertBeers @b delete from @b insert into @b (id, name) values (1, 'one') insert into @b (id, name) values (2, 'two') insert into @b (id, name) values (null, 'three') exec upsertBeers @b ")) { reader.NextResult(); reader.Read(); Assert.AreEqual(1, reader.GetInt32(0)); reader.Read(); Assert.AreEqual(2, reader.GetInt32(0)); reader.Read(); Assert.AreEqual(3, reader.GetInt32(0)); } } }); }
protected override void PrepareData(AUObjectOperationContext context) { AUCommon.DoDbAction(() => { this.schema = (AUSchema)SchemaObjectAdapter.Instance.Load(((AdminUnit)Data).AUSchemaID); if (this.schema == null || this.schema.Status != SchemaObjectStatus.Normal) throw new AUObjectValidationException(AUCommon.DisplayNameFor((AdminUnit)this.Data) + "管理单元的SchemaID无效,无法找到对应的Schema。"); }); this.PrepareRelationObject(); base.PrepareData(context); var oldObject = (AdminUnit)SCActionContext.Current.OriginalObject; if (oldObject != null && oldObject.AUSchemaID != this.schema.ID) throw new AUObjectValidationException("一旦创建,不能以任何方式修改AdminUnit的AUSchema属性"); this.existingSchemaRoles = Adapters.AUSnapshotAdapter.Instance.LoadAUSchemaRoles(schema.ID, false, DateTime.MinValue); this.existingUnitRoles = Adapters.AUSnapshotAdapter.Instance.LoadAURoles(new string[] { this.Data.ID }, new string[0], false, DateTime.MinValue); this.existingUnitScopes = Adapters.AUSnapshotAdapter.Instance.LoadAUScope(this.Data.ID, false, DateTime.MinValue); this.pendingActions.Clear(); PrepareRolesAndScopes(); }
/// <summary> /// Uninstall a schema group from the database. /// </summary> /// <remarks>This is a transactional operation</remarks> /// <param name="schemaGroup">The group to uninstall</param> /// <exception cref="ArgumentNullException">If schemaGroup is null</exception> /// <exception cref="SqlException">If any object fails to uninstall</exception> public void Uninstall(string schemaGroup) { // validate the arguments if (schemaGroup == null) throw new ArgumentNullException("schemaGroup"); // create an empty collection and install that SchemaObjectCollection objects = new SchemaObjectCollection(); Install(schemaGroup, objects); }
/// <summary> /// 带递归地删除相关对象 /// </summary> /// <param name="objs"></param> public SCOrganization DeleteObjectsRecursively(SchemaObjectCollection objs, SCOrganization parent) { SCDeleteObjectsRecursivelyExecutor executor = new SCDeleteObjectsRecursivelyExecutor(parent, objs) { NeedStatusCheck = this.NeedValidationAndStatusCheck }; CheckPermissions(SCOperationType.DeleteOrganization, parent.Schema, "DeleteChildren", parent.ID); SCOrganization result = null; ExecuteWithActions(SCOperationType.DeleteOrganization, () => SCActionContext.Current.DoActions(() => result = (SCOrganization)executor.Execute())); return result; }
public void DeleteObjectsRecursivelyTest() { // 调用SCObjectGenerator,准备测试数据,包括人员、组织群组、组织中包含子组织和人员 SCObjectGenerator.PreareTestOguObjectForDelete(); SCOrganization parent = (SCOrganization)SchemaObjectAdapter.Instance.Load("91841971-44CB-4895-8B31-D9EA7432A74A"); // cityCompany SchemaObjectCollection objectsToDelete = new SchemaObjectCollection() { SchemaObjectAdapter.Instance.Load ("471F24D5-962E-46B9-849B-639D0AEB2B16") // beijingYuanlian }; ProcessProgress.Clear(); ProcessProgress.Current.RegisterResponser(TestProgressResponser.Instance); // 执行删除,过程中会输出状态信息 SCObjectOperations.Instance.DeleteObjectsRecursively(objectsToDelete, parent); // 输出 Console.Error.WriteLine("Error: {0}", ProcessProgress.Current.GetDefaultError()); Console.WriteLine("Output: {0}", ProcessProgress.Current.GetDefaultOutput()); // 验证结果 Assert.IsFalse(this.ObjectDeleted("2B67F7D0-9362-401F-977F-3E267E87298B")); // wangfaping Assert.IsFalse(this.ObjectDeleted("3729DAC3-80E0-476C-8C4A-264E0F67BBC2")); // liumh Assert.IsTrue(this.ObjectDeleted("066352AA-8349-4D21-B83F-C909BA5B8352")); // beijingYuanlianExecutives Assert.IsTrue(this.ObjectDeleted("2F28C437-BBF9-4969-9C07-639BD9716B1E")); // yuanyangAobei Assert.IsFalse(this.ObjectDeleted("16903BF9-74B5-4B58-9204-8BB20F341D88")); // beijingZhonglian Assert.IsTrue(this.ObjectDeleted("CA093A1E-B207-48DB-B3B2-B085A81DA36A")); // groupA Assert.IsTrue(this.ObjectDeleted("A465FFC8-A742-41F3-A1B6-0D40FC5EA3D5")); // groupB Assert.IsFalse(this.ObjectDeleted("D1C28431-DD5D-496E-865B-85C6D89ED3D6")); // zhaolin1 }
/// <summary> /// Install a schema into a database. /// </summary> /// <param name="connection">The connection to use.</param> /// <param name="sql"the SQL to install.</param> private static void Install(DbConnection connection, IEnumerable<string> sql) { SchemaInstaller installer = new SchemaInstaller(connection); SchemaObjectCollection schema = new SchemaObjectCollection(); if (sql != null) { foreach (string s in sql) { // azure doesn't support xml index, so lets comment those out if (s.Contains("XML INDEX") && connection.IsAzure()) continue; schema.Add(s); } } installer.Install("test", schema); }
public SchemaObjectCollection GetCurrentUsers() { SchemaObjectCollection result = null; SCRelationObject relation = this.CurrentParentRelations.FirstOrDefault(); if (relation != null) { SCObjectAndRelationCollection objsAndRelations = SCSnapshotAdapter.Instance.QueryObjectAndRelationByParentFullPath( SchemaInfo.FilterByCategory("Users").ToSchemaNames(), new string[] { relation.FullPath }, true, true, false, DateTime.MinValue); result = objsAndRelations.ToSchemaObjects(); } else result = new SchemaObjectCollection(); return result; }
/// <summary> /// Script the changes that would be applied to the database. /// </summary> /// <param name="schemaGroup">The name of the schemaGroup.</param> /// <param name="schema">The schema to install.</param> /// <returns>The script representing the changes to the database.</returns> public string ScriptChanges(string schemaGroup, SchemaObjectCollection schema) { // create a transaction around the installation // NOTE: don't commit the changes to the database // WARNING: due to the way we script autoprocs (and maybe others), this has to modify the database, then roll back the changes // so you might not want to try this on a live production database. Go get a copy of your database, then do the scripting on a staging environment. using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(1, 0, 0, 0, 0))) { _connection.OnlyRecord(() => Install(schemaGroup, schema)); } return _connection.ScriptLog.ToString(); }
public void Install(string schemaGroup, SchemaObjectCollection schema) { _connection.ResetLog(); // validate the arguments if (schemaGroup == null) throw new ArgumentNullException("schemaGroup"); if (schema == null) throw new ArgumentNullException("schema"); // make sure the schema objects are valid schema.Validate(); // number the objects so when we compare them we have a final comparison List<SchemaObject> schemaObjects = schema.Where(o => o.SchemaObjectType != SchemaObjectType.Unused).ToList(); for (int i = 0; i < schemaObjects.Count; i++) schemaObjects[i].OriginalOrder = i; // order the changes by reverse install order schemaObjects.Sort((o1, o2) => -CompareByInstallOrder(o1, o2)); // get the list of objects to install, filtering out the extra crud InstallContext context = new InstallContext(); context.SchemaObjects = schemaObjects; // azure doesn't support filegroups or partitions, so we need to know if we are on azure context.IsAzure = _connection.ExecuteScalarSql<bool>("SELECT CONVERT(bit, CASE WHEN SERVERPROPERTY('edition') = 'SQL Azure' THEN 1 ELSE 0 END)", null); // NOTE: we can't use System.Transactions.TransactionScope here, because certain operations cause SQL server to commit internal data structures // and then if an exception is thrown, our registry changes wouldn't be in sync with the database. try { _connection.ExecuteSql("BEGIN TRANSACTION"); // load the schema registry from the database context.SchemaRegistry = new SchemaRegistry(_connection, schemaGroup); // find all of the objects that we need to drop // sort to drop in reverse dependency order context.DropObjects = context.SchemaRegistry.Entries .Where(e => !context.SchemaObjects.Any(o => String.Compare(e.ObjectName, o.Name, StringComparison.OrdinalIgnoreCase) == 0)) .ToList(); context.DropObjects.Sort((e1, e2) => -CompareByInstallOrder(e1, e2)); // find all of the objects that are not in the registry and don't exist context.AddObjects = context.SchemaObjects.Where(o => !context.SchemaRegistry.Contains(o) && !o.Exists(_connection)).ToList(); // find all of the objects that have changed _connection.DoNotLog(() => { // for anything that's not entirely new foreach (var change in context.SchemaObjects.Except(context.AddObjects)) { // if the object is in the registry and the signature matches, then there is no change var registryEntry = context.SchemaRegistry.Find(change); if (registryEntry != null && context.SchemaRegistry.Find(change).Signature == change.GetSignature(_connection, schema)) continue; // if the object is NOT in the registry, but already exists (we know because it's not in the add list already) // then we assume it has changed // UNLESS this is not a type we can drop, and we are in repair mode, we will skip it if (registryEntry == null && !change.CanModify(context, _connection) && AllowRepair) { Console.WriteLine("WARNING: {0} {1} already exists in the database and cannot be modified. Assuming that it has not changed.", change.SchemaObjectType, change.Name); continue; } ScriptUpdate(context, change); } }); // sort the objects in install order context.AddObjects.Sort(CompareByInstallOrder); // make the changes DropObjects(context.DropObjects); AddObjects(context); VerifyObjects(context.SchemaObjects); // update the schema registry context.SchemaRegistry.Update(context.SchemaObjects); // complete the changes _connection.ExecuteSql("COMMIT"); } catch (Exception) { // rollback the transaction // this shouldn't fail // if it does, then the outer application may need to roll it back try { _connection.ExecuteSql("ROLLBACK"); } catch (SqlException) { } throw; } }
private SchemaPropertyValueCollection GetCommonValues(SchemaObjectCollection objects, List<SchemaPropertyDefineConfigurationElement> propertyDefines) { SchemaPropertyValueCollection result = new SchemaPropertyValueCollection(); HashSet<string> pool = new HashSet<string>(); foreach (var item in propertyDefines) { pool.Clear(); SchemaPropertyValue val = null; foreach (var obj in objects) { val = obj.Properties[item.Name]; pool.Add(val.StringValue); } result.Add(pool.Count == 1 ? val : new SchemaPropertyValue(val.Definition)); } return result; }
/// <summary> /// Determine if the given schema has differences with the current schema. /// </summary> /// <param name="schemaGroup">The schema group to compare.</param> /// <param name="schema">The schema to compare with.</param> /// <returns>True if there are any differences.</returns> public bool Diff(string schemaGroup, SchemaObjectCollection schema) { // validate the arguments if (schemaGroup == null) throw new ArgumentNullException("schemaGroup"); if (schema == null) throw new ArgumentNullException("schema"); SchemaRegistry registry = new SchemaRegistry(_connection, schemaGroup); // if any objects are missing from the registry, then there is a difference if (schema.Any(o => registry.Find(o.Name) == null)) return true; // if there are any registry entries missing from the new schema, there is a difference if (registry.Entries.Any(e => !schema.Any(o => String.Compare(e.ObjectName, o.Name, StringComparison.OrdinalIgnoreCase) == 0))) return true; // if there are any matches, but have different signatures, there is a difference if (schema.Any(o => registry.Find(o.Name).Signature != o.GetSignature(_connection, schema))) return true; // didn't detect differences return false; }
private void ImportMembers(SCObjectSet objectSet, IImportContext context, PC.Executors.ISCObjectOperations exec, SchemaObjectCollection memberObjects, SchemaObjectBase grp) { if (this.IncludeMembers && objectSet.HasMembership) { var memberRelations = objectSet.Membership.FindAll(m => m.ContainerID == grp.ID && m.Status == SchemaObjectStatus.Normal); if (memberRelations.Count > 0 && memberObjects != null) { context.AppendLogFormat("正在试图添加{0}个群组成员\r\n", memberRelations.Count); foreach (var r in memberRelations) { var user = (SCUser)(from m in memberObjects where m.ID == r.ID select m).FirstOrDefault(); if (user != null) { try { exec.AddUserToGroup(user, (SCGroup)grp); context.AppendLogFormat("已经向群组{0}添加群组成员:{1}\r\n", ((SCGroup)grp).DisplayName, user.DisplayName); } catch (Exception ex) { context.AppendLogFormat("无法导入群组 {0} 的成员 {1}: {2}\r\n", ((SCGroup)grp).DisplayName, user.DisplayName, ex.Message); } } else { context.AppendLogFormat("已跳过不存在的成员\r\n"); } } } } }