protected override void DoWorkCore(LongOperation longOperation) { Random random = new Random(); IObjectSpace updatingObjectSpace = Application.CreateObjectSpace(typeof(FullyAuditedBatchCreationObject)); IList <FullyAuditedBatchCreationObject> collection = updatingObjectSpace.GetObjects <FullyAuditedBatchCreationObject>(); int index = 0; try { foreach (object currentObject in collection) { ((FullyAuditedBatchCreationObject)currentObject).InitializeObject(collection.Count - index); ((FullyAuditedBatchCreationObject)currentObject).Save(); if (index % 50 == 0) { updatingObjectSpace.CommitChanges(); } if (longOperation.Status == LongOperationStatus.InProgress) { longOperation.RaiseProgressChanged((int)((++index * 100) / collection.Count), "Modifying objects..."); } if (longOperation.Status == LongOperationStatus.Cancelling) { return; } } } catch (LongOperationTerminateException) { longOperation.CancelAsync(); } updatingObjectSpace.CommitChanges(); }
public override void UpdateDatabaseAfterUpdateSchema() { base.UpdateDatabaseAfterUpdateSchema(); // Disable version if (this.CurrentDBVersion != new Version("0.0.0.0")) { return; } // IObjectSpace os = ObjectSpace; Session ssn = ((ObjectSpace)os).Session; // "Наша" организация (она там одна) crmUserParty.CurrentUserParty = ValueManager.GetValueManager <crmUserParty>("UserParty"); XPQuery <crmUserParty> userParties = new XPQuery <crmUserParty>(ssn); var queryUP = (from userParty in userParties select userParty).ToList <crmUserParty>(); foreach (var up in queryUP) { crmUserParty.CurrentUserParty.Value = (crmUserParty)up; break; } // Исправление CashFlowRgister CashFlowFormed(ssn); os.CommitChanges(); // Исправление статусов заявок RepairRequestRestSum(ssn); os.CommitChanges(); }
public override void UpdateDatabaseAfterUpdateSchema() { base.UpdateDatabaseAfterUpdateSchema(); // Disable version if (this.CurrentDBVersion != new Version("0.0.0.0")) { return; } // IObjectSpace os = ObjectSpace; // Справочник Оснований платежа CreatePaymentBase(os); os.CommitChanges(); // Справочник КБК CreatePaymentKBK(os); os.CommitChanges(); // Справочник Типов платежа CreatePaymentKind(os); os.CommitChanges(); // Справочник "Периоды уплаты налога (сбора)" CreatePaymenTaxPeriod(os); os.CommitChanges(); }
public void CreateTransportOrder(int type, int ctrH, int ctrD, int lc, int IocpId, int weight, StorageLocation sourceLocation, StorageLocation targetLocation) { //Megkeressük az erőforrásokat CommonTrHeader ctrHeader = serverObjectSpace.FindObject <CommonTrHeader>(new BinaryOperator("Oid", ctrH)); CommonTrDetail cdetail = serverObjectSpace.FindObject <CommonTrDetail>(new BinaryOperator("Oid", ctrD)); LoadCarrier loadCarrier = serverObjectSpace.FindObject <LoadCarrier>(new BinaryOperator("Oid", lc)); Iocp iocp = serverObjectSpace.FindObject <Iocp>(new BinaryOperator("Oid", IocpId)); //Osztumk egy új sorszámot ushort UjTransportID = GetNewSorszam("TPO"); //Létrehozzuk az új transzportot az adatbázisban TransportOrder transportOrder = serverObjectSpace.CreateObject <TransportOrder>(); transportOrder.Iocp = iocp; transportOrder.TpId = UjTransportID; transportOrder.LC = loadCarrier; transportOrder.CommonTrHeader = ctrHeader; transportOrder.CommonDetail = cdetail; transportOrder.Type = type; transportOrder.TargetTag = iocp.TargetTag; transportOrder.SourceLocation = sourceLocation; transportOrder.TargetLocation = targetLocation; transportOrder.Weight = weight; serverObjectSpace.CommitChanges(); // Hozzáadjuk a megfelelő iocp zsák queue-hoz this.opcClient.addJob(transportOrder); }
private void SetTaskAction_Execute(object sender, SingleChoiceActionExecuteEventArgs e) { IObjectSpace objectSpace = View is ListView? Application.CreateObjectSpace(typeof(DemoTask)) : View.ObjectSpace; ArrayList objectsToProcess = new ArrayList(e.SelectedObjects); if (e.SelectedChoiceActionItem.ParentItem == setPriorityItem) { foreach (Object obj in objectsToProcess) { DemoTask objInNewObjectSpace = (DemoTask)objectSpace.GetObject(obj); objInNewObjectSpace.Priority = (Priority)e.SelectedChoiceActionItem.Data; } } else if (e.SelectedChoiceActionItem.ParentItem == setStatusItem) { foreach (Object obj in objectsToProcess) { DemoTask objInNewObjectSpace = (DemoTask)objectSpace.GetObject(obj); objInNewObjectSpace.Status = (TaskStatus)e.SelectedChoiceActionItem.Data; } } if (View is DetailView && ((DetailView)View).ViewEditMode == ViewEditMode.View) { objectSpace.CommitChanges(); } if (View is ListView) { objectSpace.CommitChanges(); View.ObjectSpace.Refresh(); } }
private void CreateUsersAndRoles() { PersistentRole adminRole = objectSpace.FindObject <PersistentRole>(new BinaryOperator("Name", "Administrators")); if (adminRole == null) { adminRole = objectSpace.CreateObject <PersistentRole>(); adminRole.Name = "Administrators"; adminRole.IsAdministrative = true; } if (objectSpace.FindObject <MyAppUser>(new BinaryOperator("UserName", XCRM.Module.Updater.AdministratorUserName)) == null) { MyAppUser administrator = objectSpace.CreateObject <MyAppUser>(); administrator.FirstName = XCRM.Module.Updater.AdministratorUserName; administrator.LastName = XCRM.Module.Updater.AdministratorUserName; ((DCUser)administrator).UserName = XCRM.Module.Updater.AdministratorUserName; administrator.IsActive = true; administrator.Roles.Add(adminRole); } if (objectSpace.FindObject <MyAppUser>(new BinaryOperator("UserName", "User1")) == null) { MyAppUser user = objectSpace.CreateObject <MyAppUser>(); user.FirstName = "User1"; user.LastName = "User1"; ((DCUser)user).UserName = "******"; user.IsActive = true; user.Roles.Add(adminRole); } objectSpace.CommitChanges(); }
public static async Task Map_Two_New_Entity <TCloudEntity, TLocalEntity>(this IObjectSpace objectSpace, Func <IObjectSpace, int, TLocalEntity> localEntityFactory, TimeSpan timeout, Func <IObjectSpace, IObservable <TCloudEntity> > synchronize, Action <TLocalEntity, TCloudEntity, int> assert) { var map = synchronize(objectSpace).Take(2).SubscribeReplay(); var localEntity1 = localEntityFactory(objectSpace, 0); objectSpace.CommitChanges(); await map.FirstAsync().Select((cloudEntity, i) => { assert(localEntity1, cloudEntity, 0); return(Unit.Default); }) .TakeUntil(objectSpace.WhenDisposed()) .Timeout(timeout); // map = synchronize(objectSpace).FirstAsync().SubscribeReplay(); var localEntity2 = localEntityFactory(objectSpace, 1); objectSpace.CommitChanges(); await map.LastAsync().Select((cloudEntity, i) => { assert(localEntity2, cloudEntity, 1); return(Unit.Default); }) .TakeUntil(objectSpace.WhenDisposed()) .Timeout(timeout); }
public static async Task Map_Existing_Entity_Two_Times <TCloudEntity, TLocalEntity>(this IObjectSpace objectSpace, TLocalEntity localEntity, Action <TLocalEntity, int> modifyLocalEntity, TCloudEntity newCloudEntity, Func <IObjectSpace, IObservable <TCloudEntity> > synchronize, Func <TLocalEntity, TCloudEntity, Task> assert, TimeSpan timeout) { localEntity = objectSpace.GetObject(localEntity); await objectSpace.NewCloudObject(localEntity, newCloudEntity).ToTaskWithoutConfigureAwait(); var map = synchronize(objectSpace).SubscribePublish(); modifyLocalEntity(localEntity, 0); objectSpace.CommitChanges(); await map.Take(1).SelectMany((cloudEntity, i) => assert(localEntity, cloudEntity).ToObservable()) .Timeout(timeout).ToTaskWithoutConfigureAwait(); modifyLocalEntity(localEntity, 1); objectSpace.CommitChanges(); await map.Take(1).Select((cloudEntity, i) => { assert(localEntity, cloudEntity); return(Unit.Default); }) .Timeout(timeout); }
private void UpdatePhotosFromReusableStorage() { var xmlUnitOfWork = GetXmlUnitOfWork(); _objectSpace.CommitChanges(); foreach (var type in new[] { typeof(Customer), typeof(Movie), typeof(Country), typeof(MoviePicture), typeof(ArtistPicture) }) { string memberName = type.Name + "Id"; Func <VideoRentalBaseObject, object> parameters = o => o.GetMemberValue("Id"); if (type == typeof(Country)) { memberName = "Name"; parameters = o => o.GetMemberValue(memberName); } else if (type == typeof(MoviePicture)) { memberName = "Movie.MovieId"; parameters = o => ((XPBaseObject)o.GetMemberValue("Movie")).GetMemberValue("Id"); } else if (type == typeof(ArtistPicture)) { memberName = "Artist.ArtistId"; parameters = o => ((XPBaseObject)o.GetMemberValue("Artist")).GetMemberValue("Id"); } UpdateImage(type, xmlUnitOfWork, memberName, parameters); } _objectSpace.CommitChanges(); }
private void GrabCustomer_Execute(object sender, SimpleActionExecuteEventArgs e) { if (e.SelectedObjects.Count > 0) { if (this.GetAvailableSnatchLimit(SecuritySystem.CurrentUserName) >= e.SelectedObjects.Count) { using (IObjectSpace os = Application.CreateObjectSpace()) { SalesRep SR = os.FindObject <SalesRep>(new BinaryOperator("SalesRepCode", SecuritySystem.CurrentUserName.ToUpper())); if (SR == null) { SR = os.CreateObject <SalesRep>(); SR.SalesRepCode = SecuritySystem.CurrentUserName; os.CommitChanges(); } foreach (CustomerRelease selectedCustomer in e.SelectedObjects) { CustomerRelease custr = os.GetObject <CustomerRelease>(selectedCustomer); custr.AquiredBy = SecuritySystem.CurrentUserName.ToUpper(); custr.AquiredDate = DateTime.Now; Customer cust = os.FindObject <Customer>(new BinaryOperator("Oid", custr.Customer)); cust.SalesRep = SR; cust.SalesRepAssignedDt = DateTime.Now; } os.CommitChanges(); ((ListView)View).CollectionSource.Reload(); } } } }
private void addHangMuc_Execute(object sender, PopupWindowShowActionExecuteEventArgs e) { if (objspc != null) { objspc.CommitChanges(); } View.ObjectSpace.Refresh(); }
public void CreateTimedObject(IObjectSpace objSpace) { var obj1 = objSpace.CreateObject <TimedObject1>(); objSpace.CommitChanges(); var obj2 = objSpace.CreateObject <TimedObject1>(); objSpace.CommitChanges(); }
public override void InsertEmptyContact(int recordsCount) { ICustomPermissionPolicyUser currentUser = GetUser(); for (int i = 1; i < recordsCount + 1; i++) { var contact = securedObjectSpace.CreateObject <ContactType>(); contact.SetDepartment(currentUser.Department); contact.FirstName = $"Contact{i}"; } securedObjectSpace.CommitChanges(); }
public override object Authenticate(IObjectSpace objectSpace) { string systemUserName = WindowsIdentity.GetCurrent().Name; string enteredUserName = ((AuthenticationStandardLogonParameters)LogonParameters).UserName; if (string.IsNullOrEmpty(enteredUserName)) { throw new ArgumentException(SecurityExceptionLocalizer.GetExceptionMessage(SecurityExceptionId.UserNameIsEmpty)); } if (!String.Equals(systemUserName, enteredUserName)) { throw new AuthenticationException(enteredUserName, "Invalid user name"); } object user = objectSpace.FindObject(UserType, new BinaryOperator("UserName", systemUserName)); if (user == null) { user = objectSpace.CreateObject(UserType); ((IAuthenticationActiveDirectoryUser)user).UserName = systemUserName; bool strictSecurityStrategyBehavior = SecurityModule.StrictSecurityStrategyBehavior; SecurityModule.StrictSecurityStrategyBehavior = false; objectSpace.CommitChanges(); SecurityModule.StrictSecurityStrategyBehavior = strictSecurityStrategyBehavior; } if (!((IAuthenticationStandardUser)user).ComparePassword(((AuthenticationStandardLogonParameters)LogonParameters).Password)) { throw new AuthenticationException(systemUserName, SecurityExceptionLocalizer.GetExceptionMessage(SecurityExceptionId.RetypeTheInformation)); } return user; }
int ImportObjects(XDocument document, IObjectSpace objectSpace) { _objectSpace = objectSpace; if (document.Root != null) { foreach (XElement element in document.Root.Nodes().OfType <XElement>()) { using (IObjectSpace nestedObjectSpace = objectSpace.CreateNestedObjectSpace()) { ITypeInfo typeInfo = GetTypeInfo(element); if (typeInfo != null) { var keys = GetKeys(element); CriteriaOperator objectKeyCriteria = GetObjectKeyCriteria(typeInfo, keys); if (!ReferenceEquals(objectKeyCriteria, null)) { CreateObject(element, nestedObjectSpace, typeInfo, objectKeyCriteria); nestedObjectSpace.CommitChanges(); } } } } objectSpace.CommitChanges(); } return(0); }
public override void ExecuteBusinessLogic(IObjectSpace objectSpace) { if (string.IsNullOrEmpty(Usuario)) { throw new ArgumentException("Usuario no especificado"); } if (Usuario == "Admin") { throw new ArgumentException("Usuario no especificado"); } Usuario usuario = objectSpace.FindObject <Usuario>(new BinaryOperator("UserName", Usuario)); if (usuario == null) { throw new ArgumentException("No se encontró el usuario proporcionado"); } byte[] randomBytes = new byte[8]; new RNGCryptoServiceProvider().GetBytes(randomBytes); string password = Convert.ToBase64String(randomBytes); usuario.SetPassword(password); usuario.ChangePasswordOnFirstLogon = true; objectSpace.CommitChanges(); // EmailLoginInformation(usuario.Email, password); RegistrarReseteo.Registrar(usuario.Oid); }
public static void CreateAdminUser(IObjectSpace ObjectSpace, string FirstName, string LastName, string EmailAddress, string Password) { try { _objectSpace = ObjectSpace; _employee = ObjectSpace.FindObject <Employee>(new BinaryOperator("UserName", EmailAddress)); _employeeRole = ObjectSpace.FindObject <EmployeeRole>(new BinaryOperator("Name", SecurityStrategy.AdministratorRoleName)); if (_employeeRole == null) { _employeeRole = ObjectSpace.CreateObject <EmployeeRole>(); _employeeRole.Name = SecurityStrategy.AdministratorRoleName; _employeeRole.IsAdministrative = true; } if (_employee == null) { _employee = ObjectSpace.CreateObject <Employee>(); _employee.FirstName = FirstName; _employee.LastName = LastName; _employee.Email = EmailAddress; _employee.UserName = EmailAddress; _employee.SetPassword(Password); _employee.EmployeeType = EmployeeType.SystemUser; _employee.EmployeeRoles.Add(_employeeRole); _objectSpace.CommitChanges(); } } catch (Exception ex) { throw ex; } }
private void UpdateEditAllRole() { using (IObjectSpace os = ObjectSpace.CreateNestedObjectSpace()) { csCSecurityRole EditAllRole = os.FindObject <csCSecurityRole>( new BinaryOperator("Name", ConfigurationManager.AppSettings["SecurityGroups.EditAllRole"]), true); if (EditAllRole == null) { EditAllRole = os.CreateObject <csCSecurityRole>(); EditAllRole.Name = ConfigurationManager.AppSettings["SecurityGroups.EditAllRole"]; } EditAllRole.BeginUpdate(); // EditAllRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Read); EditAllRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Write); EditAllRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Create); EditAllRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Delete); EditAllRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Navigate); // EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityRole), SecurityOperations.Read); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityRole), SecurityOperations.Write); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityRole), SecurityOperations.Create); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityRole), SecurityOperations.Delete); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityRole), SecurityOperations.Navigate); // EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityUser), SecurityOperations.Read); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityUser), SecurityOperations.Write); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityUser), SecurityOperations.Create); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityUser), SecurityOperations.Delete); EditAllRole.Permissions.DenyRecursive(typeof(IntecoAG.ERM.CS.Security.csCSecurityUser), SecurityOperations.Navigate); // EditAllRole.EndUpdate(); os.CommitChanges(); } }
/// <summary> /// Обновим права администратора, для политики Windows Autentication пользователь с административными /// правами создается автоматически, а вот список прав не обновляется /// Паша!!! Реализация не учитывает вариантов в системе безопасности и использует стандартный класс роли /// или его производные /// </summary> private void UpdateAdminRole() { using (IObjectSpace os = ObjectSpace.CreateNestedObjectSpace()) { csCSecurityRole administratorRole = os.FindObject <csCSecurityRole>( new BinaryOperator("Name", SecurityStrategy.AdministratorRoleName), true); if (administratorRole == null) { administratorRole = os.CreateObject <csCSecurityRole>(); administratorRole.Name = SecurityStrategy.AdministratorRoleName; ModelOperationPermissionData modelPermission = os.CreateObject <ModelOperationPermissionData>(); administratorRole.PersistentPermissions.Add(modelPermission); } administratorRole.BeginUpdate(); administratorRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Read); administratorRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Write); administratorRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Create); administratorRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Delete); administratorRole.Permissions.GrantRecursive(typeof(object), SecurityOperations.Navigate); administratorRole.EndUpdate(); if (administratorRole.Users.Count == 0) { // Паша !!! Неустойчивый вариант, нужен код определяющий тип User по конфигу Application csCSecurityUser user = os.FindObject <csCSecurityUser>( new BinaryOperator("UserName", ConfigurationManager.AppSettings["DefaultAdminName"])); if (user != null) { user.Roles.Add(administratorRole); } } os.CommitChanges(); } }
private void UpdateContractDeals() { using (IObjectSpace os = ObjectSpace.CreateNestedObjectSpace()) { crmUserParty cfr = os.GetObjects <crmUserParty>().FirstOrDefault(x => x.Party.Code == "2518"); cfr.TrwCode = "15"; IList <crmContractDeal> deals = os.GetObjects <crmContractDeal>(); foreach (crmContractDeal deal in deals) { if (deal.Current != null) { if (deal.Current.Customer != null) { deal.Current.Customer.ContractDeal = deal; deal.Current.Customer.TrwContractPartyType = TrwContractPartyType.PARTY_CUSTOMER; if (cfr.Party == deal.Current.Customer.Party) { deal.Current.Customer.CfrUserParty = cfr; } } if (deal.Current.Supplier != null) { deal.Current.Supplier.ContractDeal = deal; deal.Current.Supplier.TrwContractPartyType = TrwContractPartyType.PARTY_SUPPLIER; if (cfr.Party == deal.Current.Supplier.Party) { deal.Current.Supplier.CfrUserParty = cfr; } } } } os.CommitChanges(); } }
private void NameIsUniqueForAClass <T>(IObjectSpace objectSpace) where T : IPersistentMemberInfo { var memberInfo = objectSpace.Create <T>(); memberInfo.Name = "name"; var persistentClassInfo = objectSpace.Create <IPersistentClassInfo>(); memberInfo.Owner = persistentClassInfo; memberInfo = objectSpace.Create <T>(); memberInfo.Name = "name"; memberInfo.Owner = objectSpace.Create <IPersistentClassInfo>(); objectSpace.CommitChanges(); var usedProperties = nameof(memberInfo.Name); Validator.RuleSet.StateOf <RuleCombinationOfPropertiesIsUnique>(memberInfo, usedProperties) .Should() .Be(ValidationState.Valid); memberInfo.Owner = persistentClassInfo; Validator.RuleSet.StateOf <RuleCombinationOfPropertiesIsUnique>(memberInfo, usedProperties) .Should() .Be(ValidationState.Invalid); }
private void DeleteBarButtonItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { object cellObject = employeeGridView.GetRow(employeeGridView.FocusedRowHandle); securedObjectSpace.Delete(cellObject); securedObjectSpace.CommitChanges(); }
private void MinMaint_Execute(object sender, PopupWindowShowActionExecuteEventArgs e) { e.PopupWindow.View.ObjectSpace.CommitChanges(); IObjectSpace objectSpace = Application.CreateObjectSpace(); // Items item = objectSpace.CreateObject<Items>(); ItemMinChangeHistory currentMinChange = objectSpace.GetObject <ItemMinChangeHistory>((ItemMinChangeHistory)e.PopupWindowViewCurrentObject); //item = objectSpace.GetObject<Items>((Items)View.CurrentObject); //item.MinPrice = currentMinChange.ItemMin; //item.Save(); currentMinChange.Item.MinPrice = currentMinChange.ItemMin; currentMinChange.Save(); objectSpace.CommitChanges(); View.ObjectSpace.Refresh(); View.Refresh(); // item.MinPrice = e.PopupWindow.View<ItemMinHistory>.CurrentObject.ItemMin; MessageOptions options = new MessageOptions(); options.Duration = 20000; options.Message = string.Format("Min has been changed for Item: {0} to {1}", currentMinChange.Item.ItemNumber, currentMinChange.ItemMin.ToString()); options.Type = InformationType.Success; options.Web.Position = InformationPosition.Right; options.Win.Caption = "Success"; options.Win.Type = WinMessageType.Alert; options.Duration = 10000; Application.ShowViewStrategy.ShowMessage(options); }
public static async Task Populate_All <TEntity>(this IObjectSpace objectSpace, string syncToken, Func <CloudOfficeTokenStorage, IObservable <TEntity> > listEvents, TimeSpan timeout, Action <IObservable <TEntity> > assert, IObjectSpaceProvider assertTokenStorageProvider = null) { var tokenStorage = objectSpace.CreateObject <CloudOfficeTokenStorage>(); tokenStorage.Token = syncToken; tokenStorage.EntityName = typeof(TEntity).FullName; objectSpace.CommitChanges(); var storageOid = tokenStorage.Oid; var events = listEvents(tokenStorage).SubscribeReplay(); await events.Timeout(timeout); if (assertTokenStorageProvider != null) { using (var space = assertTokenStorageProvider.CreateObjectSpace()){ tokenStorage = space.GetObjectsQuery <CloudOfficeTokenStorage>() .First(storage => storage.Oid == storageOid); tokenStorage.Token.ShouldNotBeNull(); tokenStorage.Token.ShouldNotBe(syncToken); } } assert(events); }
private object AuthenticateActiveDirectory(IObjectSpace objectSpace) { var windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity != null) { string userName = windowsIdentity.Name; var user = (IAuthenticationActiveDirectoryUser)objectSpace.FindObject(UserType, new BinaryOperator("UserName", userName)); if (user == null) { if (_createUserAutomatically) { var args = new CustomCreateUserEventArgs(objectSpace, userName); if (!args.Handled) { user = (IAuthenticationActiveDirectoryUser)objectSpace.CreateObject(UserType); user.UserName = userName; if (Security != null) { //Security.InitializeNewUser(objectSpace, user); Security.CallMethod("InitializeNewUser", new object[] { objectSpace, user }); } } objectSpace.CommitChanges(); } } if (user == null) { throw new AuthenticationException(userName); } return(user); } return(null); }
public void Process(XafApplication application, IObjectSpace objectSpace) { var user = objectSpace.FindObject(XpandModuleBase.UserType, new GroupOperator(GroupOperatorType.Or, new BinaryOperator("UserName", UserName), new BinaryOperator("Email", Email)), true) as IAuthenticationStandardUser; if (user != null && !objectSpace.IsNewObject(user)) { throw new UserFriendlyException(CaptionHelper.GetLocalizedText(XpandSecurityModule.XpandSecurity, "AlreadyRegistered")); } var securityUserWithRoles = objectSpace.IsNewObject(user)? (ISecurityUserWithRoles)user : (ISecurityUserWithRoles)objectSpace.CreateObject(XpandModuleBase.UserType); User = securityUserWithRoles; var userTypeInfo = application.TypesInfo.FindTypeInfo(XpandModuleBase.UserType); var modelRegistration = (IModelRegistration)((IModelOptionsRegistration)application.Model.Options).Registration; AddRoles(modelRegistration, userTypeInfo, securityUserWithRoles, objectSpace); userTypeInfo.FindMember("UserName").SetValue(securityUserWithRoles, UserName); userTypeInfo.FindMember("IsActive").SetValue(securityUserWithRoles, modelRegistration.ActivateUser); modelRegistration.EmailMember.MemberInfo.SetValue(securityUserWithRoles, Email); var activationLinkMember = modelRegistration.ActivationIdMember; if (activationLinkMember != null) { activationLinkMember.MemberInfo.SetValue(securityUserWithRoles, Guid.NewGuid().ToString()); } securityUserWithRoles.CallMethod("SetPassword", new [] { typeof(string) }, Password); objectSpace.CommitChanges(); }
private void CopyBooking_Execute(object sender, SimpleActionExecuteEventArgs e) { var bookingToCopy = e.CurrentObject as IBooking; if (bookingToCopy == null) { return; } _currentObjectSpace = Application.CreateObjectSpace(); var newBooking = _currentObjectSpace.CreateObject <IBooking>(); bookingToCopy = _currentObjectSpace.GetObject(bookingToCopy); newBooking.Customer = bookingToCopy.Customer; newBooking.Date = DateTime.Today; newBooking.Employee = bookingToCopy.Employee; newBooking.StartTime = bookingToCopy.StartTime; newBooking.EndTime = bookingToCopy.EndTime; newBooking.IgnoreWeekendAndHolidays = bookingToCopy.IgnoreWeekendAndHolidays; newBooking.Project = bookingToCopy.Project; newBooking.Repetition = bookingToCopy.Repetition; newBooking.Task = bookingToCopy.Task; newBooking.TaskDescription = bookingToCopy.TaskDescription; _currentObjectSpace.CommitChanges(); ObjectSpace.Refresh(); }
public void CreateUserFriendlyIdObject(IObjectSpace objSpace) { var obj1 = objSpace.CreateObject <UserFriendlyIdObject1>(); var id = obj1.SequentialNumber; objSpace.CommitChanges(); }
public override void UpdateDatabaseAfterUpdateSchema() { base.UpdateDatabaseAfterUpdateSchema(); // Disable version if (this.CurrentDBVersion != new Version("0.0.0.0")) { return; } // using (IObjectSpace os = ObjectSpace.CreateNestedObjectSpace()) { csValuta val_rub = os.FindObject <csValuta>( XPQuery <csValuta> .TransformExpression(((ObjectSpace)os).Session, val => val.Code == "RUB")); // fmCAVTInvoiceVersion ver; IList <fmCAVTInvoiceVersion> ver_list = os.GetObjects <fmCAVTInvoiceVersion>( XPQuery <fmCAVTInvoiceVersion> .TransformExpression(((ObjectSpace)os).Session, inv => inv.Valuta == null)); foreach (fmCAVTInvoiceVersion ver in ver_list) { ver.Valuta = val_rub; } os.CommitChanges(); } using (IObjectSpace os = ObjectSpace.CreateNestedObjectSpace()) { IList <fmCAVTInvoiceBase> inv_list = os.GetObjects <fmCAVTInvoiceBase>(new UnaryOperator(UnaryOperatorType.IsNull, "InvoiceIntType")); foreach (fmCAVTInvoiceBase inv in inv_list) { inv.InvoiceIntType = fmCAVTInvoiceIntType.NORMAL; } os.CommitChanges(); } ObjectSpace.CommitChanges(); }
public PersistentAssemblyInfo Build(string customer, string order, string orderLine, string name) { var persistentAssemblyInfo = _objectSpace.CreateObject <PersistentAssemblyInfo>(); persistentAssemblyInfo.Name = name; var customerClassInfo = persistentAssemblyInfo.CreateClass(customer); customerClassInfo.BaseTypeFullName = GetInheritance(customerClassInfo).FullName; var orderClassInfo = persistentAssemblyInfo.CreateClass(order); orderClassInfo.BaseTypeFullName = GetInheritance(orderClassInfo).FullName; orderClassInfo.CreateReferenceMember(customerClassInfo, true); GetOrderTemplateInfos(orderClassInfo, customer).Each(info => orderClassInfo.TemplateInfos.Add(info)); var orderLineClassInfo = persistentAssemblyInfo.CreateClass(orderLine); orderLineClassInfo.BaseTypeFullName = GetInheritance(orderLineClassInfo).FullName; orderLineClassInfo.CreateReferenceMember(orderClassInfo, true); GetOrderLineTemplateInfos(orderLineClassInfo, order).Each(info => orderLineClassInfo.TemplateInfos.Add(info)); _objectSpace.CommitChanges(); return(persistentAssemblyInfo); }
private static void UpdateDatabase(IObjectSpace objectSpace) { PermissionPolicyUser userAdmin = objectSpace.CreateObject <PermissionPolicyUser>(); userAdmin.UserName = "******"; userAdmin.SetPassword(""); PermissionPolicyRole adminRole = objectSpace.CreateObject <PermissionPolicyRole>(); adminRole.IsAdministrative = true; userAdmin.Roles.Add(adminRole); PermissionPolicyUser userJohn = objectSpace.CreateObject <PermissionPolicyUser>(); userJohn.UserName = "******"; PermissionPolicyRole userRole = objectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Users")); userRole = objectSpace.CreateObject <PermissionPolicyRole>(); userRole.AddObjectPermission <Person>(SecurityOperations.Read, "[FirstName] == 'User person'", SecurityPermissionState.Allow); userJohn.Roles.Add(userRole); Person adminPerson = objectSpace.FindObject <Person>(new BinaryOperator("FirstName", "Person for Admin")); adminPerson = objectSpace.CreateObject <Person>(); adminPerson.FirstName = "Admin person"; Person userPerson = objectSpace.CreateObject <Person>(); userPerson.FirstName = "User person"; objectSpace.CommitChanges(); }
public static void InitializeSecurity(IObjectSpace objectSpace) { var defaultRole = objectSpace.GetDefaultRole(); var administratorRole = objectSpace.GetAdminRole("Administrator"); var modelRole = objectSpace.GetDefaultModelRole("ModelDifference"); objectSpace.GetUser("Admin", "Admin", administratorRole); objectSpace.GetUser("User", "", defaultRole, modelRole); objectSpace.CommitChanges(); }
public static void InitializeSecurity(IObjectSpace objectSpace) { var defaultRole = objectSpace.GetDefaultRole(); var administratorRole = objectSpace.GetAdminRole("Administrator"); var modelRole = objectSpace.GetDefaultModelRole("ModelDifference"); var user = objectSpace.GetUser("Admin", "Admin", administratorRole); UserFilterProvider.UpdaterUserKey = ((SecuritySystemUser)user).Oid; user = objectSpace.GetUser("User", "", defaultRole, modelRole); UserFilterProvider.UpdaterUserKey = ((SecuritySystemUser)user).Oid; objectSpace.CommitChanges(); }
int ImportObjects(XDocument document, IObjectSpace objectSpace) { _objectSpace = objectSpace; if (document.Root != null) { foreach (XElement element in document.Root.Nodes().OfType<XElement>()) { using (IObjectSpace nestedObjectSpace = objectSpace.CreateNestedObjectSpace()) { ITypeInfo typeInfo = GetTypeInfo(element); if (typeInfo != null) { var keys = GetKeys(element); CriteriaOperator objectKeyCriteria = GetObjectKeyCriteria(typeInfo, keys); if (!ReferenceEquals(objectKeyCriteria, null)) { CreateObject(element, nestedObjectSpace, typeInfo, objectKeyCriteria); nestedObjectSpace.CommitChanges(); } } } } objectSpace.CommitChanges(); } return 0; }
public void Process(XafApplication application,IObjectSpace objectSpace) { var user = objectSpace.FindObject(XpandModuleBase.UserType, new GroupOperator(GroupOperatorType.Or,new BinaryOperator("UserName", UserName),new BinaryOperator("Email",Email)),true) as IAuthenticationStandardUser; if (user != null&&!objectSpace.IsNewObject(user)) throw new ArgumentException(CaptionHelper.GetLocalizedText(XpandSecurityModule.XpandSecurity, "AlreadyRegistered")); var securityUserWithRoles = objectSpace.IsNewObject(user)? (ISecurityUserWithRoles) user : (ISecurityUserWithRoles)objectSpace.CreateObject(XpandModuleBase.UserType); User = securityUserWithRoles; var userTypeInfo = application.TypesInfo.FindTypeInfo(XpandModuleBase.UserType); var modelRegistration = (IModelRegistration)((IModelOptionsRegistration)application.Model.Options).Registration; AddRoles(modelRegistration, userTypeInfo, securityUserWithRoles, objectSpace); userTypeInfo.FindMember("UserName").SetValue(securityUserWithRoles,UserName); userTypeInfo.FindMember("IsActive").SetValue(securityUserWithRoles,modelRegistration.ActivateUser); modelRegistration.EmailMember.MemberInfo.SetValue(securityUserWithRoles,Email); var activationLinkMember = modelRegistration.ActivationIdMember; if (activationLinkMember!=null) { activationLinkMember.MemberInfo.SetValue(securityUserWithRoles, Guid.NewGuid().ToString()); } securityUserWithRoles.CallMethod("SetPassword", Password); objectSpace.CommitChanges(); }
private void ExecuteModule(IDynamicModule module, ExecuteCommand command, IObjectSpace os, IExamination examination) { // Определяем идентификатор приложения которое будет открывать файл обследования // Для модулей которые могут работать с несколькими приложениями Guid soft = examination.ExaminationSoftType.ExaminationSoftTypeId; // Получаем имя РЕАЛЬНОГО файла обследования из базы !!! string file = examination.ExaminationFile.RealFileName; Guid context = (examination as DevExpress.ExpressApp.DC.DCBaseObject).Oid; if (System.IO.File.Exists(file) == true) {// если файл удалось найти в том месте, где он должен быть if (FileWatcher.GetFileState(file) == FileState.Close) {// если файл никем не используется т.е закрыт if (new FileInfo(file).Length == 0) {// если файл обследования по какой то причине пустой, то открываем его как новый // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; PatientData data = GetFromExamination(examination); if (TryToExecuteModule(module, ExecuteCommand.New, file, context, data) == false) {// если при запуске приложения возникла ошибка // удаляем обследование если его можно удалять if (examination.AllowEmptyOrNotExistsFile == false) os.Delete(examination); string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } if (os.IsModified == true) os.CommitChanges(); } else {// Если файл не пустой // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; if (TryToExecuteModule(module, command, file, context) == false) { string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } if (os.IsModified == true) os.CommitChanges(); } } else {// если файл в момент записи открыт где то еще string message = "Ошибка доступа к файлу обследования!\nВозможно файл открыт внешним приложением или нет прав доступа"; //CaptionHelper.GetLocalizedText("Warnings", "RequiredExaminationIsAlreadyLaunched"); XtraMessageBox.Show(message, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return; } } else // АХТУНГ !!! НАДО УДАЛЯТЬ ОБСЛЕДОВАНИЯ СОДЕРЖАШИЕ УДАЛЕННЫЕ ФАЙЛЫ ИЛИ НЕ НАДО ?!!?!?!? {// если реального файла нет - создаем новый пустой файл using (Stream stream = File.Create(file)) { }; // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; PatientData data = GetFromExamination(examination); TryToExecuteModule(module, ExecuteCommand.New, file, context, data); } os.Refresh(); }
protected virtual void CloseObjectSpace(IObjectSpace objectSpace, bool success) { if (objectSpace != null && !objectSpace.IsDisposed) { if (success) { objectSpace.CommitChanges(); } else { objectSpace.Rollback(); } objectSpace.Dispose(); } }
/// <summary> /// Uploads pending XafDelta messages to intermidiate net storages. /// </summary> /// <param name="xafDeltaModule">The xaf delta module.</param> /// <param name="objectSpace">The object space.</param> /// <param name="worker">The worker.</param> public void Upload(XafDeltaModule xafDeltaModule, IObjectSpace objectSpace, ActionWorker worker) { worker.ReportProgress(Localizer.UploadStarted); var transportList = (from m in XafDeltaModule.XafApp.Modules where m is IXafDeltaTransport && ((IXafDeltaTransport)m).UseForUpload select m).Cast<IXafDeltaTransport>().ToList().AsReadOnly(); if (transportList.Count > 0) { var replicas = (from r in objectSpace.GetObjects<Package>() where r.IsOutput && r.GetEventDateTime(PackageEventType.Sent) == DateTime.MinValue orderby r.PackageDateTime select r).ToList(); var tickets = (from t in objectSpace.GetObjects<Ticket>(CriteriaOperator.Parse("IsNull(ProcessingDateTime)"), true) where t.Package != null && t.Package.IsInput orderby t.TicketDateTime select t).ToList(); var messages = replicas.Cast<IReplicationMessage>().Union(tickets.Cast<IReplicationMessage>()).ToList(); var uploadData = new Dictionary<IXafDeltaTransport, List<IReplicationMessage>>(); worker.ReportProgress(string.Format(Localizer.FoundForUpload, messages.Count())); foreach (var message in messages.TakeWhile(x => !worker.CancellationPending)) { var args = new SelectUploadTransportArgs(message, transportList[0]); Owner.OnSelectUploadTransport(args); if(args.Transport != null) { List<IReplicationMessage> list; if(!uploadData.TryGetValue(args.Transport, out list)) { list = new List<IReplicationMessage>(); uploadData.Add(args.Transport, list); } list.Add(message); } } if(!worker.CancellationPending && uploadData.Keys.Count > 0) { foreach (var transport in uploadData.Keys.TakeWhile(x => !worker.CancellationPending)) { try { worker.ReportProgress(string.Format(Localizer.OpenTransport, transport)); transport.Open(TransportMode.Upload, worker); var messageList = uploadData[transport]; foreach (var message in messageList) { var recipientAddress = message.RecipientAddress; // worker.ReportProgress(string.Format(Localizer.UploadingFile, message)); transport.UploadFile(message.ToString(), message.GetData(), recipientAddress, worker); if (message is Package) ((Package)message).CreateLogRecord(PackageEventType.Sent); else ((Ticket) message).ProcessingDateTime = DateTime.Now; objectSpace.CommitChanges(); } } catch (Exception exception) { objectSpace.Rollback(); worker.ReportError(Localizer.UploadError, exception.Message); } finally { worker.ReportProgress(string.Format(Localizer.CloseTransport, transport)); transport.Close(); } } } } else worker.ReportProgress(Color.BlueViolet, Localizer.UploadTransportNotFound); worker.ReportProgress(Color.Blue, Localizer.UploadFinished); }
/// <summary> /// Downloads XafDelta messages into replication storage database. /// </summary> /// <param name="xafDeltaModule">The xaf delta module.</param> /// <param name="objectSpace">The object space.</param> /// <param name="worker">The worker.</param> public void Download(XafDeltaModule xafDeltaModule, IObjectSpace objectSpace, ActionWorker worker) { worker.ReportProgress(Localizer.DownloadStarted); var transportList = (from m in xafDeltaModule.ModuleManager.Modules where m is IXafDeltaTransport && ((IXafDeltaTransport) m).UseForDownload select m).Cast<IXafDeltaTransport>().ToList(); worker.ReportProgress(string.Format(Localizer.TransportFound, transportList.Count())); foreach (var transport in transportList.TakeWhile(x => !worker.CancellationPending)) { worker.ReportProgress(string.Format(Localizer.DownloadUsing, transport)); try { worker.ReportProgress(string.Format(Localizer.OpenTransport, transport)); transport.Open(TransportMode.Download, worker); var existingReplicaNames = from c in objectSpace.GetObjects<Package>() select c.FileName; var fileNames = transport.GetFileNames(worker, @"(" + Ticket.FileMask + "|" + Package.FileMask + ")").ToList(); fileNames = fileNames.Except(existingReplicaNames).ToList(); worker.ReportProgress(string.Format(Localizer.FilesForDownload, fileNames.Count)); foreach (var fileName in fileNames.TakeWhile(x => !worker.CancellationPending)) { // worker.ReportProgress(string.Format(Localizer.DownloadFile, fileName)); var fileData = transport.DownloadFile(fileName, worker); if(fileData != null && fileData.Length > 0) { if (fileName.EndsWith(Package.PackageFileExtension)) { var replica = Package.ImportFromBytes(objectSpace, fileName, fileData); replica.Save(); } else { var replicaTicket = Ticket.ImportTicket(objectSpace, fileData); replicaTicket.Save(); } if (!fileName.Contains(ReplicationNode.AllNodes)) transport.DeleteFile(fileName, worker); objectSpace.CommitChanges(); } } } catch (Exception exception) { objectSpace.Rollback(); worker.ReportError(Localizer.DownloadError, exception.Message); } finally { worker.ReportProgress(Localizer.CloseTransport, transport); transport.Close(); } } worker.ReportProgress(Color.Blue, Localizer.DownloadFinished); }
public static void InitializeDefaultSolution(IObjectSpace os) { var enumerable = ReflectionHelper.FindTypeDescendants(ReflectionHelper.FindTypeInfoByName(typeof(I单据编号).FullName)); var dictionary = os.GetObjects<单据编号方案>(null, true).ToDictionary(p => p.应用单据); foreach (ITypeInfo info2 in enumerable) { if (!info2.IsAbstract && info2.IsPersistent) { var key = info2.Type; 单据编号方案 i单据编号方案 = null; if (dictionary.ContainsKey(key)) { i单据编号方案 = dictionary[key]; } else { i单据编号方案 = os.CreateObject<单据编号方案>(); i单据编号方案.名称 = key.FullName; i单据编号方案.应用单据 = info2.Type; var item = os.CreateObject<单据编号自动编号规则>(); item.格式化字符串 = "00000"; i单据编号方案.编号规则.Add(item); dictionary.Add(key, i单据编号方案); } } } os.CommitChanges(); }
private object AuthenticateActiveDirectory(IObjectSpace objectSpace) { var windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity != null) { string userName = windowsIdentity.Name; var user = (IAuthenticationActiveDirectoryUser)objectSpace.FindObject(UserType, new BinaryOperator("UserName", userName)); if (user == null) { if (_createUserAutomatically) { var args = new CustomCreateUserEventArgs(objectSpace, userName); if (!args.Handled) { user = (IAuthenticationActiveDirectoryUser)objectSpace.CreateObject(UserType); user.UserName = userName; if (Security != null) { //Security.InitializeNewUser(objectSpace, user); Security.CallMethod("InitializeNewUser", new object[]{objectSpace, user}); } } objectSpace.CommitChanges(); } } if (user == null) { throw new AuthenticationException(userName); } return user; } return null; }
public static void CreateWMS(IObjectSpace os,bool deleteExist) { WMSPackage wms = new WMSPackage(os); wms.Create(deleteExist); wms.AutoRun(); os.CommitChanges(); }
public static void CreateSystemTypes(IObjectSpace ObjectSpace,IModelApplication app,bool deleteExists) { var objs = ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", false)); if (objs.Count > 0) return; ObjectSpace.Delete(objs); #region 系统类型 AddBusinessObject(typeof (单据<>), "单据<明细>", CreateNameSpace(typeof (单据<>).Namespace,ObjectSpace), "单据<明细>,继承自单据基类,支持将明细类型做为参数传入(内部使用泛型实现)", false,ObjectSpace); //AddBusinessObject(typeof (订单<>), "订单<明细>", CreateNameSpace(typeof (订单<>).Namespace, ObjectSpace), // "订单<明细>,继承自 单据<明细>基类 ,支持将明细类型做为参数传入(内部使用泛型实现),并支持各类订单类型的抽象实现.", false, ObjectSpace); //AddBusinessObject(typeof (仓库单据基类<>), "仓库单据基类<明细>", CreateNameSpace(typeof (仓库单据基类<>).Namespace,ObjectSpace), // "仓库单据基类<明细>,继承自 单据<明细>基类,支持将明细类型做为参数传入(内部使用泛型实现),并支持各类仓库类单据的抽象实现.", false,ObjectSpace); //AddBusinessObject(typeof (库存单据明细<>), "库存单据明细<单据>", CreateNameSpace(typeof (库存单据明细<>).Namespace,ObjectSpace), // "继承自库存流水,用于库存单据明细的基类,需要传入单据类型.", false,ObjectSpace); //AddBusinessObject(typeof (订单明细<>), "订单明细<订单>", CreateNameSpace(typeof (订单明细<>).Namespace,ObjectSpace), "可以与订单<订单明细>成对出现使用.",false,ObjectSpace); AddBusinessObject(typeof (明细<>), "明细<单据>", CreateNameSpace(typeof (明细<>).Namespace, ObjectSpace), "可以与单据<明细>成对继承使用.", false, ObjectSpace); //第一步,创建出所有基类类型 var exists = ObjectSpace.GetObjects<BusinessObjectBase>(null, true); foreach (var bom in app.BOModel) { if (!bom.TypeInfo.Type.IsGenericType && bom.TypeInfo.Type.Assembly.Location != AdmiralEnvironment.UserDefineBusinessFile.FullName) { var ns = CreateNameSpace(bom.TypeInfo.Type.Namespace, ObjectSpace); AddBusinessObject(bom.TypeInfo.Type, bom.Caption, ns, "", false, ObjectSpace); } } //第二步,创建这些类的属性,因为属性中可能使用了类型,所以先要创建类型. var bos = ObjectSpace.GetObjects<BusinessObject>(null, true); foreach (var bob in bos.Where(x => !x.IsRuntimeDefine)) { var type = ReflectionHelper.FindType(bob.FullName); if (type.BaseType != null && type.BaseType != typeof (object)) { var fullName = type.BaseType.Namespace + "." + type.BaseType.Name; var baseType = bos.SingleOrDefault(x => x.FullName == fullName); bob.Base = baseType; if (bob.Base == null) { Debug.WriteLine(type.FullName + "没有找到基类:" + fullName); } } if (type.IsGenericType) { bob.DisableCreateGenericParameterValues = true; foreach (var item in type.GetGenericArguments()) { var gp = ObjectSpace.CreateObject<GenericParameter>(); gp.Owner = bob; gp.Name = item.Name; if (item.IsGenericParameter) { gp.ParameterIndex = item.GenericParameterPosition; } else { } if (!string.IsNullOrEmpty(item.FullName)) gp.ParameterValue = exists.SingleOrDefault(x => x.FullName == item.FullName); var att = item.GetCustomAttributes(typeof (ItemTypeAttribute), false) .OfType<ItemTypeAttribute>() .FirstOrDefault(); if (att != null) { var gi = bos.SingleOrDefault(x => x.FullName == att.ItemType.FullName); gp.DefaultGenericType = gi; } } } var typeInfo = CaptionHelper.ApplicationModel.BOModel.GetClass(type); if (typeInfo != null && false) { foreach (var tim in typeInfo.OwnMembers) { if (tim.MemberInfo.IsAssociation) { var collectionMember = ObjectSpace.CreateObject<CollectionProperty>(); collectionMember.Owner = bob; collectionMember.Aggregated = tim.MemberInfo.IsAggregated; collectionMember.名称 = tim.Name; collectionMember.PropertyType = bos.SingleOrDefault(x => x.FullName == tim.Type.FullName); if (collectionMember.PropertyType == null) { Debug.WriteLine("没有找到属性类型:" + tim.Type.FullName); //throw new Exception("没有找到属性类型" + tim.Type.FullName); } } else { var member = ObjectSpace.CreateObject<Property>(); member.Owner = bob; member.名称 = tim.Name; member.PropertyType = exists.SingleOrDefault(x => x.FullName == tim.Type.FullName); member.Owner = bob; if (member.PropertyType == null) { Debug.WriteLine("没有找到属性类型:" + tim.Type.FullName); //throw new Exception("没有找到属性类型" + tim.Type.FullName); } } } } else { Debug.WriteLine("没有找到类型:" + type.FullName); } } //第三步,设置属性的关联属性,因为可能用到第二步中创建的属性,及,创建关系. foreach (var bob in bos.Where(x => !x.IsRuntimeDefine)) { if (bob.CollectionProperties.Count > 0) { var type = ReflectionHelper.FindType(bob.FullName); var typeInfo = CaptionHelper.ApplicationModel.BOModel.GetClass(type); foreach (var cp in bob.CollectionProperties) { var mi = typeInfo.FindMember(cp.名称); cp.RelationProperty = cp.PropertyType.FindProperty(mi.MemberInfo.AssociatedMemberInfo.Name); } } } #endregion ObjectSpace.CommitChanges(); }
protected virtual void OnRequestProcessed(IObjectSpace objectSpace, ObjectChangedXpoStartWorkflowRequest request) { objectSpace.Delete(request); objectSpace.CommitChanges(); }
/// <summary> /// Commits the object space on load. /// </summary> /// <param name="objectSpace">The object space.</param> /// <param name="activeObjectSpaces">The active object spaces.</param> private void commitObjectSpaceOnLoad(IObjectSpace objectSpace, Dictionary<Guid, IObjectSpace> activeObjectSpaces) { var children = from s in activeObjectSpaces.Values where s is NestedObjectSpace && ((NestedObjectSpace) s).ParentObjectSpace == objectSpace select s; foreach (var child in children) commitObjectSpaceOnLoad(child, activeObjectSpaces); var newMaps = from c in objectSpace.ModifiedObjects.Cast<object>() where c is OidMap && ((OidMap) c).NewObject != null select c as OidMap; objectSpace.CommitChanges(); newMaps.ToList().ForEach(x => x.FixReference()); objectSpace.CommitChanges(); objectSpace.Dispose(); var sessionId = (from a in activeObjectSpaces where a.Value == objectSpace select a.Key).FirstOrDefault(); activeObjectSpaces.Remove(sessionId); }
public static void MassUpdateDataType(IObjectSpace objectSpace, string oldDataType, Type newDataType) { foreach (ReportData reportData in objectSpace.GetObjects<ReportData>(new BinaryOperator("dataTypeName", oldDataType))) { XafReport report = reportData.LoadXtraReport(objectSpace); report.DataType = newDataType; reportData.SaveXtraReport(report); } objectSpace.CommitChanges(); }
public void Process(XafApplication application,IObjectSpace objectSpace) { var user = objectSpace.FindObject(XpandModuleBase.UserType, CriteriaOperator.Parse("Email = ?", Email)) as IAuthenticationStandardUser; if (user == null) throw new ArgumentException("Cannot find registered users by the provided email address!"); User = user; var randomBytes = new byte[6]; new RNGCryptoServiceProvider().GetBytes(randomBytes); Password = Convert.ToBase64String(randomBytes); user.SetPassword(Password); user.ChangePasswordOnFirstLogon = true; objectSpace.CommitChanges(); }
public InitWMSDataController() { this.components = new System.ComponentModel.Container(); this.TargetWindowType = WindowType.Main; var initData = new SimpleAction(this.components); initData.Category = "Tools"; initData.Caption = "生成默认数据"; initData.Id = "InitData"; initData.Execute += (snd, e) => { ObjectSpace = Application.CreateObjectSpace(); var inited = ObjectSpace.GetObjectsCount(typeof(产品), null) > 0; var tdch = new CIIP.Module.DatabaseUpdate.TestDataGeneratorHelper(); if (!inited) { var t = CreateUnit("台"); var g = CreateUnit("个"); CreateProduct("Surface 3 64G 2G", t, 2000, 2999); CreateProduct("Surface 3 128G 4G", t, 2000, 4888); CreateProduct("Surface Pro 3 I3 64G 4G", t, 3000, 4499); CreateProduct("Surface Pro 3 I5 128G 4G", t, 4500, 5699); CreateProduct("Surface Pro 3 I5 256G 8G", t, 6388, 6999); CreateProduct("Surface Pro 3 I7 256G 8G", t, 7000, 8888); CreateProduct("Surface Pro 3 I7 512G 8G", t, 8000, 9999); CreateProduct("Surface Pro 4 CoreM 128G 8G", t, 5688, 6688); CreateProduct("Surface Pro 4 I5 128G 8G", t, 6388, 7388); CreateProduct("Surface Pro 4 I5 256G 8G", t, 6388, 9688); CreateProduct("Surface Pro 4 I7 256G 16G", t, 6388, 13388); CreateProduct("Surface Notebook I5 128G 8G", t, 10000, 11088); CreateProduct("Surface Notebook I5 256G 16G", t, 10000, 14088); CreateProduct("Surface Notebook I7 256G 16G", t, 13000, 15588); CreateProduct("Surface Notebook I7 512G 16G", t, 15000, 20088); var microsoft = CreateCompany("Microsoft", "比尔.盖茨", "13800001111", "徐家汇", true, true); var google = CreateCompany("Google", "拉里·佩奇", "13988881111", "徐家汇", true, true); var baidu = CreateCompany("Baidu", "李彦宏", "13900001111", "陆家嘴", true, true); var tencent = CreateCompany("Tencent", "15912111211", "马化腾", "陆家嘴", true, true); var ali = CreateCompany("Alibaba", "15612121212", "马云", "陆家嘴", true, true); //500个客户 } var area = ObjectSpace.FindObject<省份>(null); if (area == null) { var js = CreateSF("江苏"); CreateCity(js, "苏州", "姑苏区,相城区,吴中区,虎丘区,工业园区,吴江区,张家港市,常熟市,太仓巿,昆山市"); CreateCity(js, "南京", "鼓楼区,白下区,玄武区,秦淮区,建邺区,下关区,雨花台区,栖霞区,高淳县,溧水县,六合区,浦口区,江宁区"); var tjs = CreateSF("天津"); CreateCity(tjs, "天津", "和平区,河东区,河西区,南开区,河北区,红桥区,滨海新区,东丽区,西青区,津南区,北辰区,武清区,宝坻区,宁河区,静海区,蓟县"); var cqs = CreateSF("重庆"); CreateCity(cqs, "重庆", "渝中区,大渡口区,江北区,沙坪坝区,九龙坡区,南岸区,北碚区,渝北区,巴南区,涪陵区,綦江区,大足区,长寿区,江津区,合川区,永川区,南川区,璧山区,铜梁区,潼南区,荣昌区,万州区,梁平县,城口县,丰都县,垫江县,忠县,开县,云阳县,奉节县,巫山县,巫溪县,黔江区,武隆县,石柱土家族自治县,秀山土家族苗族自治县,酉阳土家族苗族自治县,彭水苗族土家族自治县"); var zjs = CreateSF("浙江"); CreateCity(zjs, "杭州", "市区,上城区,下城区,江干区,拱墅区,西湖区,滨江区,萧山区,余杭区,富阳区,桐庐县,淳安县,建德市,临安市"); var scs = CreateSF("四川"); CreateCity(scs, "成都", "武侯区,锦江区,青羊区,金牛区,成华区,龙泉驿区,温江区,新都区,青白江区,双流区,郫县,蒲江县,大邑县,金堂县,新津县,都江堰市,彭州市,邛崃市,崇州市"); var gds = CreateSF("广东"); CreateCity(gds, "广州", "越秀区,荔湾区,海珠区,天河区,白云区,黄埔区,番禺区,花都区,南沙区,增城区,从化区"); var szs = CreateSF("深圳"); CreateCity(szs, "深圳", "福田区,罗湖区,南山区,盐田区,宝安区,龙岗区"); var shs = CreateSF("上海"); CreateCity(shs, "上海", "黄浦区,浦东新区,徐汇区,长宁区,静安区,普陀区,虹口区,杨浦区,闵行区,宝山区,嘉定区,金山区,松江区,青浦区,奉贤区,崇明县"); var bjs = CreateSF("北京"); CreateCity(bjs, "北京", "东城区,西城区,海淀区,朝阳区,丰台区,石景山区,门头沟区,通州区,顺义区,房山区,大兴区,昌平区,怀柔区,平谷区,密云区,延庆区"); ObjectSpace.CommitChanges(); var s = ObjectSpace.GetObjects<销售区域>(); var customers = tdch.GetRandomNames(500); var rnd = new Random(); foreach (var customer in customers) { CreateCompany(customer, customer, "13900005555", "中国", false, true, s[rnd.Next(s.Count - 1)]); } } }; this.Actions.Add(initData); this.RegisterActions(this.components); // Target required Views (via the TargetXXX properties) and create their Actions. }
public static void AddTag(ITaggedDataObject dataObject, IObjectSpace os, String name) { ITag tag = os.GetObjects<ITag>(CriteriaOperator.Parse("Name = ?", name)).FirstOrDefault(); if (tag == null) { tag = os.CreateObject<ITag>(); tag.Name = name; os.CommitChanges(); } IObjectTag objectTag = dataObject.Tags.FirstOrDefault(tmp => tmp.Tag == tag); if (objectTag == null) { objectTag = os.CreateObject<IObjectTag>(); objectTag.Tag = tag; dataObject.Tags.Add(objectTag); } }
/// <summary> /// Метод создает в БД новое обследование /// </summary> private IExamination CreateNewExamination(IObjectSpace os, IPatient patient, Guid id, ExaminationType type = null, bool allowEmptyFile = false) { IExamination examination = os.CreateObject<IExamination>(); examination.ExaminationSoftType = os.FindObject<ExaminationSoftType>(CriteriaOperator.Parse("ExaminationSoftTypeId = ?", id)); examination.Patient = os.GetObject<IPatient>(patient); examination.AllowEmptyOrNotExistsFile = allowEmptyFile; examination.TimeStart = DateTime.Now; // Создается новое обследование поэтому файла еще нет if (examination.ExaminationFile == null) { // заводим в базе файл //examination.ExaminationFile = os.CreateObject<FileSystemStoreObject>(); examination.ExaminationFile = os.CreateObject<ExaminationFile>(); examination.ExaminationFile.OwnerId = (examination as DevExpress.ExpressApp.DC.DCBaseObject).Oid; if (type != null) { examination.ExaminationType = os.GetObjectByKey<ExaminationType>(type.Oid); //FindObject<ExaminationType>(CriteriaOperator.Parse("ExaminationTypeId = ?", type.)); } // Применяем изменения os.CommitChanges(); if (String.IsNullOrEmpty(examination.ObjectCode) == false) { string fileName = examination.ObjectCode; string fileExtension = examination.ExaminationSoftType.ExaminationFileExtension; examination.ExaminationFile.FileName = Converters.GetFileNameWithoutInvalidChars(fileName, fileExtension); } else throw new Exception("Examination invalid params"); } os.CommitChanges(); // здесь создается пустой файл обследования while (os.IsCommitting) { Thread.Sleep(1000); } // ждем пока применятся изменения, не знаю зачем... //// Заполняем созданный файл заключения //// !!! ЗАПОЛНЯТЬ ЗАКЛЮЧЕНИЕ ПРИ СОЗДАНИИ НЕ НАДО !!! //ConclusionViewController conclusionController = Frame.GetController<ConclusionViewController>(); //if (conclusionController != null) //{ // conclusionController.PopulateConclusionFile(examination); //} return examination; }