public bool AreEqual(SyncSession session, PropertyMapping mapping, NameObjectCollection srcValues, SchemaObjectBase targetObj) { var srcValue = srcValues[mapping.SourceProperty] ?? Common.EmptyString; var targetString = targetObj.Properties[mapping.TargetProperty].StringValue; if (typeof(float).IsAssignableFrom(srcValue.GetType())) { if (string.IsNullOrEmpty(targetString) == false) { float left = (float)srcValue; float right = float.Parse(targetString); if (string.IsNullOrEmpty(mapping.Parameters["precision"])) { return left.Equals(right); //完全精度匹配(几乎不可能实现) } else { int precision = int.Parse(mapping.Parameters["precision"]); double delta = Math.Abs(left - right) * Math.Pow(10, precision); //通常两个数相差在delta范围内算相等 return delta < 1; } } else return false; // 左边对象有值,而右边对象没值 } else if (srcValue is string) { return ((string)srcValue) == targetString; } else { return mapping.Parameters["sourceDefaultValue"] == targetString; //源对象为null或其他情形 } }
public DeleteSelfAction(SchemaObjectBase item) { this.item = item; item.ClearRelativeData(); this.parentRelations = item.CurrentParentRelations; this.containerRelations = SCMemberRelationAdapter.Instance.LoadByMemberID(item.ID).FilterByStatus(SchemaObjectStatusFilterTypes.Normal); }
private static string GetMessage(SchemaObjectBase originalData, Executors.AUOperationType auOperationType) { if (originalData == null) throw new ArgumentNullException("originalData"); return string.Format("ID:为 {0} 的对象的状态不允许执行{1}操作。", originalData.ID, auOperationType.ToString()); }
public bool AreEqual(SyncSession session, PropertyMapping mapping, NameObjectCollection srcValues, SchemaObjectBase targetObj) { var srcValue = srcValues[mapping.SourceProperty] ?? Common.EmptyString; var targetString = targetObj.Properties[mapping.TargetProperty].StringValue; if (typeof(DateTime).IsAssignableFrom(srcValue.GetType())) { if (string.IsNullOrEmpty(targetString) == false) { DateTime left = (DateTime)srcValue; DateTime right = DateTime.Parse(targetString); return left.Equals(right); //完全精度匹配(几乎不可能实现) } else return false; // 左边对象有值,而右边对象没值 } else if (srcValue is string) { return ((string)srcValue) == targetString; } else { return mapping.Parameters["sourceDefaultValue"] == targetString; //源对象为null或其他情形 } }
public SCAclContainer(SchemaObjectBase container) { container.NullCheck("container"); this.ContainerID = container.ID; this.ContainerSchemaType = container.SchemaType; }
private void ImportOneUnit(MCS.Library.SOA.DataObjects.Security.SCObjectSet objectSet, Operations.IFacade exec, ImportContextWrapper wrapper, SchemaObjectBase parent, int totalSteps, AdminUnit unit) { int currentStep = 0; var scopes = (from m in objectSet.Membership where m.ContainerID == unit.ID && m.MemberSchemaType == AUCommon.SchemaAUAdminScope && m.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal join o in objectSet.Objects on m.ID equals o.ID where o.SchemaType == AUCommon.SchemaAUAdminScope && o.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal select (AUAdminScope)o).ToArray(); var roles = (from m in objectSet.Membership where m.ContainerID == unit.ID && m.MemberSchemaType == AUCommon.SchemaAdminUnitRole && m.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal join o in objectSet.Objects on m.ID equals o.ID where o.SchemaType == AUCommon.SchemaAdminUnitRole && o.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal select (AURole)o).ToArray(); try { currentStep++; wrapper.SetStatusAndLog(currentStep, totalSteps, "正在导入管理单元" + unit.GetQualifiedName()); exec.AddAdminUnitWithMembers(unit, (AdminUnit)parent, roles, scopes); ImportRoleMembers(objectSet, exec, wrapper, totalSteps, unit, currentStep, roles); ImportConditions(objectSet, exec, wrapper, totalSteps, unit, currentStep, scopes); if (this.ImportSubUnits) { wrapper.IncreaseLevel(); var subs = (from r in objectSet.Relations where r.ParentID == unit.ID && r.ChildSchemaType == AUCommon.SchemaAdminUnit && r.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal join o in objectSet.Objects on r.ID equals o.ID where o.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal && o.SchemaType == AUCommon.SchemaAdminUnit select (AdminUnit)o).ToArray(); int count = subs.Length; foreach (AdminUnit s in subs) { ImportOneUnit(objectSet, exec, wrapper, unit, count, s); } wrapper.DecreaseLevel(); } } catch (Exception ex) { wrapper.IncreaseError(); wrapper.SetStatusAndLog(currentStep, totalSteps, string.Format("导入单元 {0} 失败,原因是:{1}", unit.GetQualifiedName(), ex.ToString())); } }
public AUObjectExecutor(AUOperationType opType, SchemaObjectBase data) : base(opType) { data.NullCheck("data"); data.ClearRelativeData(); this._Data = data; }
protected virtual void Fill(IOguObject target, SchemaObjectBase src, SCObjectAndRelation relation, SCSimpleObjectCollection parentsInfo) { Fill(target, src, relation); var wrapper = target as IOguPropertyAccessible; if (parentsInfo != null && parentsInfo.Count > 0) wrapper.FullPath = parentsInfo.JoinNameToFullPath() + "\\" + wrapper.Name; }
public AddMemberAction(SchemaObjectBase container, SchemaObjectBase member) { this.container = container; this.member = member; this.relation = new SCMemberRelation(container, member); if (member.Status != Schemas.SchemaProperties.SchemaObjectStatus.Normal) relation.Status = Schemas.SchemaProperties.SchemaObjectStatus.Deleted; }
private void CodeNameValidationMethod(string strToValue, SchemaObjectBase doValidateObj, string key, ValidationResults validateResults) { bool result = CodeNameUniqueValidatorFacade.ValidateCodeName(strToValue, CodeNameUniqueValidatorFacade.GetScopeSchemas2(doValidateObj.Schema.CodeNameKey).ToArray(), doValidateObj.ID, this.includingDeleted == false, false, DateTime.MinValue); if (result == false) { ObjectSchemaConfigurationElement config = ObjectSchemaSettings.GetConfig().Schemas[doValidateObj.SchemaType]; RecordValidationResult(validateResults, string.Format(this.MessageTemplate, string.IsNullOrEmpty(config.Description) ? config.Description : config.Name, doValidateObj.Properties["Name"].StringValue, doValidateObj.ID), doValidateObj, key); } }
public SCUpdateObjectImageExecutor(SCOperationType opType, SchemaObjectBase obj, string propertyName, ImageProperty image) : base(opType) { obj.NullCheck("obj"); propertyName.IsNullOrEmpty().TrueThrow("propertyName不能为空!"); this._Object = obj; this._PropertyName = propertyName; this._Image = image; }
public DataView Query(int startRowIndex, int maximumRows, string unitID, string scopeType, string where, string orderBy, ref int totalCount) { unitID.NullCheck("unitID"); scopeType.NullCheck("scopeType"); this.scope = Adapters.AUSnapshotAdapter.Instance.LoadAUScope(unitID, scopeType, true, DateTime.MinValue).FirstOrDefault(); if (this.scope == null || this.scope.Status != Schemas.SchemaProperties.SchemaObjectStatus.Normal) throw new AUObjectException("不存在指定的单元或者管理范围"); return base.Query(startRowIndex, maximumRows, where, orderBy, ref totalCount); }
/// <summary> /// 断开容器与成员的关系(不影响成员对象) /// </summary> /// <param name="obj"></param> public void ClearContainer(SchemaObjectBase obj) { AUCommon.DoDbAction(() => { var memberRelations = PC.Adapters.SCMemberRelationAdapter.Instance.LoadByContainerID(obj.ID, DateTime.MinValue); foreach (var item in memberRelations) { if (item.Status == Schemas.SchemaProperties.SchemaObjectStatus.Normal) PC.Adapters.SCMemberRelationAdapter.Instance.UpdateStatus(item, Schemas.SchemaProperties.SchemaObjectStatus.Deleted); } }); }
public AUMemberRelativeExecutorBase(AUOperationType opType, SchemaObjectBase container, SchemaObjectBase member) : base(opType, member) { container.NullCheck("container"); container.ClearRelativeData(); if (member != null) member.ClearRelativeData(); this._Container = container; this._Relation = PrepareRelationObject(container, member); }
public override void WriteErrorLog(SyncSession syncSession, SchemaObjectBase scObj, Exception ex) { CheckLogPresent(); this.log.NumberOfExceptions++; var detail = new SqlIncomeSyncLogDetail(); detail.LogDetailID = UuidHelper.NewUuidString(); detail.LogID = this.log.LogID; detail.SCObjectID = scObj.ID; detail.Summary = ex.Message; detail.Detail = ex.ToString(); detail.ActionType = SqlIncomeSyncLogDetailStatus.Update; Adapters.SqlIncomeLogDetailAdapter.Instance.Update(detail); }
private static DeluxeTreeNode CreateTreeNode(SchemaObjectBase obj) { string name = obj.Properties.GetValue("DisplayName", string.Empty); if (string.IsNullOrEmpty(name)) name = obj.Properties.GetValue("Name", string.Empty); DeluxeTreeNode node = new DeluxeTreeNode(name, obj.ID); node.ChildNodesLoadingType = ChildNodesLoadingTypeDefine.LazyLoading; node.ToolTip = obj.Properties.GetValue("description", string.Empty); node.NodeOpenImg = ControlResources.OULogoUrl; node.NodeCloseImg = ControlResources.OULogoUrl; return node; }
private List<Validator> GenerateValidators(SchemaObjectBase obj) { List<Validator> result = new List<Validator>(); foreach (SchemaPropertyValue pv in obj.Properties) { foreach (Validator v in pv.Validators) { ValueAccessValidator validator = new ValueAccessValidator(new SchemaPropertyValueAccess(pv), v, pv.Definition.Name); result.Add(validator); } } return result; }
/// <summary> /// 构造一个生成FullPath的作业 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static SCToDoJob CreateGenerateFullPathsJob(SchemaObjectBase obj) { obj.NullCheck("obj"); SCToDoJob job = new SCToDoJob(); job.Type = "GenerateFullPaths"; if (obj != null) { job.SourceID = obj.ID; job.Description = string.Format("Generate full paths from '{0}'", obj.ID); job.Data = obj.ToString(); } return job; }
public void SetValue(SyncSession session, PropertyMapping mapping, NameObjectCollection srcValues, SchemaObjectBase targetObj) { var srcValue = srcValues[mapping.SourceProperty] ?? Common.EmptyString; if (typeof(int).IsAssignableFrom(srcValue.GetType())) { targetObj.Properties[mapping.TargetProperty].StringValue = ((int)srcValue).ToString(); } else if (srcValue is string) { targetObj.Properties[mapping.TargetProperty].StringValue = (string)srcValue; } else { //其他情况如null,DbNull等,以及不知如何转换的 targetObj.Properties[mapping.TargetProperty].StringValue = string.Empty ; } }
public virtual void Fill(IOguObject target, SchemaObjectBase src, SCObjectAndRelation relation) { var wrapper = target as IOguPropertyAccessible; (wrapper != null).FalseThrow("工厂创建的对象未实现IOguPropertyAccessible"); wrapper.Description = src.Properties.GetValue<string>("Description", string.Empty); wrapper.DisplayName = src.Properties.GetValue<string>("DisplayName", string.Empty); wrapper.ID = src.ID; wrapper.Name = src.Properties.GetValue<string>("Name", string.Empty); wrapper.Name.IsNullOrEmpty().TrueThrow<InvalidCastException>("名称不可省略"); if (relation != null) { wrapper.SortID = relation.InnerSort.ToString(); wrapper.Properties["ParentID"] = relation.ParentID; } }
private bool InitState() { string ouID = WebUtility.GetRequestQueryString("ou", string.Empty); bool result = true; try { SchemaObjectBase parent = DbUtil.GetEffectiveObject(ouID, null); this.ParentOrganization = parent.ToSimpleObject(); this.hfOuParentId.Value = parent.ID == SCOrganization.RootOrganizationID ? string.Empty : DbUtil.GetParentOURelation(parent.ID).ParentID; } catch (ObjectNotFoundException) { result = false; } return(result); }
/// <summary> /// 数据库字段是否级联删除 /// </summary> /// <param name="column"></param> /// <returns></returns> private static bool IsCascadeDelete(SchemaObjectBase column) { bool cascadeDelete = false; try { if (column.ExtendedProperties.Contains(ExtendedPropertyNames.CascadeDelete)) { string value = column.ExtendedProperties[ExtendedPropertyNames.CascadeDelete].Value.ToString(); bool.TryParse(value, out cascadeDelete); } } catch (Exception ex) { Debug.WriteLine("异常: " + ex.Message); } return(cascadeDelete); }
/// <summary> /// 将指定的<see cref="SchemaObjectBase"/>的派生类转换为<see cref="PhantomOguBase"/>的对应派生类 /// </summary> /// <param name="oguObj"></param> /// <returns></returns> public static PhantomOguBase ToPhantom(this SchemaObjectBase oguObj) { var category = oguObj.Schema.Category; switch (category) { case "Users": return(new PhantomUser(oguObj)); case "Groups": return(new PhantomGroup(oguObj)); case "Organizations": return(new PhantomOrganization(oguObj)); default: throw new ArgumentException("不支持的SchemaObject类型", "oguObj"); } }
private static void ParentsCheck(params SchemaObjectBase[] objs) { if (objs.Length > 0) { SchemaObjectBase prevObj = objs[0]; for (int i = 1; i < objs.Length; i++) { SchemaObjectBase currentObj = objs[i]; Assert.IsTrue(prevObj.CurrentParents.ContainsKey(currentObj.ID), "对象{0}({1})不是对象{2}({3})的父对象", currentObj.ID, currentObj.SchemaType, prevObj.ID, prevObj.SchemaType); prevObj = currentObj; } } }
private static void DoOperation(SchemaObjectBase relativeObject, string description, Action <RolesFunctionsImportContext> callerAction, Action innerAction) { innerAction.NullCheck("innerAction"); RolesFunctionsImportContext context = new RolesFunctionsImportContext() { RelativeObject = relativeObject, Description = description }; ProcessProgress.Current.Response(context.Description); try { innerAction(); } catch (System.Exception ex) { context.Exception = ex; } finally { if (context.Exception == null) { context.ResponseMessage = string.Format("{0}完成", context.Description); } else { context.ResponseMessage = string.Format("{0}异常: {1}", context.Description, context.Exception.Message); } if (callerAction != null) { callerAction(context); } ProcessProgress.Current.Increment(); ProcessProgress.Current.Response(context.ResponseMessage); } context.Continue.FalseThrow("导入被终止"); }
internal void WriteErrorLog(SchemaObjectBase scObj, Exception ex) { if (this.Loggers != null) { foreach (var item in this.Loggers) { try { item.WriteErrorLog(this, scObj, ex); } catch { if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debugger.Log(1, "日志", "记录日志时发生错误。"); } } } } }
public PhantomOguBase(SchemaObjectBase src) : base(new DummyOguObject(), GetSchemaType(src.Schema.Category)) { this.ID = src.ID; this.ObjectType = GetSchemaType(src.Schema.Category); this.Name = src.Properties.GetValue <string>("Name", string.Empty); this.DisplayName = src.Properties.GetValue <string>("DisplayName", this.Name); if (string.IsNullOrEmpty(this.DisplayName)) { this.DisplayName = this.Name; } if (src.Status == SchemaObjectStatus.Deleted || src.Status == SchemaObjectStatus.DeletedByContainer) { this.Properties["STATUS"] = 3; } else { this.Properties["STATUS"] = 1; } }
internal static SchemaObjectBase GetEffectiveObject(string id, string message) { SchemaObjectBase result = null; AUCommon.DoDbAction(() => { result = PC.Adapters.SchemaObjectAdapter.Instance.Load(id); }); if (result == null) { throw message != null ? new ObjectNotFoundException(message) : ObjectNotFoundException.CreateForID(id); } else if (result.Status != SchemaObjectStatus.Normal) { throw message != null ? new ObjectNotFoundException(message) : ObjectNotFoundException.CreateForID(id); } return(result); }
private void ImportConditions(SCObjectSet objectSet, IImportContext context, SchemaObjectBase grp) { if (this.IncludeConditions && objectSet.HasConditions) { PC.Conditions.SCConditionOwner owner = new PC.Conditions.SCConditionOwner() { OwnerID = grp.ID, Type = "Default" }; var conditions = from c in objectSet.Conditions where c.OwnerID == grp.ID && c.Type == "Default" select c; foreach (var c in conditions) { owner.Conditions.Add(c); } context.AppendLog("正在添加条件表达式"); PC.Adapters.SCConditionAdapter.Instance.UpdateConditions(owner); context.AppendLog("添加条件表达式结束。"); } }
/// <summary> /// 根据ID校验对象一致性 /// </summary> /// <param name="description">描述</param> /// <param name="errors">一个集合,如果发生错误,将错误添加到此集合 - 或 - <see langword="null"/>时,忽略此集合。</param> /// <param name="objects"></param> /// <param name="ids"></param> internal static void ValidateObjectsByIDs(string description, IBatchErrorAdapter errors, SchemaObjectCollection objects, IEnumerable <string> ids) { foreach (string id in ids) { try { SchemaObjectBase obj = objects[id]; (obj == null).TrueThrow("类型{0},对象{1}不存在", description ?? "(未知)", id); (obj.Status != SchemaObjectStatus.Normal).TrueThrow("类型{0},对象{1}已删除", description ?? obj.SchemaType, id); } catch (System.Exception ex) { if (errors != null) { errors.AddError(ex); } } } }
public SchemaObjectBase DeletePermission(SCPermission permission) { SCObjectExecutor executor = new SCObjectExecutor(SCOperationType.DeletePermission, permission) { NeedValidation = false, NeedDeleteMemberRelations = true, NeedDeleteRelations = true, NeedStatusCheck = this.NeedValidationAndStatusCheck }; if (this._NeedCheckPermissions) { CheckApplicationMemberPermissions(SCOperationType.DeletePermission, "DeletePermissions", permission); } permission.Status = SchemaObjectStatus.Deleted; SchemaObjectBase result = null; ExecuteWithActions(SCOperationType.DeletePermission, () => SCActionContext.Current.DoActions(() => result = (SchemaObjectBase)executor.Execute())); return(result); }
private SchemaObjectBase DoOperation(SchemaOperationDefine sod, SchemaObjectBase data, SchemaObjectBase parent, bool deletedByContainer) { sod.MethodName.CheckStringIsNullOrEmpty("MethodName"); Type type = this.GetType(); MethodInfo mi = type.GetMethod(sod.MethodName); (mi != null).FalseThrow("不能在类型{0}中找到方法{1}", type.FullName, sod.MethodName); object[] parameters = null; if (sod.HasParentParemeter || parent != null) { if (sod.OperationMode == SCObjectOperationMode.Delete) { parameters = new object[] { data, parent, deletedByContainer } } ; else { parameters = new object[] { data, parent } }; } else { parameters = new object[] { data } }; try { return((SchemaObjectBase)mi.Invoke(this, parameters)); } catch (TargetParameterCountException ex) { Exception realException = ex.GetRealException(); throw new ApplicationException(string.Format("调用方法{0}出现异常,参数个数为{1}: {2}", sod.MethodName, parameters.Length, realException.Message), realException); } }
public bool AreEqual(SyncSession session, PropertyMapping mapping, NameObjectCollection srcValues, SchemaObjectBase targetObj) { string enumType = mapping.Parameters["enumType"]; if (string.IsNullOrEmpty(enumType)) throw new System.Configuration.ConfigurationErrorsException("配置EnumPropertyComparer时,必须指定enumType属性"); var type = Type.GetType(enumType); if (type == null) throw new System.Configuration.ConfigurationErrorsException("未找到指定的枚举类型 " + enumType); object srcValue = srcValues[mapping.SourceProperty]; string targetString = targetObj.Properties[mapping.TargetProperty].StringValue; if (string.IsNullOrEmpty(targetString) == false) { return srcValue.Equals(int.Parse(targetString)); } else return false; }
protected override void DoValidate(object objectToValidate, object currentObject, string key, ValidationResults validateResults) { bool isValid = false; var types = SchemaInfo.FilterByCategory("AdminScopeItems"); foreach (var item in types) { if (item.Name.Equals(objectToValidate)) { isValid = true; break; } } if (isValid == false) { SchemaObjectBase doValidateObj = (SchemaObjectBase)currentObject; ObjectSchemaConfigurationElement config = ObjectSchemaSettings.GetConfig().Schemas[doValidateObj.SchemaType]; this.RecordValidationResult(validateResults, string.Format(this.MessageTemplate, string.IsNullOrEmpty(config.Description) ? config.Description : config.Name, doValidateObj.Properties["Name"].StringValue, doValidateObj.ID), doValidateObj, key); } }
public void Alter(TextWriter writer, SchemaObjectBase schemaObject) { if (schemaObject is ViewSchema) { writer.Write( schemaObject.Database.Provider.GetViewText(schemaObject.Database.ConnectionString, (ViewSchema)schemaObject).Replace("CREATE ", "ALTER ") ); } if (schemaObject is CommandSchema) { writer.Write( schemaObject.Database.Provider.GetCommandText(schemaObject.Database.ConnectionString, (CommandSchema)schemaObject).Replace("CREATE ", "ALTER ") ); } if (schemaObject is TableSchema) { // TODO } }
public override void Fill(IOguObject target, SchemaObjectBase src, SCObjectAndRelation relation) { base.Fill(target, src, relation); if (src.SchemaType != "Users") throw new ArgumentException(string.Format("SchemaType不匹配", src), "src"); var wrapper = target as OGUPermission.IUserPropertyAccessible; if (wrapper == null) throw new InvalidCastException("工厂创建的对象未实现IUserPropertyAccessible"); //wrapper.Levels = src.Properties.GetValue<int>("Levels", 0); wrapper.Attributes = src.Properties.GetValue<UserAttributesType>("CadreType", UserAttributesType.Unspecified); wrapper.Email = src.Properties.GetValue<string>("Mail", string.Empty); wrapper.LogOnName = src.Properties.GetValue<string>("CodeName", string.Empty); wrapper.ObjectType = SchemaType.Users; wrapper.Occupation = src.Properties.GetValue<string>("Occupation", string.Empty); wrapper.Rank = src.Properties.GetValue<UserRankType>("UserRank", UserRankType.Unspecified); if (relation != null) wrapper.IsSideline = !relation.Default; }
private static void FillCommon(SchemaObjectBase pcObj, ClientSchemaObjectBase clientObj) { pcObj.NullCheck("pcObj"); clientObj.NullCheck("clientObj"); clientObj.ID = pcObj.ID; clientObj.CreateDate = pcObj.CreateDate; clientObj.SchemaType = pcObj.SchemaType; clientObj.Status = (ClientSchemaObjectStatus)pcObj.Status; clientObj.VersionEndTime = pcObj.VersionEndTime; clientObj.VersionStartTime = pcObj.VersionStartTime; if (pcObj.Creator != null) { clientObj.Creator = new ClientOguUser() { DisplayName = string.IsNullOrEmpty(pcObj.Creator.DisplayName) ? pcObj.Creator.Name : pcObj.Creator.DisplayName, ID = pcObj.Creator.ID }; } pcObj.Properties.CopyTo(clientObj.Properties); }
protected void CheckObjectStatus(params SchemaObjectBase[] objsToCheck) { List <SchemaObjectBase> normalizedObjsToCheck = new List <SchemaObjectBase>(); foreach (SchemaObjectBase obj in objsToCheck) { normalizedObjsToCheck.Add(obj); } InSqlClauseBuilder idBuilder = new InSqlClauseBuilder("ID"); normalizedObjsToCheck.ForEach(o => idBuilder.AppendItem(o.ID)); if (idBuilder.IsEmpty == false) { SchemaObjectCollection originalDataList = null; AUCommon.DoDbAction(() => { originalDataList = SchemaObjectAdapter.Instance.Load(idBuilder); }); string opName = EnumItemDescriptionAttribute.GetDescription(this.OperationType); foreach (SchemaObjectBase objToCheck in normalizedObjsToCheck) { if (originalDataList.ContainsKey(objToCheck.ID) == false) { throw new AUStatusCheckException(string.Format("ID为\"{0}\"的对象不存在,不能执行{1}操作", objToCheck.ID, opName)); } SchemaObjectBase originalData = originalDataList[objToCheck.ID]; if (originalData.Status != SchemaObjectStatus.Normal) { throw new AUStatusCheckException(originalData, this.OperationType); } } } }
protected override void DoValidate(object objectToValidate, object currentObject, string key, ValidationResults validateResults) { SchemaObjectBase doValidateObj = currentObject as SchemaObjectBase; if (doValidateObj != null) { string strValue = objectToValidate.ToString(); ExceptionHelper.TrueThrow(strValue.IsNullOrEmpty(), "代码名称不能为空"); switch (doValidateObj.Schema.CodeNameValidationMethod) { case SchemaObjectCodeNameValidationMethod.ByCodeNameKey: this.CodeNameValidationMethod(strValue, doValidateObj, key, validateResults); break; case SchemaObjectCodeNameValidationMethod.ByContainerAndCodeNameKey: this.ByContainerAndCodeNameKey(strValue, doValidateObj, key, validateResults); break; } } }
public override void Fill(IOguObject target, SchemaObjectBase src, SCObjectAndRelation relation) { base.Fill(target, src, relation); if (src.SchemaType != "Organizations") { throw new ArgumentException(string.Format("SchemaType {0}不匹配", src), "src"); } var wrapper = target as OGUPermission.IOrganizationPropertyAccessible; if (wrapper == null) { throw new InvalidCastException("工厂创建的对象未实现IOrganizationPropertyAccessible"); } wrapper.CustomsCode = src.Properties.GetValue <string>("CustomsCode", string.Empty); // 关区号 wrapper.DepartmentClass = src.Properties.GetValue <DepartmentClassType>("DepartmentClass", DepartmentClassType.Unspecified); wrapper.DepartmentType = src.Properties.GetValue <DepartmentTypeDefine>("DepartmentType", DepartmentTypeDefine.Unspecified); //wrapper.Levels = src.Properties.GetValue<int>("Levels", 0); wrapper.ObjectType = SchemaType.Organizations; wrapper.Rank = src.Properties.GetValue <DepartmentRankType>("DepartmentRank", DepartmentRankType.None); }
private void DoBatchExecute(SyncSession session) { DataProviderBase provider = session.SourceProvider; provider.Reset(); List <NameObjectCollection> buffer = new List <NameObjectCollection>(session.BatchSize); int len; do { buffer.Clear(); len = FetchToBuffer(buffer, provider, session.BatchSize); if (len > 0) { string[] keys = new string[len]; for (int i = buffer.Count - 1; i >= 0; i--) { keys[i] = (string)buffer[i][session.Mappings.SourceKeyProperty]; if (string.IsNullOrWhiteSpace(keys[i])) { throw new SyncException("数据源提供的对象的ID为空"); } } SchemaObjectCollection scObjs = LoadSchemaObjects(keys); foreach (NameObjectCollection item in buffer) { string id = (string)item[session.Mappings.SourceKeyProperty]; SchemaObjectBase scObj = scObjs[id]; if (scObjs != null) { CompareAndChange(session, item, session.Mappings.AllObjectValues, scObj); } } } } while (len > 0 && len != session.BatchSize); }
private SCSimpleRelationBase PrepareRelationObject(SchemaObjectBase container, SchemaObjectBase member) { SCSimpleRelationBase relation = SCMemberRelationAdapter.Instance.Load(container.ID, member.ID); if (relation == null) { relation = CreateRelation(container, member); } else { if (relation.Status == SchemaObjectStatus.Normal) { this._RelationExisted = true; } else { relation.Status = SchemaObjectStatus.Normal; } } return(relation); }
public void CreateSchemaObjectPerformanceTest() { var schemaElem = ObjectSchemaSettings.GetConfig().Schemas[0]; Stopwatch sw = new Stopwatch(); sw.Start(); try { for (int i = 0; i < 100000; i++) { SchemaObjectBase obj = SchemaExtensions.CreateObject(schemaElem.Name); Assert.IsTrue(obj.Properties != null); } } finally { sw.Stop(); Console.WriteLine("经过时间{0:#,##0}毫秒", sw.ElapsedMilliseconds); } }
public OguObjectCollection <IOguObject> GetObjects(params string[] ids) { ids.NullCheck("ids"); SCObjectAndRelationCollection relations = SCSnapshotAdapter.Instance.QueryObjectAndRelationByIDs(SchemaInfo.FilterByCategory("Users", "Groups", "Organizations").ToSchemaNames(), ids, false, DateTime.MinValue); relations.FillDetails(); List <IOguObject> list = new List <IOguObject>(relations.Count); foreach (var item in relations) { SchemaObjectBase obj = item.Detail; if (obj != null) { IOguObject oguObj = obj.ToSimpleObject().ToOguObject(); list.Add(oguObj); } } return(new OguObjectCollection <IOguObject>(list)); }
/// <summary> /// 逐级检查父子关系 /// </summary> /// <param name="objs"></param> private static void ChildrenCheck(params SchemaObjectBase[] objs) { if (objs.Length > 0) { SchemaObjectBase prevObj = objs[0]; for (int i = 1; i < objs.Length; i++) { SchemaObjectBase currentObj = objs[i]; if (prevObj is ISCRelationContainer) { Assert.IsTrue(((ISCRelationContainer)prevObj).CurrentChildren.ContainsKey(currentObj.ID), "对象{0}({1})不是对象{2}({3})的子对象", currentObj.ID, currentObj.SchemaType, prevObj.ID, prevObj.SchemaType); } prevObj = currentObj; } } }
private void GenerateOneUserAndContainerSnapshot(ISCUserContainerObject container) { SchemaObjectBase obj = container as SchemaObjectBase; string objName = obj.Properties.GetValue("Name", string.Empty); string description = string.Format("对象\"{0}\"({1})", objName, obj.ID); ProcessProgress.Current.StatusText = string.Format("正在生成\"{0}\"({1})所包含的用户", objName, obj.Schema.Name); ProcessProgress.Current.Response(); try { SchemaObjectCollection currentUsers = container.GetCurrentUsers(); SchemaObjectCollection calculatedUsers = this.Calculate(SCConditionAdapter.Instance.Load(obj.ID), description); currentUsers.Merge(calculatedUsers); ProcessProgress.Current.StatusText = string.Format("正在提交\"{0}\"({1})的生成结果", objName, obj.Schema.Name); ProcessProgress.Current.MaxStep += calculatedUsers.Count; ProcessProgress.Current.Response(); ConditionCalculateResultAdapter.Instance.Update(obj.ID, calculatedUsers); UserAndContainerSnapshotAdapter.Instance.Merge(obj.ID, obj.SchemaType, currentUsers); } catch (System.Exception ex) { string exPrefix = string.Format("生成{0}时所包含的用户出错:", description); ProcessProgress.Current.Error.WriteLine("{0}: {1}", exPrefix, ex.ToString()); } finally { ProcessProgress.Current.Increment(); ProcessProgress.Current.Response(); } }
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 AddUserToRole(SCUser user, AdminUnit unit, AUSchemaRole role) { CheckUnitPermission(AUOperationType.RemoveUserFromRole, "EditRoleMembers", unit); SchemaObjectBase r = Adapters.AUSnapshotAdapter.Instance.LoadAURole(role.ID, unit.ID, true, DateTime.MinValue); if (r == null) { throw new AUObjectValidationException("没有找到此管理单元的角色,请尝试重新添加此角色"); } AUMemberRelativeExecutor executor = new Executors.AUMemberRelativeExecutor(AUOperationType.AddUserToRole, r, user) { SaveTargetData = false, NeedValidation = false, NeedContainerStatusCheck = this.NeedValidationAndStatusCheck, }; ExecuteWithActions(AUOperationType.AddUserToRole, () => SCActionContext.Current.DoActions(() => { executor.Execute(); })); }
public SCOrganization UpdateOrganization(SCOrganization org) { SCObjectExecutor executor = new SCObjectExecutor(SCOperationType.UpdateOrganization, org) { NeedValidation = this.NeedValidationAndStatusCheck, NeedStatusCheck = this.NeedValidationAndStatusCheck }; SchemaObjectBase parent = org.CurrentParents.FirstOrDefault(); if (parent != null) { CheckPermissions(SCOperationType.UpdateOrganization, parent.Schema, "UpdateChildren", parent.ID); } else { CheckSupervisorPermissions(SCOperationType.UpdateOrganization); } SCOrganization result = null; ExecuteWithActions(SCOperationType.UpdateOrganization, () => SCActionContext.Current.DoActions(() => result = (SCOrganization)executor.Execute())); return(result); }
public bool AreEqual(SyncSession session, PropertyMapping mapping, NameObjectCollection srcValues, SchemaObjectBase targetObj) { var srcValue = srcValues[mapping.SourceProperty] ?? Common.EmptyString; var targetString = targetObj.Properties[mapping.TargetProperty].StringValue; if (typeof(bool).IsAssignableFrom(srcValue.GetType())) { if (string.IsNullOrEmpty(targetString) == false) { return ((bool)srcValue).Equals(bool.Parse(targetString)); } else return false; // 左边对象有值,而右边对象没值 } else if (srcValue is string) { return string.Equals((string)srcValue, (string)targetString, StringComparison.OrdinalIgnoreCase); } else { return mapping.Parameters["sourceDefaultValue"] == targetString; //源对象为null或其他情形 } }
private static bool IsFunction(SchemaObjectBase command) { bool isFunction; string temp; foreach (var name in FunctionProperties) { if (!command.ExtendedProperties.Contains(name)) { continue; } temp = command.ExtendedProperties[name].Value.ToString(); bool.TryParse(temp, out isFunction); if (isFunction) { return(true); } } return(false); }
private void RenderAllTabs(SchemaObjectBase data, bool readOnly) { Dictionary <string, SchemaPropertyValueCollection> tabGroup = data.Properties.GroupByTab(); this.tabs.TabPages.Clear(); foreach (SchemaTabDefine tab in data.Schema.Tabs) { SchemaPropertyValueCollection properties = null; if (tabGroup.TryGetValue(tab.Name, out properties) == false) { properties = new SchemaPropertyValueCollection(); } this.RenderOnePanel(tab, properties, readOnly); } if (tabs.TabPages.Count > 0) { tabs.ActiveTabPageIndex = 0; } }
public void Drop(TextWriter writer, SchemaObjectBase schemaObject) { writer.WriteLine(string.Format("/****** Objet : [{0}].[{1}] Date de génération du script : {2} ******/", schemaObject.Owner, schemaObject.Name, DateTime.Now.ToLongDateString())); writer.Write("IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'"); writer.WriteLine(string.Format("[{0}].[{1}]')", schemaObject.Owner, schemaObject.Name)); if (schemaObject is CommandSchema) { writer.WriteLine("AND type in (N'P', N'PC'))"); } if (schemaObject is TableSchema) { writer.WriteLine("AND type in (N'U'))"); } if (schemaObject is ViewSchema) { writer.WriteLine("AND type in (N'V'))"); } writer.Write("DROP "); if (schemaObject is CommandSchema) { writer.Write("PROCEDURE"); } if (schemaObject is TableSchema) { writer.Write("TABLE"); } if (schemaObject is ViewSchema) { writer.Write("VIEW"); } writer.WriteLine(string.Format("[{0}].[{1}])", schemaObject.Owner, schemaObject.Name)); }
private void RenderAllTabs(SchemaObjectBase data, bool readOnly) { string defaultKey = this.tabStrip.SelectedKey; Dictionary <string, SchemaPropertyValueCollection> tabGroup = data.Properties.GroupByTab(); this.tabStrip.TabStrips.Clear(); foreach (SchemaTabDefine tab in data.Schema.Tabs) { SchemaPropertyValueCollection properties = null; if (tabGroup.TryGetValue(tab.Name, out properties) == false) { properties = new SchemaPropertyValueCollection(); } Control panel = this.RenderOnePanel(tab, this.panelContainer, properties, readOnly); TabStripItem item = new TabStripItem() { Key = tab.Name, Text = tab.Description, ControlID = panel.ClientID, Tag = panel.Controls[0].ClientID }; this.tabStrip.TabStrips.Add(item); if (defaultKey.IsNullOrEmpty()) { defaultKey = item.Key; } } if (defaultKey.IsNotEmpty()) { this.tabStrip.SelectedKey = defaultKey; } }
public ExtendedProperty[] GetExtendedProperties(string connectionString, SchemaObjectBase schemaObject) { //No extended properties in SQLite return new ExtendedProperty[0]; }
public AUMemberRelativeExecutor(AUOperationType opType, SchemaObjectBase container, SchemaObjectBase member) : base(opType, container, member) { }
protected override SCSimpleRelationBase CreateRelation(SchemaObjectBase container, SchemaObjectBase member) { return new SCMemberRelation(container, member); }
private void RenderAllTabs(SchemaObjectBase data, bool readOnly) { string defaultKey = this.tabStrip.SelectedKey; Dictionary<string, SchemaPropertyValueCollection> tabGroup = data.Properties.GroupByTab(); this.tabStrip.TabStrips.Clear(); foreach (SchemaTabDefine tab in data.Schema.Tabs) { SchemaPropertyValueCollection properties = null; if (tabGroup.TryGetValue(tab.Name, out properties) == false) properties = new SchemaPropertyValueCollection(); Control panel = this.RenderOnePanel(tab, this.panelContainer, properties, readOnly); TabStripItem item = new TabStripItem() { Key = tab.Name, Text = tab.Description, ControlID = panel.ClientID, Tag = panel.Controls[0].ClientID }; this.tabStrip.TabStrips.Add(item); if (defaultKey.IsNullOrEmpty()) defaultKey = item.Key; } if (defaultKey.IsNotEmpty()) this.tabStrip.SelectedKey = defaultKey; }
public ExtendedProperty[] GetExtendedProperties(string connectionString, SchemaObjectBase schemaObject) { return new ExtendedProperty[0]; }
private void PrepareRelationObject() { AUCommon.DoDbAction(() => { this.oldRelationToSchema = SchemaRelationObjectAdapter.Instance.Load(((AdminUnit)this.Data).AUSchemaID, this.Data.ID); this.oldRelationToUnit = SchemaRelationObjectAdapter.Instance.LoadByObjectID(this.Data.ID).Where(m => m.Status == SchemaObjectStatus.Normal && m.ParentSchemaType == AUCommon.SchemaAdminUnit).FirstOrDefault(); if (this.Data.Status == SchemaObjectStatus.Normal) //添加操作 { this.actualParent = inputParent != null ? SchemaObjectAdapter.Instance.Load(this.inputParent.ID) : this.schema; if (this.actualParent.ID == this.Data.ID) throw new AUObjectValidationException("管理单元的父管理单元不能是其自身。"); if (this.actualParent == null || this.actualParent.Status != SchemaObjectStatus.Normal) throw new AUObjectValidationException("指定的父管理单元在系统中不存在或已删除"); if (this.oldRelationToSchema != null && this.oldRelationToSchema.Status == SchemaObjectStatus.Normal && this.oldRelationToUnit != null && this.oldRelationToUnit.Status == SchemaObjectStatus.Normal) throw new AUObjectValidationException("关系错误。此管理单元已经存在,但存在错误的关联。一个管理单元不能同时与Schema和另一个管理单元关联"); else if (this.oldRelationToSchema != null && this.oldRelationToSchema.Status == SchemaObjectStatus.Normal && actualParent.ID != this.oldRelationToSchema.ParentID) throw new AUObjectValidationException("关系错误。此管理单元已经与另一个Schema关联。"); else if (this.oldRelationToUnit != null && this.oldRelationToUnit.Status == SchemaObjectStatus.Normal && actualParent.ID != this.oldRelationToUnit.ParentID) throw new AUObjectValidationException("关系错误。此管理单元已经与另一个AdminUnit关联。"); } else //删除操作,忽略传,m入的parent参数,因此需要查找真实的parent { if (oldRelationToUnit != null && oldRelationToUnit.Status == SchemaObjectStatus.Normal) { this.actualParent = SchemaObjectAdapter.Instance.Load(oldRelationToUnit.ParentID); } else if (oldRelationToSchema != null && oldRelationToSchema.Status == SchemaObjectStatus.Normal) { this.actualParent = schema; } } this.oldRelationToChildren = SchemaRelationObjectAdapter.Instance.LoadByParentID(this.Data.ID); if (actualParent is AUSchema) { // 应该是跟Schema关联 if (oldRelationToSchema != null && oldRelationToSchema.Status == SchemaObjectStatus.Normal) { relationExists = true; } targetRelation = new SCRelationObject(schema, this.Data) { Status = SchemaObjectStatus.Normal }; } else { targetRelation = SchemaRelationObjectAdapter.Instance.Load(actualParent.ID, this.Data.ID); if (targetRelation != null) { if (targetRelation.Status == SchemaObjectStatus.Normal) { relationExists = true; } targetRelation.Status = SchemaObjectStatus.Normal; } else { targetRelation = new SCRelationObject(actualParent, this.Data) { Status = SchemaObjectStatus.Normal }; } } }); }